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/output_surface.h"
28 #include "cc/output/render_surface_filters.h"
29 #include "cc/output/static_geometry_binding.h"
30 #include "cc/quads/draw_polygon.h"
31 #include "cc/quads/picture_draw_quad.h"
32 #include "cc/quads/render_pass.h"
33 #include "cc/quads/stream_video_draw_quad.h"
34 #include "cc/quads/texture_draw_quad.h"
35 #include "cc/resources/layer_quad.h"
36 #include "cc/resources/scoped_gpu_raster.h"
37 #include "cc/resources/scoped_resource.h"
38 #include "cc/resources/texture_mailbox_deleter.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/SkGrTexturePixelRef.h"
51 #include "third_party/skia/include/gpu/gl/GrGLInterface.h"
52 #include "ui/gfx/geometry/quad_f.h"
53 #include "ui/gfx/geometry/rect_conversions.h"
55 using gpu::gles2::GLES2Interface
;
60 bool NeedsIOSurfaceReadbackWorkaround() {
61 #if defined(OS_MACOSX)
62 // This isn't strictly required in DumpRenderTree-mode when Mesa is used,
63 // but it doesn't seem to hurt.
70 Float4
UVTransform(const TextureDrawQuad
* quad
) {
71 gfx::PointF uv0
= quad
->uv_top_left
;
72 gfx::PointF uv1
= quad
->uv_bottom_right
;
73 Float4 xform
= {{uv0
.x(), uv0
.y(), uv1
.x() - uv0
.x(), uv1
.y() - uv0
.y()}};
75 xform
.data
[1] = 1.0f
- xform
.data
[1];
76 xform
.data
[3] = -xform
.data
[3];
81 Float4
PremultipliedColor(SkColor color
) {
82 const float factor
= 1.0f
/ 255.0f
;
83 const float alpha
= SkColorGetA(color
) * factor
;
86 {SkColorGetR(color
) * factor
* alpha
, SkColorGetG(color
) * factor
* alpha
,
87 SkColorGetB(color
) * factor
* alpha
, alpha
}};
91 SamplerType
SamplerTypeFromTextureTarget(GLenum target
) {
94 return SAMPLER_TYPE_2D
;
95 case GL_TEXTURE_RECTANGLE_ARB
:
96 return SAMPLER_TYPE_2D_RECT
;
97 case GL_TEXTURE_EXTERNAL_OES
:
98 return SAMPLER_TYPE_EXTERNAL_OES
;
101 return SAMPLER_TYPE_2D
;
105 BlendMode
BlendModeFromSkXfermode(SkXfermode::Mode mode
) {
107 case SkXfermode::kSrcOver_Mode
:
108 return BLEND_MODE_NORMAL
;
109 case SkXfermode::kScreen_Mode
:
110 return BLEND_MODE_SCREEN
;
111 case SkXfermode::kOverlay_Mode
:
112 return BLEND_MODE_OVERLAY
;
113 case SkXfermode::kDarken_Mode
:
114 return BLEND_MODE_DARKEN
;
115 case SkXfermode::kLighten_Mode
:
116 return BLEND_MODE_LIGHTEN
;
117 case SkXfermode::kColorDodge_Mode
:
118 return BLEND_MODE_COLOR_DODGE
;
119 case SkXfermode::kColorBurn_Mode
:
120 return BLEND_MODE_COLOR_BURN
;
121 case SkXfermode::kHardLight_Mode
:
122 return BLEND_MODE_HARD_LIGHT
;
123 case SkXfermode::kSoftLight_Mode
:
124 return BLEND_MODE_SOFT_LIGHT
;
125 case SkXfermode::kDifference_Mode
:
126 return BLEND_MODE_DIFFERENCE
;
127 case SkXfermode::kExclusion_Mode
:
128 return BLEND_MODE_EXCLUSION
;
129 case SkXfermode::kMultiply_Mode
:
130 return BLEND_MODE_MULTIPLY
;
131 case SkXfermode::kHue_Mode
:
132 return BLEND_MODE_HUE
;
133 case SkXfermode::kSaturation_Mode
:
134 return BLEND_MODE_SATURATION
;
135 case SkXfermode::kColor_Mode
:
136 return BLEND_MODE_COLOR
;
137 case SkXfermode::kLuminosity_Mode
:
138 return BLEND_MODE_LUMINOSITY
;
141 return BLEND_MODE_NONE
;
145 // Smallest unit that impact anti-aliasing output. We use this to
146 // determine when anti-aliasing is unnecessary.
147 const float kAntiAliasingEpsilon
= 1.0f
/ 1024.0f
;
149 // Block or crash if the number of pending sync queries reach this high as
150 // something is seriously wrong on the service side if this happens.
151 const size_t kMaxPendingSyncQueries
= 16;
153 } // anonymous namespace
155 static GLint
GetActiveTextureUnit(GLES2Interface
* gl
) {
156 GLint active_unit
= 0;
157 gl
->GetIntegerv(GL_ACTIVE_TEXTURE
, &active_unit
);
161 class GLRenderer::ScopedUseGrContext
{
163 static scoped_ptr
<ScopedUseGrContext
> Create(GLRenderer
* renderer
,
164 DrawingFrame
* frame
) {
165 return make_scoped_ptr(new ScopedUseGrContext(renderer
, frame
));
168 ~ScopedUseGrContext() {
169 // Pass context control back to GLrenderer.
170 scoped_gpu_raster_
= nullptr;
171 renderer_
->RestoreGLState();
172 renderer_
->RestoreFramebuffer(frame_
);
175 GrContext
* context() const {
176 return renderer_
->output_surface_
->context_provider()->GrContext();
180 ScopedUseGrContext(GLRenderer
* renderer
, DrawingFrame
* frame
)
181 : scoped_gpu_raster_(
182 new ScopedGpuRaster(renderer
->output_surface_
->context_provider())),
185 // scoped_gpu_raster_ passes context control to Skia.
188 scoped_ptr
<ScopedGpuRaster
> scoped_gpu_raster_
;
189 GLRenderer
* renderer_
;
190 DrawingFrame
* frame_
;
192 DISALLOW_COPY_AND_ASSIGN(ScopedUseGrContext
);
195 struct GLRenderer::PendingAsyncReadPixels
{
196 PendingAsyncReadPixels() : buffer(0) {}
198 scoped_ptr
<CopyOutputRequest
> copy_request
;
199 base::CancelableClosure finished_read_pixels_callback
;
203 DISALLOW_COPY_AND_ASSIGN(PendingAsyncReadPixels
);
206 class GLRenderer::SyncQuery
{
208 explicit SyncQuery(gpu::gles2::GLES2Interface
* gl
)
209 : gl_(gl
), query_id_(0u), is_pending_(false), weak_ptr_factory_(this) {
210 gl_
->GenQueriesEXT(1, &query_id_
);
212 virtual ~SyncQuery() { gl_
->DeleteQueriesEXT(1, &query_id_
); }
214 scoped_refptr
<ResourceProvider::Fence
> Begin() {
215 DCHECK(!IsPending());
216 // Invalidate weak pointer held by old fence.
217 weak_ptr_factory_
.InvalidateWeakPtrs();
218 // Note: In case the set of drawing commands issued before End() do not
219 // depend on the query, defer BeginQueryEXT call until Set() is called and
220 // query is required.
221 return make_scoped_refptr
<ResourceProvider::Fence
>(
222 new Fence(weak_ptr_factory_
.GetWeakPtr()));
229 // Note: BeginQueryEXT on GL_COMMANDS_COMPLETED_CHROMIUM is effectively a
230 // noop relative to GL, so it doesn't matter where it happens but we still
231 // make sure to issue this command when Set() is called (prior to issuing
232 // any drawing commands that depend on query), in case some future extension
233 // can take advantage of this.
234 gl_
->BeginQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
, query_id_
);
242 gl_
->EndQueryEXT(GL_COMMANDS_COMPLETED_CHROMIUM
);
249 unsigned result_available
= 1;
250 gl_
->GetQueryObjectuivEXT(
251 query_id_
, GL_QUERY_RESULT_AVAILABLE_EXT
, &result_available
);
252 is_pending_
= !result_available
;
261 gl_
->GetQueryObjectuivEXT(query_id_
, GL_QUERY_RESULT_EXT
, &result
);
266 class Fence
: public ResourceProvider::Fence
{
268 explicit Fence(base::WeakPtr
<GLRenderer::SyncQuery
> query
)
271 // Overridden from ResourceProvider::Fence:
272 void Set() override
{
276 bool HasPassed() override
{ return !query_
|| !query_
->IsPending(); }
277 void Wait() override
{
285 base::WeakPtr
<SyncQuery
> query_
;
287 DISALLOW_COPY_AND_ASSIGN(Fence
);
290 gpu::gles2::GLES2Interface
* gl_
;
293 base::WeakPtrFactory
<SyncQuery
> weak_ptr_factory_
;
295 DISALLOW_COPY_AND_ASSIGN(SyncQuery
);
298 scoped_ptr
<GLRenderer
> GLRenderer::Create(
299 RendererClient
* client
,
300 const RendererSettings
* settings
,
301 OutputSurface
* output_surface
,
302 ResourceProvider
* resource_provider
,
303 TextureMailboxDeleter
* texture_mailbox_deleter
,
304 int highp_threshold_min
) {
305 return make_scoped_ptr(new GLRenderer(client
,
309 texture_mailbox_deleter
,
310 highp_threshold_min
));
313 GLRenderer::GLRenderer(RendererClient
* client
,
314 const RendererSettings
* settings
,
315 OutputSurface
* output_surface
,
316 ResourceProvider
* resource_provider
,
317 TextureMailboxDeleter
* texture_mailbox_deleter
,
318 int highp_threshold_min
)
319 : DirectRenderer(client
, settings
, output_surface
, resource_provider
),
320 offscreen_framebuffer_id_(0),
321 shared_geometry_quad_(QuadVertexRect()),
322 gl_(output_surface
->context_provider()->ContextGL()),
323 context_support_(output_surface
->context_provider()->ContextSupport()),
324 texture_mailbox_deleter_(texture_mailbox_deleter
),
325 is_backbuffer_discarded_(false),
326 is_scissor_enabled_(false),
327 scissor_rect_needs_reset_(true),
328 stencil_shadow_(false),
329 blend_shadow_(false),
330 highp_threshold_min_(highp_threshold_min
),
331 highp_threshold_cache_(0),
332 use_sync_query_(false),
333 on_demand_tile_raster_resource_id_(0),
334 bound_geometry_(NO_BINDING
) {
336 DCHECK(context_support_
);
338 ContextProvider::Capabilities context_caps
=
339 output_surface_
->context_provider()->ContextCapabilities();
341 capabilities_
.using_partial_swap
=
342 settings_
->partial_swap_enabled
&& context_caps
.gpu
.post_sub_buffer
;
344 DCHECK(!context_caps
.gpu
.iosurface
|| context_caps
.gpu
.texture_rectangle
);
346 capabilities_
.using_egl_image
= context_caps
.gpu
.egl_image_external
;
348 capabilities_
.max_texture_size
= resource_provider_
->max_texture_size();
349 capabilities_
.best_texture_format
= resource_provider_
->best_texture_format();
351 // The updater can access textures while the GLRenderer is using them.
352 capabilities_
.allow_partial_texture_updates
= true;
354 capabilities_
.using_image
= context_caps
.gpu
.image
;
356 capabilities_
.using_discard_framebuffer
=
357 context_caps
.gpu
.discard_framebuffer
;
359 capabilities_
.allow_rasterize_on_demand
= true;
361 use_sync_query_
= context_caps
.gpu
.sync_query
;
362 use_blend_equation_advanced_
= context_caps
.gpu
.blend_equation_advanced
;
363 use_blend_equation_advanced_coherent_
=
364 context_caps
.gpu
.blend_equation_advanced_coherent
;
366 InitializeSharedObjects();
369 GLRenderer::~GLRenderer() {
370 while (!pending_async_read_pixels_
.empty()) {
371 PendingAsyncReadPixels
* pending_read
= pending_async_read_pixels_
.back();
372 pending_read
->finished_read_pixels_callback
.Cancel();
373 pending_async_read_pixels_
.pop_back();
376 in_use_overlay_resources_
.clear();
378 CleanupSharedObjects();
381 const RendererCapabilitiesImpl
& GLRenderer::Capabilities() const {
382 return capabilities_
;
385 void GLRenderer::DidChangeVisibility() {
386 EnforceMemoryPolicy();
388 context_support_
->SetSurfaceVisible(visible());
391 void GLRenderer::ReleaseRenderPassTextures() { render_pass_textures_
.clear(); }
393 void GLRenderer::DiscardPixels() {
394 if (!capabilities_
.using_discard_framebuffer
)
396 bool using_default_framebuffer
=
397 !current_framebuffer_lock_
&&
398 output_surface_
->capabilities().uses_default_gl_framebuffer
;
399 GLenum attachments
[] = {static_cast<GLenum
>(
400 using_default_framebuffer
? GL_COLOR_EXT
: GL_COLOR_ATTACHMENT0_EXT
)};
401 gl_
->DiscardFramebufferEXT(
402 GL_FRAMEBUFFER
, arraysize(attachments
), attachments
);
405 void GLRenderer::PrepareSurfaceForPass(
407 SurfaceInitializationMode initialization_mode
,
408 const gfx::Rect
& render_pass_scissor
) {
411 switch (initialization_mode
) {
412 case SURFACE_INITIALIZATION_MODE_PRESERVE
:
413 EnsureScissorTestDisabled();
415 case SURFACE_INITIALIZATION_MODE_FULL_SURFACE_CLEAR
:
416 EnsureScissorTestDisabled();
418 ClearFramebuffer(frame
);
420 case SURFACE_INITIALIZATION_MODE_SCISSORED_CLEAR
:
421 SetScissorTestRect(render_pass_scissor
);
422 ClearFramebuffer(frame
);
427 void GLRenderer::ClearFramebuffer(DrawingFrame
* frame
) {
428 // On DEBUG builds, opaque render passes are cleared to blue to easily see
429 // regions that were not drawn on the screen.
430 if (frame
->current_render_pass
->has_transparent_background
)
431 gl_
->ClearColor(0, 0, 0, 0);
433 gl_
->ClearColor(0, 0, 1, 1);
435 bool always_clear
= false;
439 if (always_clear
|| frame
->current_render_pass
->has_transparent_background
) {
440 GLbitfield clear_bits
= GL_COLOR_BUFFER_BIT
;
442 clear_bits
|= GL_STENCIL_BUFFER_BIT
;
443 gl_
->Clear(clear_bits
);
447 static ResourceProvider::ResourceId
WaitOnResourceSyncPoints(
448 ResourceProvider
* resource_provider
,
449 ResourceProvider::ResourceId resource_id
) {
450 resource_provider
->WaitSyncPointIfNeeded(resource_id
);
454 void GLRenderer::BeginDrawingFrame(DrawingFrame
* frame
) {
455 TRACE_EVENT0("cc", "GLRenderer::BeginDrawingFrame");
457 scoped_refptr
<ResourceProvider::Fence
> read_lock_fence
;
458 if (use_sync_query_
) {
459 // Block until oldest sync query has passed if the number of pending queries
460 // ever reach kMaxPendingSyncQueries.
461 if (pending_sync_queries_
.size() >= kMaxPendingSyncQueries
) {
462 LOG(ERROR
) << "Reached limit of pending sync queries.";
464 pending_sync_queries_
.front()->Wait();
465 DCHECK(!pending_sync_queries_
.front()->IsPending());
468 while (!pending_sync_queries_
.empty()) {
469 if (pending_sync_queries_
.front()->IsPending())
472 available_sync_queries_
.push_back(pending_sync_queries_
.take_front());
475 current_sync_query_
= available_sync_queries_
.empty()
476 ? make_scoped_ptr(new SyncQuery(gl_
))
477 : available_sync_queries_
.take_front();
479 read_lock_fence
= current_sync_query_
->Begin();
482 make_scoped_refptr(new ResourceProvider::SynchronousFence(gl_
));
484 resource_provider_
->SetReadLockFence(read_lock_fence
.get());
486 // Insert WaitSyncPointCHROMIUM on quad resources prior to drawing the frame,
487 // so that drawing can proceed without GL context switching interruptions.
488 DrawQuad::ResourceIteratorCallback wait_on_resource_syncpoints_callback
=
489 base::Bind(&WaitOnResourceSyncPoints
, resource_provider_
);
491 for (const auto& pass
: *frame
->render_passes_in_draw_order
) {
492 for (const auto& quad
: pass
->quad_list
)
493 quad
->IterateResources(wait_on_resource_syncpoints_callback
);
496 // TODO(enne): Do we need to reinitialize all of this state per frame?
497 ReinitializeGLState();
500 void GLRenderer::DoNoOp() {
501 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0);
505 void GLRenderer::DoDrawQuad(DrawingFrame
* frame
,
506 const DrawQuad
* quad
,
507 const gfx::QuadF
* clip_region
) {
508 DCHECK(quad
->rect
.Contains(quad
->visible_rect
));
509 if (quad
->material
!= DrawQuad::TEXTURE_CONTENT
) {
510 FlushTextureQuadCache(SHARED_BINDING
);
513 switch (quad
->material
) {
514 case DrawQuad::INVALID
:
517 case DrawQuad::CHECKERBOARD
:
518 DrawCheckerboardQuad(frame
, CheckerboardDrawQuad::MaterialCast(quad
),
521 case DrawQuad::DEBUG_BORDER
:
522 DrawDebugBorderQuad(frame
, DebugBorderDrawQuad::MaterialCast(quad
));
524 case DrawQuad::IO_SURFACE_CONTENT
:
525 DrawIOSurfaceQuad(frame
, IOSurfaceDrawQuad::MaterialCast(quad
),
528 case DrawQuad::PICTURE_CONTENT
:
529 // PictureDrawQuad should only be used for resourceless software draws.
532 case DrawQuad::RENDER_PASS
:
533 DrawRenderPassQuad(frame
, RenderPassDrawQuad::MaterialCast(quad
),
536 case DrawQuad::SOLID_COLOR
:
537 DrawSolidColorQuad(frame
, SolidColorDrawQuad::MaterialCast(quad
),
540 case DrawQuad::STREAM_VIDEO_CONTENT
:
541 DrawStreamVideoQuad(frame
, StreamVideoDrawQuad::MaterialCast(quad
),
544 case DrawQuad::SURFACE_CONTENT
:
545 // Surface content should be fully resolved to other quad types before
546 // reaching a direct renderer.
549 case DrawQuad::TEXTURE_CONTENT
:
550 EnqueueTextureQuad(frame
, TextureDrawQuad::MaterialCast(quad
),
553 case DrawQuad::TILED_CONTENT
:
554 DrawTileQuad(frame
, TileDrawQuad::MaterialCast(quad
), clip_region
);
556 case DrawQuad::YUV_VIDEO_CONTENT
:
557 DrawYUVVideoQuad(frame
, YUVVideoDrawQuad::MaterialCast(quad
),
563 void GLRenderer::DrawCheckerboardQuad(const DrawingFrame
* frame
,
564 const CheckerboardDrawQuad
* quad
,
565 const gfx::QuadF
* clip_region
) {
566 // TODO(enne) For now since checkerboards shouldn't be part of a 3D
567 // context, clipping regions aren't supported so we skip drawing them
568 // if this becomes the case.
572 SetBlendEnabled(quad
->ShouldDrawWithBlending());
574 const TileCheckerboardProgram
* program
= GetTileCheckerboardProgram();
575 DCHECK(program
&& (program
->initialized() || IsContextLost()));
576 SetUseProgram(program
->program());
578 SkColor color
= quad
->color
;
579 gl_
->Uniform4f(program
->fragment_shader().color_location(),
580 SkColorGetR(color
) * (1.0f
/ 255.0f
),
581 SkColorGetG(color
) * (1.0f
/ 255.0f
),
582 SkColorGetB(color
) * (1.0f
/ 255.0f
), 1);
584 const int kCheckerboardWidth
= 16;
585 float frequency
= 1.0f
/ kCheckerboardWidth
;
587 gfx::Rect tile_rect
= quad
->rect
;
589 static_cast<int>(tile_rect
.x() / quad
->scale
) % kCheckerboardWidth
;
591 static_cast<int>(tile_rect
.y() / quad
->scale
) % kCheckerboardWidth
;
592 float tex_scale_x
= tile_rect
.width() / quad
->scale
;
593 float tex_scale_y
= tile_rect
.height() / quad
->scale
;
594 gl_
->Uniform4f(program
->fragment_shader().tex_transform_location(),
595 tex_offset_x
, tex_offset_y
, tex_scale_x
, tex_scale_y
);
597 gl_
->Uniform1f(program
->fragment_shader().frequency_location(), frequency
);
599 SetShaderOpacity(quad
->opacity(),
600 program
->fragment_shader().alpha_location());
601 DrawQuadGeometry(frame
,
602 quad
->quadTransform(),
604 program
->vertex_shader().matrix_location());
607 // This function does not handle 3D sorting right now, since the debug border
608 // quads are just drawn as their original quads and not in split pieces. This
609 // results in some debug border quads drawing over foreground quads.
610 void GLRenderer::DrawDebugBorderQuad(const DrawingFrame
* frame
,
611 const DebugBorderDrawQuad
* quad
) {
612 SetBlendEnabled(quad
->ShouldDrawWithBlending());
614 static float gl_matrix
[16];
615 const DebugBorderProgram
* program
= GetDebugBorderProgram();
616 DCHECK(program
&& (program
->initialized() || IsContextLost()));
617 SetUseProgram(program
->program());
619 // Use the full quad_rect for debug quads to not move the edges based on
621 gfx::Rect layer_rect
= quad
->rect
;
622 gfx::Transform render_matrix
;
623 QuadRectTransform(&render_matrix
, quad
->quadTransform(), layer_rect
);
624 GLRenderer::ToGLMatrix(&gl_matrix
[0],
625 frame
->projection_matrix
* render_matrix
);
626 gl_
->UniformMatrix4fv(program
->vertex_shader().matrix_location(), 1, false,
629 SkColor color
= quad
->color
;
630 float alpha
= SkColorGetA(color
) * (1.0f
/ 255.0f
);
632 gl_
->Uniform4f(program
->fragment_shader().color_location(),
633 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
634 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
635 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
637 gl_
->LineWidth(quad
->width
);
639 // The indices for the line are stored in the same array as the triangle
641 gl_
->DrawElements(GL_LINE_LOOP
, 4, GL_UNSIGNED_SHORT
, 0);
644 static skia::RefPtr
<SkImage
> ApplyImageFilter(
645 scoped_ptr
<GLRenderer::ScopedUseGrContext
> use_gr_context
,
646 ResourceProvider
* resource_provider
,
647 const gfx::Rect
& rect
,
648 const gfx::Vector2dF
& scale
,
649 SkImageFilter
* filter
,
650 ScopedResource
* source_texture_resource
) {
652 return skia::RefPtr
<SkImage
>();
655 return skia::RefPtr
<SkImage
>();
657 ResourceProvider::ScopedReadLockGL
lock(resource_provider
,
658 source_texture_resource
->id());
660 // Wrap the source texture in a Ganesh platform texture.
661 GrBackendTextureDesc backend_texture_description
;
662 backend_texture_description
.fWidth
= source_texture_resource
->size().width();
663 backend_texture_description
.fHeight
=
664 source_texture_resource
->size().height();
665 backend_texture_description
.fConfig
= kSkia8888_GrPixelConfig
;
666 backend_texture_description
.fTextureHandle
= lock
.texture_id();
667 backend_texture_description
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
668 skia::RefPtr
<GrTexture
> texture
=
669 skia::AdoptRef(use_gr_context
->context()->wrapBackendTexture(
670 backend_texture_description
));
672 TRACE_EVENT_INSTANT0("cc",
673 "ApplyImageFilter wrap background texture failed",
674 TRACE_EVENT_SCOPE_THREAD
);
675 return skia::RefPtr
<SkImage
>();
679 SkImageInfo::MakeN32Premul(source_texture_resource
->size().width(),
680 source_texture_resource
->size().height());
681 // Place the platform texture inside an SkBitmap.
683 source
.setInfo(info
);
684 skia::RefPtr
<SkGrPixelRef
> pixel_ref
=
685 skia::AdoptRef(new SkGrPixelRef(info
, texture
.get()));
686 source
.setPixelRef(pixel_ref
.get());
688 // Create a scratch texture for backing store.
690 desc
.fFlags
= kRenderTarget_GrTextureFlagBit
| kNoStencil_GrTextureFlagBit
;
692 desc
.fWidth
= source
.width();
693 desc
.fHeight
= source
.height();
694 desc
.fConfig
= kSkia8888_GrPixelConfig
;
695 desc
.fOrigin
= kBottomLeft_GrSurfaceOrigin
;
696 skia::RefPtr
<GrTexture
> backing_store
=
697 skia::AdoptRef(use_gr_context
->context()->refScratchTexture(
698 desc
, GrContext::kExact_ScratchTexMatch
));
699 if (!backing_store
) {
700 TRACE_EVENT_INSTANT0("cc",
701 "ApplyImageFilter scratch texture allocation failed",
702 TRACE_EVENT_SCOPE_THREAD
);
703 return skia::RefPtr
<SkImage
>();
706 // Create surface to draw into.
707 skia::RefPtr
<SkSurface
> surface
= skia::AdoptRef(
708 SkSurface::NewRenderTargetDirect(backing_store
->asRenderTarget()));
709 skia::RefPtr
<SkCanvas
> canvas
= skia::SharePtr(surface
->getCanvas());
711 // Draw the source bitmap through the filter to the canvas.
713 paint
.setImageFilter(filter
);
714 canvas
->clear(SK_ColorTRANSPARENT
);
716 // The origin of the filter is top-left and the origin of the source is
717 // bottom-left, but the orientation is the same, so we must translate the
718 // filter so that it renders at the bottom of the texture to avoid
720 int y_translate
= source
.height() - rect
.height() - rect
.origin().y();
721 canvas
->translate(-rect
.origin().x(), y_translate
);
722 canvas
->scale(scale
.x(), scale
.y());
723 canvas
->drawSprite(source
, 0, 0, &paint
);
725 skia::RefPtr
<SkImage
> image
= skia::AdoptRef(surface
->newImageSnapshot());
726 if (!image
|| !image
->getTexture()) {
727 return skia::RefPtr
<SkImage
>();
730 // Flush the GrContext to ensure all buffered GL calls are drawn to the
731 // backing store before we access and return it, and have cc begin using the
738 bool GLRenderer::CanApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
739 return use_blend_equation_advanced_
||
740 blend_mode
== SkXfermode::kScreen_Mode
||
741 blend_mode
== SkXfermode::kSrcOver_Mode
;
744 void GLRenderer::ApplyBlendModeUsingBlendFunc(SkXfermode::Mode blend_mode
) {
745 DCHECK(CanApplyBlendModeUsingBlendFunc(blend_mode
));
747 // Any modes set here must be reset in RestoreBlendFuncToDefault
748 if (use_blend_equation_advanced_
) {
749 GLenum equation
= GL_FUNC_ADD
;
751 switch (blend_mode
) {
752 case SkXfermode::kScreen_Mode
:
753 equation
= GL_SCREEN_KHR
;
755 case SkXfermode::kOverlay_Mode
:
756 equation
= GL_OVERLAY_KHR
;
758 case SkXfermode::kDarken_Mode
:
759 equation
= GL_DARKEN_KHR
;
761 case SkXfermode::kLighten_Mode
:
762 equation
= GL_LIGHTEN_KHR
;
764 case SkXfermode::kColorDodge_Mode
:
765 equation
= GL_COLORDODGE_KHR
;
767 case SkXfermode::kColorBurn_Mode
:
768 equation
= GL_COLORBURN_KHR
;
770 case SkXfermode::kHardLight_Mode
:
771 equation
= GL_HARDLIGHT_KHR
;
773 case SkXfermode::kSoftLight_Mode
:
774 equation
= GL_SOFTLIGHT_KHR
;
776 case SkXfermode::kDifference_Mode
:
777 equation
= GL_DIFFERENCE_KHR
;
779 case SkXfermode::kExclusion_Mode
:
780 equation
= GL_EXCLUSION_KHR
;
782 case SkXfermode::kMultiply_Mode
:
783 equation
= GL_MULTIPLY_KHR
;
785 case SkXfermode::kHue_Mode
:
786 equation
= GL_HSL_HUE_KHR
;
788 case SkXfermode::kSaturation_Mode
:
789 equation
= GL_HSL_SATURATION_KHR
;
791 case SkXfermode::kColor_Mode
:
792 equation
= GL_HSL_COLOR_KHR
;
794 case SkXfermode::kLuminosity_Mode
:
795 equation
= GL_HSL_LUMINOSITY_KHR
;
801 gl_
->BlendEquation(equation
);
803 if (blend_mode
== SkXfermode::kScreen_Mode
) {
804 gl_
->BlendFunc(GL_ONE_MINUS_DST_COLOR
, GL_ONE
);
809 void GLRenderer::RestoreBlendFuncToDefault(SkXfermode::Mode blend_mode
) {
810 if (blend_mode
== SkXfermode::kSrcOver_Mode
)
813 if (use_blend_equation_advanced_
) {
814 gl_
->BlendEquation(GL_FUNC_ADD
);
816 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
820 bool GLRenderer::ShouldApplyBackgroundFilters(DrawingFrame
* frame
,
821 const RenderPassDrawQuad
* quad
) {
822 if (quad
->background_filters
.IsEmpty())
825 // TODO(danakj): We only allow background filters on an opaque render surface
826 // because other surfaces may contain translucent pixels, and the contents
827 // behind those translucent pixels wouldn't have the filter applied.
828 if (frame
->current_render_pass
->has_transparent_background
)
831 // TODO(ajuma): Add support for reference filters once
832 // FilterOperations::GetOutsets supports reference filters.
833 if (quad
->background_filters
.HasReferenceFilter())
838 // This takes a gfx::Rect and a clip region quad in the same space,
839 // and returns a quad with the same proportions in the space -0.5->0.5.
840 bool GetScaledRegion(const gfx::Rect
& rect
,
841 const gfx::QuadF
* clip
,
842 gfx::QuadF
* scaled_region
) {
846 gfx::PointF
p1(((clip
->p1().x() - rect
.x()) / rect
.width()) - 0.5f
,
847 ((clip
->p1().y() - rect
.y()) / rect
.height()) - 0.5f
);
848 gfx::PointF
p2(((clip
->p2().x() - rect
.x()) / rect
.width()) - 0.5f
,
849 ((clip
->p2().y() - rect
.y()) / rect
.height()) - 0.5f
);
850 gfx::PointF
p3(((clip
->p3().x() - rect
.x()) / rect
.width()) - 0.5f
,
851 ((clip
->p3().y() - rect
.y()) / rect
.height()) - 0.5f
);
852 gfx::PointF
p4(((clip
->p4().x() - rect
.x()) / rect
.width()) - 0.5f
,
853 ((clip
->p4().y() - rect
.y()) / rect
.height()) - 0.5f
);
854 *scaled_region
= gfx::QuadF(p1
, p2
, p3
, p4
);
858 // This takes a gfx::Rect and a clip region quad in the same space,
859 // and returns the proportional uv's in the space 0->1.
860 bool GetScaledUVs(const gfx::Rect
& rect
, const gfx::QuadF
* clip
, float uvs
[8]) {
864 uvs
[0] = ((clip
->p1().x() - rect
.x()) / rect
.width());
865 uvs
[1] = ((clip
->p1().y() - rect
.y()) / rect
.height());
866 uvs
[2] = ((clip
->p2().x() - rect
.x()) / rect
.width());
867 uvs
[3] = ((clip
->p2().y() - rect
.y()) / rect
.height());
868 uvs
[4] = ((clip
->p3().x() - rect
.x()) / rect
.width());
869 uvs
[5] = ((clip
->p3().y() - rect
.y()) / rect
.height());
870 uvs
[6] = ((clip
->p4().x() - rect
.x()) / rect
.width());
871 uvs
[7] = ((clip
->p4().y() - rect
.y()) / rect
.height());
875 gfx::Rect
GLRenderer::GetBackdropBoundingBoxForRenderPassQuad(
877 const RenderPassDrawQuad
* quad
,
878 const gfx::Transform
& contents_device_transform
,
879 const gfx::QuadF
* clip_region
,
881 gfx::QuadF scaled_region
;
882 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
883 scaled_region
= SharedGeometryQuad().BoundingBox();
886 gfx::Rect backdrop_rect
= gfx::ToEnclosingRect(MathUtil::MapClippedRect(
887 contents_device_transform
, scaled_region
.BoundingBox()));
889 if (ShouldApplyBackgroundFilters(frame
, quad
)) {
890 int top
, right
, bottom
, left
;
891 quad
->background_filters
.GetOutsets(&top
, &right
, &bottom
, &left
);
892 backdrop_rect
.Inset(-left
, -top
, -right
, -bottom
);
895 if (!backdrop_rect
.IsEmpty() && use_aa
) {
896 const int kOutsetForAntialiasing
= 1;
897 backdrop_rect
.Inset(-kOutsetForAntialiasing
, -kOutsetForAntialiasing
);
900 backdrop_rect
.Intersect(MoveFromDrawToWindowSpace(
901 frame
, frame
->current_render_pass
->output_rect
));
902 return backdrop_rect
;
905 scoped_ptr
<ScopedResource
> GLRenderer::GetBackdropTexture(
906 const gfx::Rect
& bounding_rect
) {
907 scoped_ptr
<ScopedResource
> device_background_texture
=
908 ScopedResource::Create(resource_provider_
);
909 // CopyTexImage2D fails when called on a texture having immutable storage.
910 device_background_texture
->Allocate(
911 bounding_rect
.size(), ResourceProvider::TEXTURE_HINT_DEFAULT
, RGBA_8888
);
913 ResourceProvider::ScopedWriteLockGL
lock(resource_provider_
,
914 device_background_texture
->id());
915 GetFramebufferTexture(
916 lock
.texture_id(), device_background_texture
->format(), bounding_rect
);
918 return device_background_texture
.Pass();
921 skia::RefPtr
<SkImage
> GLRenderer::ApplyBackgroundFilters(
923 const RenderPassDrawQuad
* quad
,
924 ScopedResource
* background_texture
) {
925 DCHECK(ShouldApplyBackgroundFilters(frame
, quad
));
926 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
927 quad
->background_filters
, background_texture
->size());
929 skia::RefPtr
<SkImage
> background_with_filters
= ApplyImageFilter(
930 ScopedUseGrContext::Create(this, frame
), resource_provider_
, quad
->rect
,
931 quad
->filters_scale
, filter
.get(), background_texture
);
932 return background_with_filters
;
935 void GLRenderer::DrawRenderPassQuad(DrawingFrame
* frame
,
936 const RenderPassDrawQuad
* quad
,
937 const gfx::QuadF
* clip_region
) {
938 ScopedResource
* contents_texture
=
939 render_pass_textures_
.get(quad
->render_pass_id
);
940 if (!contents_texture
|| !contents_texture
->id())
943 gfx::Transform quad_rect_matrix
;
944 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
945 gfx::Transform contents_device_transform
=
946 frame
->window_matrix
* frame
->projection_matrix
* quad_rect_matrix
;
947 contents_device_transform
.FlattenTo2d();
949 // Can only draw surface if device matrix is invertible.
950 if (!contents_device_transform
.IsInvertible())
953 gfx::QuadF surface_quad
= SharedGeometryQuad();
955 bool use_aa
= settings_
->allow_antialiasing
&&
956 ShouldAntialiasQuad(contents_device_transform
, quad
,
957 settings_
->force_antialiasing
);
959 SetupQuadForClippingAndAntialiasing(contents_device_transform
, quad
, use_aa
,
960 clip_region
, &surface_quad
, edge
);
961 SkXfermode::Mode blend_mode
= quad
->shared_quad_state
->blend_mode
;
962 bool use_shaders_for_blending
=
963 !CanApplyBlendModeUsingBlendFunc(blend_mode
) ||
964 ShouldApplyBackgroundFilters(frame
, quad
) ||
965 settings_
->force_blending_with_shaders
;
967 scoped_ptr
<ScopedResource
> background_texture
;
968 skia::RefPtr
<SkImage
> background_image
;
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());
996 if (!background_texture
) {
997 // Something went wrong with reading the backdrop.
998 DCHECK(!background_image
);
999 use_shaders_for_blending
= false;
1000 } else if (background_image
) {
1001 // Reset original background texture if there is not any mask
1002 if (!quad
->mask_resource_id
)
1003 background_texture
.reset();
1004 } else if (CanApplyBlendModeUsingBlendFunc(blend_mode
) &&
1005 ShouldApplyBackgroundFilters(frame
, quad
)) {
1006 // Something went wrong with applying background filters to the backdrop.
1007 use_shaders_for_blending
= false;
1008 background_texture
.reset();
1011 // Need original background texture for mask?
1012 bool mask_for_background
=
1013 background_texture
&& // Have original background texture
1014 background_image
&& // Have filtered background texture
1015 quad
->mask_resource_id
; // Have mask texture
1017 !use_shaders_for_blending
&&
1018 (quad
->ShouldDrawWithBlending() || !IsDefaultBlendMode(blend_mode
)));
1020 // TODO(senorblanco): Cache this value so that we don't have to do it for both
1021 // the surface and its replica. Apply filters to the contents texture.
1022 skia::RefPtr
<SkImage
> filter_image
;
1023 SkScalar color_matrix
[20];
1024 bool use_color_matrix
= false;
1025 if (!quad
->filters
.IsEmpty()) {
1026 skia::RefPtr
<SkImageFilter
> filter
= RenderSurfaceFilters::BuildImageFilter(
1027 quad
->filters
, contents_texture
->size());
1029 skia::RefPtr
<SkColorFilter
> cf
;
1032 SkColorFilter
* colorfilter_rawptr
= NULL
;
1033 filter
->asColorFilter(&colorfilter_rawptr
);
1034 cf
= skia::AdoptRef(colorfilter_rawptr
);
1037 if (cf
&& cf
->asColorMatrix(color_matrix
) && !filter
->getInput(0)) {
1038 // We have a single color matrix as a filter; apply it locally
1039 // in the compositor.
1040 use_color_matrix
= true;
1042 filter_image
= ApplyImageFilter(
1043 ScopedUseGrContext::Create(this, frame
), resource_provider_
,
1044 quad
->rect
, quad
->filters_scale
, filter
.get(), contents_texture
);
1049 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> mask_resource_lock
;
1050 unsigned mask_texture_id
= 0;
1051 SamplerType mask_sampler
= SAMPLER_TYPE_NA
;
1052 if (quad
->mask_resource_id
) {
1053 mask_resource_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1054 resource_provider_
, quad
->mask_resource_id
, GL_TEXTURE1
, GL_LINEAR
));
1055 mask_texture_id
= mask_resource_lock
->texture_id();
1056 mask_sampler
= SamplerTypeFromTextureTarget(mask_resource_lock
->target());
1059 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> contents_resource_lock
;
1061 GrTexture
* texture
= filter_image
->getTexture();
1062 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
1063 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1065 contents_resource_lock
=
1066 make_scoped_ptr(new ResourceProvider::ScopedSamplerGL(
1067 resource_provider_
, contents_texture
->id(), GL_LINEAR
));
1068 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1069 contents_resource_lock
->target());
1072 if (!use_shaders_for_blending
) {
1073 if (!use_blend_equation_advanced_coherent_
&& use_blend_equation_advanced_
)
1074 gl_
->BlendBarrierKHR();
1076 ApplyBlendModeUsingBlendFunc(blend_mode
);
1079 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1081 &highp_threshold_cache_
,
1082 highp_threshold_min_
,
1083 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1085 ShaderLocations locations
;
1087 DCHECK_EQ(background_texture
|| background_image
, use_shaders_for_blending
);
1088 BlendMode shader_blend_mode
= use_shaders_for_blending
1089 ? BlendModeFromSkXfermode(blend_mode
)
1092 if (use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1093 const RenderPassMaskProgramAA
* program
= GetRenderPassMaskProgramAA(
1094 tex_coord_precision
, mask_sampler
,
1095 shader_blend_mode
, mask_for_background
);
1096 SetUseProgram(program
->program());
1097 program
->vertex_shader().FillLocations(&locations
);
1098 program
->fragment_shader().FillLocations(&locations
);
1099 gl_
->Uniform1i(locations
.sampler
, 0);
1100 } else if (!use_aa
&& mask_texture_id
&& !use_color_matrix
) {
1101 const RenderPassMaskProgram
* program
= GetRenderPassMaskProgram(
1102 tex_coord_precision
, mask_sampler
,
1103 shader_blend_mode
, mask_for_background
);
1104 SetUseProgram(program
->program());
1105 program
->vertex_shader().FillLocations(&locations
);
1106 program
->fragment_shader().FillLocations(&locations
);
1107 gl_
->Uniform1i(locations
.sampler
, 0);
1108 } else if (use_aa
&& !mask_texture_id
&& !use_color_matrix
) {
1109 const RenderPassProgramAA
* program
=
1110 GetRenderPassProgramAA(tex_coord_precision
, shader_blend_mode
);
1111 SetUseProgram(program
->program());
1112 program
->vertex_shader().FillLocations(&locations
);
1113 program
->fragment_shader().FillLocations(&locations
);
1114 gl_
->Uniform1i(locations
.sampler
, 0);
1115 } else if (use_aa
&& mask_texture_id
&& use_color_matrix
) {
1116 const RenderPassMaskColorMatrixProgramAA
* program
=
1117 GetRenderPassMaskColorMatrixProgramAA(
1118 tex_coord_precision
, mask_sampler
,
1119 shader_blend_mode
, mask_for_background
);
1120 SetUseProgram(program
->program());
1121 program
->vertex_shader().FillLocations(&locations
);
1122 program
->fragment_shader().FillLocations(&locations
);
1123 gl_
->Uniform1i(locations
.sampler
, 0);
1124 } else if (use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1125 const RenderPassColorMatrixProgramAA
* program
=
1126 GetRenderPassColorMatrixProgramAA(tex_coord_precision
,
1128 SetUseProgram(program
->program());
1129 program
->vertex_shader().FillLocations(&locations
);
1130 program
->fragment_shader().FillLocations(&locations
);
1131 gl_
->Uniform1i(locations
.sampler
, 0);
1132 } else if (!use_aa
&& mask_texture_id
&& use_color_matrix
) {
1133 const RenderPassMaskColorMatrixProgram
* program
=
1134 GetRenderPassMaskColorMatrixProgram(
1135 tex_coord_precision
, mask_sampler
,
1136 shader_blend_mode
, mask_for_background
);
1137 SetUseProgram(program
->program());
1138 program
->vertex_shader().FillLocations(&locations
);
1139 program
->fragment_shader().FillLocations(&locations
);
1140 gl_
->Uniform1i(locations
.sampler
, 0);
1141 } else if (!use_aa
&& !mask_texture_id
&& use_color_matrix
) {
1142 const RenderPassColorMatrixProgram
* program
=
1143 GetRenderPassColorMatrixProgram(tex_coord_precision
, shader_blend_mode
);
1144 SetUseProgram(program
->program());
1145 program
->vertex_shader().FillLocations(&locations
);
1146 program
->fragment_shader().FillLocations(&locations
);
1147 gl_
->Uniform1i(locations
.sampler
, 0);
1149 const RenderPassProgram
* program
=
1150 GetRenderPassProgram(tex_coord_precision
, shader_blend_mode
);
1151 SetUseProgram(program
->program());
1152 program
->vertex_shader().FillLocations(&locations
);
1153 program
->fragment_shader().FillLocations(&locations
);
1154 gl_
->Uniform1i(locations
.sampler
, 0);
1157 quad
->rect
.width() / static_cast<float>(contents_texture
->size().width());
1158 float tex_scale_y
= quad
->rect
.height() /
1159 static_cast<float>(contents_texture
->size().height());
1160 DCHECK_LE(tex_scale_x
, 1.0f
);
1161 DCHECK_LE(tex_scale_y
, 1.0f
);
1163 DCHECK(locations
.tex_transform
!= -1 || IsContextLost());
1164 // Flip the content vertically in the shader, as the RenderPass input
1165 // texture is already oriented the same way as the framebuffer, but the
1166 // projection transform does a flip.
1167 gl_
->Uniform4f(locations
.tex_transform
, 0.0f
, tex_scale_y
, tex_scale_x
,
1170 GLint last_texture_unit
= 0;
1171 if (locations
.mask_sampler
!= -1) {
1172 DCHECK_NE(locations
.mask_tex_coord_scale
, 1);
1173 DCHECK_NE(locations
.mask_tex_coord_offset
, 1);
1174 gl_
->Uniform1i(locations
.mask_sampler
, 1);
1176 gfx::RectF mask_uv_rect
= quad
->MaskUVRect();
1177 if (mask_sampler
!= SAMPLER_TYPE_2D
) {
1178 mask_uv_rect
.Scale(quad
->mask_texture_size
.width(),
1179 quad
->mask_texture_size
.height());
1182 // Mask textures are oriented vertically flipped relative to the framebuffer
1183 // and the RenderPass contents texture, so we flip the tex coords from the
1184 // RenderPass texture to find the mask texture coords.
1185 gl_
->Uniform2f(locations
.mask_tex_coord_offset
, mask_uv_rect
.x(),
1186 mask_uv_rect
.bottom());
1187 gl_
->Uniform2f(locations
.mask_tex_coord_scale
,
1188 mask_uv_rect
.width() / tex_scale_x
,
1189 -mask_uv_rect
.height() / tex_scale_y
);
1191 last_texture_unit
= 1;
1194 if (locations
.edge
!= -1)
1195 gl_
->Uniform3fv(locations
.edge
, 8, edge
);
1197 if (locations
.viewport
!= -1) {
1198 float viewport
[4] = {
1199 static_cast<float>(current_window_space_viewport_
.x()),
1200 static_cast<float>(current_window_space_viewport_
.y()),
1201 static_cast<float>(current_window_space_viewport_
.width()),
1202 static_cast<float>(current_window_space_viewport_
.height()),
1204 gl_
->Uniform4fv(locations
.viewport
, 1, viewport
);
1207 if (locations
.color_matrix
!= -1) {
1209 for (int i
= 0; i
< 4; ++i
) {
1210 for (int j
= 0; j
< 4; ++j
)
1211 matrix
[i
* 4 + j
] = SkScalarToFloat(color_matrix
[j
* 5 + i
]);
1213 gl_
->UniformMatrix4fv(locations
.color_matrix
, 1, false, matrix
);
1215 static const float kScale
= 1.0f
/ 255.0f
;
1216 if (locations
.color_offset
!= -1) {
1218 for (int i
= 0; i
< 4; ++i
)
1219 offset
[i
] = SkScalarToFloat(color_matrix
[i
* 5 + 4]) * kScale
;
1221 gl_
->Uniform4fv(locations
.color_offset
, 1, offset
);
1224 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> shader_background_sampler_lock
;
1225 if (locations
.backdrop
!= -1) {
1226 DCHECK(background_texture
|| background_image
);
1227 DCHECK_NE(locations
.backdrop
, 0);
1228 DCHECK_NE(locations
.backdrop_rect
, 0);
1230 gl_
->Uniform1i(locations
.backdrop
, ++last_texture_unit
);
1232 gl_
->Uniform4f(locations
.backdrop_rect
, background_rect
.x(),
1233 background_rect
.y(), background_rect
.width(),
1234 background_rect
.height());
1236 if (background_image
) {
1237 GrTexture
* texture
= background_image
->getTexture();
1238 gl_
->ActiveTexture(GL_TEXTURE0
+ last_texture_unit
);
1239 gl_
->BindTexture(GL_TEXTURE_2D
, texture
->getTextureHandle());
1240 gl_
->ActiveTexture(GL_TEXTURE0
);
1241 if (mask_for_background
)
1242 gl_
->Uniform1i(locations
.original_backdrop
, ++last_texture_unit
);
1244 if (background_texture
) {
1245 shader_background_sampler_lock
= make_scoped_ptr(
1246 new ResourceProvider::ScopedSamplerGL(resource_provider_
,
1247 background_texture
->id(),
1248 GL_TEXTURE0
+ last_texture_unit
,
1250 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
),
1251 shader_background_sampler_lock
->target());
1255 SetShaderOpacity(quad
->opacity(), locations
.alpha
);
1256 SetShaderQuadF(surface_quad
, locations
.quad
);
1258 frame
, quad
->quadTransform(), quad
->rect
, locations
.matrix
);
1260 // Flush the compositor context before the filter bitmap goes out of
1261 // scope, so the draw gets processed before the filter texture gets deleted.
1265 if (!use_shaders_for_blending
)
1266 RestoreBlendFuncToDefault(blend_mode
);
1269 struct SolidColorProgramUniforms
{
1271 unsigned matrix_location
;
1272 unsigned viewport_location
;
1273 unsigned quad_location
;
1274 unsigned edge_location
;
1275 unsigned color_location
;
1279 static void SolidColorUniformLocation(T program
,
1280 SolidColorProgramUniforms
* uniforms
) {
1281 uniforms
->program
= program
->program();
1282 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1283 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1284 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1285 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1286 uniforms
->color_location
= program
->fragment_shader().color_location();
1290 // These functions determine if a quad, clipped by a clip_region contains
1291 // the entire {top|bottom|left|right} edge.
1292 bool is_top(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1293 if (!quad
->IsTopEdge())
1298 return std::abs(clip_region
->p1().y()) < kAntiAliasingEpsilon
&&
1299 std::abs(clip_region
->p2().y()) < kAntiAliasingEpsilon
;
1302 bool is_bottom(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1303 if (!quad
->IsBottomEdge())
1308 return std::abs(clip_region
->p3().y() -
1309 quad
->shared_quad_state
->content_bounds
.height()) <
1310 kAntiAliasingEpsilon
&&
1311 std::abs(clip_region
->p4().y() -
1312 quad
->shared_quad_state
->content_bounds
.height()) <
1313 kAntiAliasingEpsilon
;
1316 bool is_left(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1317 if (!quad
->IsLeftEdge())
1322 return std::abs(clip_region
->p1().x()) < kAntiAliasingEpsilon
&&
1323 std::abs(clip_region
->p4().x()) < kAntiAliasingEpsilon
;
1326 bool is_right(const gfx::QuadF
* clip_region
, const DrawQuad
* quad
) {
1327 if (!quad
->IsRightEdge())
1332 return std::abs(clip_region
->p2().x() -
1333 quad
->shared_quad_state
->content_bounds
.width()) <
1334 kAntiAliasingEpsilon
&&
1335 std::abs(clip_region
->p3().x() -
1336 quad
->shared_quad_state
->content_bounds
.width()) <
1337 kAntiAliasingEpsilon
;
1339 } // anonymous namespace
1341 static gfx::QuadF
GetDeviceQuadWithAntialiasingOnExteriorEdges(
1342 const LayerQuad
& device_layer_edges
,
1343 const gfx::Transform
& device_transform
,
1344 const gfx::QuadF
* clip_region
,
1345 const DrawQuad
* quad
) {
1346 gfx::RectF tile_rect
= quad
->visible_rect
;
1347 gfx::QuadF
tile_quad(tile_rect
);
1350 if (quad
->material
!= DrawQuad::RENDER_PASS
) {
1351 tile_quad
= *clip_region
;
1353 GetScaledRegion(quad
->rect
, clip_region
, &tile_quad
);
1357 gfx::PointF bottom_right
= tile_quad
.p3();
1358 gfx::PointF bottom_left
= tile_quad
.p4();
1359 gfx::PointF top_left
= tile_quad
.p1();
1360 gfx::PointF top_right
= tile_quad
.p2();
1361 bool clipped
= false;
1363 // Map points to device space. We ignore |clipped|, since the result of
1364 // |MapPoint()| still produces a valid point to draw the quad with. When
1365 // clipped, the point will be outside of the viewport. See crbug.com/416367.
1366 bottom_right
= MathUtil::MapPoint(device_transform
, bottom_right
, &clipped
);
1367 bottom_left
= MathUtil::MapPoint(device_transform
, bottom_left
, &clipped
);
1368 top_left
= MathUtil::MapPoint(device_transform
, top_left
, &clipped
);
1369 top_right
= MathUtil::MapPoint(device_transform
, top_right
, &clipped
);
1371 LayerQuad::Edge
bottom_edge(bottom_right
, bottom_left
);
1372 LayerQuad::Edge
left_edge(bottom_left
, top_left
);
1373 LayerQuad::Edge
top_edge(top_left
, top_right
);
1374 LayerQuad::Edge
right_edge(top_right
, bottom_right
);
1376 // Only apply anti-aliasing to edges not clipped by culling or scissoring.
1377 // If an edge is degenerate we do not want to replace it with a "proper" edge
1378 // as that will cause the quad to possibly expand is strange ways.
1379 if (!top_edge
.degenerate() && is_top(clip_region
, quad
) &&
1380 tile_rect
.y() == quad
->rect
.y()) {
1381 top_edge
= device_layer_edges
.top();
1383 if (!left_edge
.degenerate() && is_left(clip_region
, quad
) &&
1384 tile_rect
.x() == quad
->rect
.x()) {
1385 left_edge
= device_layer_edges
.left();
1387 if (!right_edge
.degenerate() && is_right(clip_region
, quad
) &&
1388 tile_rect
.right() == quad
->rect
.right()) {
1389 right_edge
= device_layer_edges
.right();
1391 if (!bottom_edge
.degenerate() && is_bottom(clip_region
, quad
) &&
1392 tile_rect
.bottom() == quad
->rect
.bottom()) {
1393 bottom_edge
= device_layer_edges
.bottom();
1396 float sign
= tile_quad
.IsCounterClockwise() ? -1 : 1;
1397 bottom_edge
.scale(sign
);
1398 left_edge
.scale(sign
);
1399 top_edge
.scale(sign
);
1400 right_edge
.scale(sign
);
1402 // Create device space quad.
1403 return LayerQuad(left_edge
, top_edge
, right_edge
, bottom_edge
).ToQuadF();
1406 float GetTotalQuadError(const gfx::QuadF
* clipped_quad
,
1407 const gfx::QuadF
* ideal_rect
) {
1408 return (clipped_quad
->p1() - ideal_rect
->p1()).LengthSquared() +
1409 (clipped_quad
->p2() - ideal_rect
->p2()).LengthSquared() +
1410 (clipped_quad
->p3() - ideal_rect
->p3()).LengthSquared() +
1411 (clipped_quad
->p4() - ideal_rect
->p4()).LengthSquared();
1414 // Attempt to rotate the clipped quad until it lines up the most
1415 // correctly. This is necessary because we check the edges of this
1416 // quad against the expected left/right/top/bottom for anti-aliasing.
1417 void AlignQuadToBoundingBox(gfx::QuadF
* clipped_quad
) {
1418 gfx::QuadF bounding_quad
= gfx::QuadF(clipped_quad
->BoundingBox());
1419 gfx::QuadF best_rotation
= *clipped_quad
;
1420 float least_error_amount
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1421 for (size_t i
= 1; i
< 4; ++i
) {
1422 clipped_quad
->Realign(1);
1423 float new_error
= GetTotalQuadError(clipped_quad
, &bounding_quad
);
1424 if (new_error
< least_error_amount
) {
1425 least_error_amount
= new_error
;
1426 best_rotation
= *clipped_quad
;
1429 *clipped_quad
= best_rotation
;
1433 bool GLRenderer::ShouldAntialiasQuad(const gfx::Transform
& device_transform
,
1434 const DrawQuad
* quad
,
1435 bool force_antialiasing
) {
1436 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1437 // For render pass quads, |device_transform| already contains quad's rect.
1438 // TODO(rosca@adobe.com): remove branching on is_render_pass_quad
1440 if (!is_render_pass_quad
&& !quad
->IsEdge())
1442 gfx::RectF content_rect
=
1443 is_render_pass_quad
? QuadVertexRect() : quad
->visibleContentRect();
1445 bool clipped
= false;
1446 gfx::QuadF device_layer_quad
=
1447 MathUtil::MapQuad(device_transform
, gfx::QuadF(content_rect
), &clipped
);
1449 if (device_layer_quad
.BoundingBox().IsEmpty())
1452 bool is_axis_aligned_in_target
= device_layer_quad
.IsRectilinear();
1453 bool is_nearest_rect_within_epsilon
=
1454 is_axis_aligned_in_target
&&
1455 gfx::IsNearestRectWithinDistance(device_layer_quad
.BoundingBox(),
1456 kAntiAliasingEpsilon
);
1457 // AAing clipped quads is not supported by the code yet.
1458 bool use_aa
= !clipped
&& !is_nearest_rect_within_epsilon
;
1459 return use_aa
|| force_antialiasing
;
1463 void GLRenderer::SetupQuadForClippingAndAntialiasing(
1464 const gfx::Transform
& device_transform
,
1465 const DrawQuad
* quad
,
1467 const gfx::QuadF
* clip_region
,
1468 gfx::QuadF
* local_quad
,
1470 bool is_render_pass_quad
= (quad
->material
== DrawQuad::RENDER_PASS
);
1471 gfx::QuadF rotated_clip
;
1472 const gfx::QuadF
* local_clip_region
= clip_region
;
1473 if (local_clip_region
) {
1474 rotated_clip
= *clip_region
;
1475 AlignQuadToBoundingBox(&rotated_clip
);
1476 local_clip_region
= &rotated_clip
;
1479 gfx::QuadF content_rect
= is_render_pass_quad
1480 ? gfx::QuadF(QuadVertexRect())
1481 : gfx::QuadF(quad
->visibleContentRect());
1483 if (local_clip_region
) {
1484 if (!is_render_pass_quad
) {
1485 content_rect
= *local_clip_region
;
1487 GetScaledRegion(quad
->rect
, local_clip_region
, &content_rect
);
1489 *local_quad
= content_rect
;
1493 bool clipped
= false;
1494 gfx::QuadF device_layer_quad
=
1495 MathUtil::MapQuad(device_transform
, content_rect
, &clipped
);
1497 LayerQuad
device_layer_bounds(gfx::QuadF(device_layer_quad
.BoundingBox()));
1498 device_layer_bounds
.InflateAntiAliasingDistance();
1500 LayerQuad
device_layer_edges(device_layer_quad
);
1501 device_layer_edges
.InflateAntiAliasingDistance();
1503 device_layer_edges
.ToFloatArray(edge
);
1504 device_layer_bounds
.ToFloatArray(&edge
[12]);
1506 // If we have a clip region then we are split, and therefore
1507 // by necessity, at least one of our edges is not an external
1509 bool is_full_rect
= quad
->visible_rect
== quad
->rect
;
1511 bool region_contains_all_outside_edges
=
1513 (is_top(local_clip_region
, quad
) && is_left(local_clip_region
, quad
) &&
1514 is_bottom(local_clip_region
, quad
) && is_right(local_clip_region
, quad
));
1516 bool use_aa_on_all_four_edges
=
1517 !local_clip_region
&&
1518 (is_render_pass_quad
|| region_contains_all_outside_edges
);
1520 gfx::QuadF device_quad
=
1521 use_aa_on_all_four_edges
1522 ? device_layer_edges
.ToQuadF()
1523 : GetDeviceQuadWithAntialiasingOnExteriorEdges(
1524 device_layer_edges
, device_transform
, local_clip_region
, quad
);
1526 // Map device space quad to local space. device_transform has no 3d
1527 // component since it was flattened, so we don't need to project. We should
1528 // have already checked that the transform was uninvertible above.
1529 gfx::Transform
inverse_device_transform(gfx::Transform::kSkipInitialization
);
1530 bool did_invert
= device_transform
.GetInverse(&inverse_device_transform
);
1533 MathUtil::MapQuad(inverse_device_transform
, device_quad
, &clipped
);
1534 // We should not DCHECK(!clipped) here, because anti-aliasing inflation may
1535 // cause device_quad to become clipped. To our knowledge this scenario does
1536 // not need to be handled differently than the unclipped case.
1539 void GLRenderer::DrawSolidColorQuad(const DrawingFrame
* frame
,
1540 const SolidColorDrawQuad
* quad
,
1541 const gfx::QuadF
* clip_region
) {
1542 gfx::Rect tile_rect
= quad
->visible_rect
;
1544 SkColor color
= quad
->color
;
1545 float opacity
= quad
->opacity();
1546 float alpha
= (SkColorGetA(color
) * (1.0f
/ 255.0f
)) * opacity
;
1548 // Early out if alpha is small enough that quad doesn't contribute to output.
1549 if (alpha
< std::numeric_limits
<float>::epsilon() &&
1550 quad
->ShouldDrawWithBlending())
1553 gfx::Transform device_transform
=
1554 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1555 device_transform
.FlattenTo2d();
1556 if (!device_transform
.IsInvertible())
1559 bool force_aa
= false;
1560 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1562 bool use_aa
= settings_
->allow_antialiasing
&&
1563 !quad
->force_anti_aliasing_off
&&
1564 ShouldAntialiasQuad(device_transform
, quad
, force_aa
);
1565 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, use_aa
,
1566 clip_region
, &local_quad
, edge
);
1568 SolidColorProgramUniforms uniforms
;
1570 SolidColorUniformLocation(GetSolidColorProgramAA(), &uniforms
);
1572 SolidColorUniformLocation(GetSolidColorProgram(), &uniforms
);
1574 SetUseProgram(uniforms
.program
);
1576 gl_
->Uniform4f(uniforms
.color_location
,
1577 (SkColorGetR(color
) * (1.0f
/ 255.0f
)) * alpha
,
1578 (SkColorGetG(color
) * (1.0f
/ 255.0f
)) * alpha
,
1579 (SkColorGetB(color
) * (1.0f
/ 255.0f
)) * alpha
, alpha
);
1581 float viewport
[4] = {
1582 static_cast<float>(current_window_space_viewport_
.x()),
1583 static_cast<float>(current_window_space_viewport_
.y()),
1584 static_cast<float>(current_window_space_viewport_
.width()),
1585 static_cast<float>(current_window_space_viewport_
.height()),
1587 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1588 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1591 // Enable blending when the quad properties require it or if we decided
1592 // to use antialiasing.
1593 SetBlendEnabled(quad
->ShouldDrawWithBlending() || use_aa
);
1595 // Normalize to tile_rect.
1596 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1598 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1600 // The transform and vertex data are used to figure out the extents that the
1601 // un-antialiased quad should have and which vertex this is and the float
1602 // quad passed in via uniform is the actual geometry that gets used to draw
1603 // it. This is why this centered rect is used and not the original quad_rect.
1604 gfx::RectF
centered_rect(
1605 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1608 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1611 struct TileProgramUniforms
{
1613 unsigned matrix_location
;
1614 unsigned viewport_location
;
1615 unsigned quad_location
;
1616 unsigned edge_location
;
1617 unsigned vertex_tex_transform_location
;
1618 unsigned sampler_location
;
1619 unsigned fragment_tex_transform_location
;
1620 unsigned alpha_location
;
1624 static void TileUniformLocation(T program
, TileProgramUniforms
* uniforms
) {
1625 uniforms
->program
= program
->program();
1626 uniforms
->matrix_location
= program
->vertex_shader().matrix_location();
1627 uniforms
->viewport_location
= program
->vertex_shader().viewport_location();
1628 uniforms
->quad_location
= program
->vertex_shader().quad_location();
1629 uniforms
->edge_location
= program
->vertex_shader().edge_location();
1630 uniforms
->vertex_tex_transform_location
=
1631 program
->vertex_shader().vertex_tex_transform_location();
1633 uniforms
->sampler_location
= program
->fragment_shader().sampler_location();
1634 uniforms
->alpha_location
= program
->fragment_shader().alpha_location();
1635 uniforms
->fragment_tex_transform_location
=
1636 program
->fragment_shader().fragment_tex_transform_location();
1639 void GLRenderer::DrawTileQuad(const DrawingFrame
* frame
,
1640 const TileDrawQuad
* quad
,
1641 const gfx::QuadF
* clip_region
) {
1642 DrawContentQuad(frame
, quad
, quad
->resource_id
, clip_region
);
1645 void GLRenderer::DrawContentQuad(const DrawingFrame
* frame
,
1646 const ContentDrawQuadBase
* quad
,
1647 ResourceProvider::ResourceId resource_id
,
1648 const gfx::QuadF
* clip_region
) {
1649 gfx::Transform device_transform
=
1650 frame
->window_matrix
* frame
->projection_matrix
* quad
->quadTransform();
1651 device_transform
.FlattenTo2d();
1653 bool use_aa
= settings_
->allow_antialiasing
&&
1654 ShouldAntialiasQuad(device_transform
, quad
, false);
1656 // TODO(timav): simplify coordinate transformations in DrawContentQuadAA
1657 // similar to the way DrawContentQuadNoAA works and then consider
1658 // combining DrawContentQuadAA and DrawContentQuadNoAA into one method.
1660 DrawContentQuadAA(frame
, quad
, resource_id
, device_transform
, clip_region
);
1662 DrawContentQuadNoAA(frame
, quad
, resource_id
, clip_region
);
1665 void GLRenderer::DrawContentQuadAA(const DrawingFrame
* frame
,
1666 const ContentDrawQuadBase
* quad
,
1667 ResourceProvider::ResourceId resource_id
,
1668 const gfx::Transform
& device_transform
,
1669 const gfx::QuadF
* clip_region
) {
1670 if (!device_transform
.IsInvertible())
1673 gfx::Rect tile_rect
= quad
->visible_rect
;
1675 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1676 quad
->tex_coord_rect
, quad
->rect
, tile_rect
);
1677 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1678 float tex_to_geom_scale_y
=
1679 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1681 gfx::RectF
clamp_geom_rect(tile_rect
);
1682 gfx::RectF
clamp_tex_rect(tex_coord_rect
);
1683 // Clamp texture coordinates to avoid sampling outside the layer
1684 // by deflating the tile region half a texel or half a texel
1685 // minus epsilon for one pixel layers. The resulting clamp region
1686 // is mapped to the unit square by the vertex shader and mapped
1687 // back to normalized texture coordinates by the fragment shader
1688 // after being clamped to 0-1 range.
1690 std::min(0.5f
, 0.5f
* clamp_tex_rect
.width() - kAntiAliasingEpsilon
);
1692 std::min(0.5f
, 0.5f
* clamp_tex_rect
.height() - kAntiAliasingEpsilon
);
1693 float geom_clamp_x
=
1694 std::min(tex_clamp_x
* tex_to_geom_scale_x
,
1695 0.5f
* clamp_geom_rect
.width() - kAntiAliasingEpsilon
);
1696 float geom_clamp_y
=
1697 std::min(tex_clamp_y
* tex_to_geom_scale_y
,
1698 0.5f
* clamp_geom_rect
.height() - kAntiAliasingEpsilon
);
1699 clamp_geom_rect
.Inset(geom_clamp_x
, geom_clamp_y
, geom_clamp_x
, geom_clamp_y
);
1700 clamp_tex_rect
.Inset(tex_clamp_x
, tex_clamp_y
, tex_clamp_x
, tex_clamp_y
);
1702 // Map clamping rectangle to unit square.
1703 float vertex_tex_translate_x
= -clamp_geom_rect
.x() / clamp_geom_rect
.width();
1704 float vertex_tex_translate_y
=
1705 -clamp_geom_rect
.y() / clamp_geom_rect
.height();
1706 float vertex_tex_scale_x
= tile_rect
.width() / clamp_geom_rect
.width();
1707 float vertex_tex_scale_y
= tile_rect
.height() / clamp_geom_rect
.height();
1709 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1710 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1712 gfx::QuadF local_quad
= gfx::QuadF(gfx::RectF(tile_rect
));
1714 SetupQuadForClippingAndAntialiasing(device_transform
, quad
, true, clip_region
,
1716 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1717 resource_provider_
, resource_id
,
1718 quad
->nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
1719 SamplerType sampler
=
1720 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1722 float fragment_tex_translate_x
= clamp_tex_rect
.x();
1723 float fragment_tex_translate_y
= clamp_tex_rect
.y();
1724 float fragment_tex_scale_x
= clamp_tex_rect
.width();
1725 float fragment_tex_scale_y
= clamp_tex_rect
.height();
1727 // Map to normalized texture coordinates.
1728 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1729 gfx::Size texture_size
= quad
->texture_size
;
1730 DCHECK(!texture_size
.IsEmpty());
1731 fragment_tex_translate_x
/= texture_size
.width();
1732 fragment_tex_translate_y
/= texture_size
.height();
1733 fragment_tex_scale_x
/= texture_size
.width();
1734 fragment_tex_scale_y
/= texture_size
.height();
1737 TileProgramUniforms uniforms
;
1738 if (quad
->swizzle_contents
) {
1739 TileUniformLocation(GetTileProgramSwizzleAA(tex_coord_precision
, sampler
),
1742 TileUniformLocation(GetTileProgramAA(tex_coord_precision
, sampler
),
1746 SetUseProgram(uniforms
.program
);
1747 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1749 float viewport
[4] = {
1750 static_cast<float>(current_window_space_viewport_
.x()),
1751 static_cast<float>(current_window_space_viewport_
.y()),
1752 static_cast<float>(current_window_space_viewport_
.width()),
1753 static_cast<float>(current_window_space_viewport_
.height()),
1755 gl_
->Uniform4fv(uniforms
.viewport_location
, 1, viewport
);
1756 gl_
->Uniform3fv(uniforms
.edge_location
, 8, edge
);
1758 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1759 vertex_tex_translate_y
, vertex_tex_scale_x
,
1760 vertex_tex_scale_y
);
1761 gl_
->Uniform4f(uniforms
.fragment_tex_transform_location
,
1762 fragment_tex_translate_x
, fragment_tex_translate_y
,
1763 fragment_tex_scale_x
, fragment_tex_scale_y
);
1765 // Blending is required for antialiasing.
1766 SetBlendEnabled(true);
1768 // Normalize to tile_rect.
1769 local_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
1771 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1772 SetShaderQuadF(local_quad
, uniforms
.quad_location
);
1774 // The transform and vertex data are used to figure out the extents that the
1775 // un-antialiased quad should have and which vertex this is and the float
1776 // quad passed in via uniform is the actual geometry that gets used to draw
1777 // it. This is why this centered rect is used and not the original quad_rect.
1778 gfx::RectF
centered_rect(
1779 gfx::PointF(-0.5f
* tile_rect
.width(), -0.5f
* tile_rect
.height()),
1782 frame
, quad
->quadTransform(), centered_rect
, uniforms
.matrix_location
);
1785 void GLRenderer::DrawContentQuadNoAA(const DrawingFrame
* frame
,
1786 const ContentDrawQuadBase
* quad
,
1787 ResourceProvider::ResourceId resource_id
,
1788 const gfx::QuadF
* clip_region
) {
1789 gfx::RectF tex_coord_rect
= MathUtil::ScaleRectProportional(
1790 quad
->tex_coord_rect
, quad
->rect
, quad
->visible_rect
);
1791 float tex_to_geom_scale_x
= quad
->rect
.width() / quad
->tex_coord_rect
.width();
1792 float tex_to_geom_scale_y
=
1793 quad
->rect
.height() / quad
->tex_coord_rect
.height();
1795 bool scaled
= (tex_to_geom_scale_x
!= 1.f
|| tex_to_geom_scale_y
!= 1.f
);
1797 (scaled
|| !quad
->quadTransform().IsIdentityOrIntegerTranslation()) &&
1798 !quad
->nearest_neighbor
1802 ResourceProvider::ScopedSamplerGL
quad_resource_lock(
1803 resource_provider_
, resource_id
, filter
);
1804 SamplerType sampler
=
1805 SamplerTypeFromTextureTarget(quad_resource_lock
.target());
1807 float vertex_tex_translate_x
= tex_coord_rect
.x();
1808 float vertex_tex_translate_y
= tex_coord_rect
.y();
1809 float vertex_tex_scale_x
= tex_coord_rect
.width();
1810 float vertex_tex_scale_y
= tex_coord_rect
.height();
1812 // Map to normalized texture coordinates.
1813 if (sampler
!= SAMPLER_TYPE_2D_RECT
) {
1814 gfx::Size texture_size
= quad
->texture_size
;
1815 DCHECK(!texture_size
.IsEmpty());
1816 vertex_tex_translate_x
/= texture_size
.width();
1817 vertex_tex_translate_y
/= texture_size
.height();
1818 vertex_tex_scale_x
/= texture_size
.width();
1819 vertex_tex_scale_y
/= texture_size
.height();
1822 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1823 gl_
, &highp_threshold_cache_
, highp_threshold_min_
, quad
->texture_size
);
1825 TileProgramUniforms uniforms
;
1826 if (quad
->ShouldDrawWithBlending()) {
1827 if (quad
->swizzle_contents
) {
1828 TileUniformLocation(GetTileProgramSwizzle(tex_coord_precision
, sampler
),
1831 TileUniformLocation(GetTileProgram(tex_coord_precision
, sampler
),
1835 if (quad
->swizzle_contents
) {
1836 TileUniformLocation(
1837 GetTileProgramSwizzleOpaque(tex_coord_precision
, sampler
), &uniforms
);
1839 TileUniformLocation(GetTileProgramOpaque(tex_coord_precision
, sampler
),
1844 SetUseProgram(uniforms
.program
);
1845 gl_
->Uniform1i(uniforms
.sampler_location
, 0);
1847 gl_
->Uniform4f(uniforms
.vertex_tex_transform_location
, vertex_tex_translate_x
,
1848 vertex_tex_translate_y
, vertex_tex_scale_x
,
1849 vertex_tex_scale_y
);
1851 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1853 SetShaderOpacity(quad
->opacity(), uniforms
.alpha_location
);
1855 // Pass quad coordinates to the uniform in the same order as GeometryBinding
1856 // does, then vertices will match the texture mapping in the vertex buffer.
1857 // The method SetShaderQuadF() changes the order of vertices and so it's
1859 gfx::QuadF
tile_rect(quad
->visible_rect
);
1860 float width
= quad
->visible_rect
.width();
1861 float height
= quad
->visible_rect
.height();
1862 gfx::PointF top_left
= quad
->visible_rect
.origin();
1864 tile_rect
= *clip_region
;
1866 (tile_rect
.p4().x() - top_left
.x()) / width
,
1867 (tile_rect
.p4().y() - top_left
.y()) / height
,
1868 (tile_rect
.p1().x() - top_left
.x()) / width
,
1869 (tile_rect
.p1().y() - top_left
.y()) / height
,
1870 (tile_rect
.p2().x() - top_left
.x()) / width
,
1871 (tile_rect
.p2().y() - top_left
.y()) / height
,
1872 (tile_rect
.p3().x() - top_left
.x()) / width
,
1873 (tile_rect
.p3().y() - top_left
.y()) / height
,
1875 PrepareGeometry(CLIPPED_BINDING
);
1876 clipped_geometry_
->InitializeCustomQuadWithUVs(
1877 gfx::QuadF(quad
->visible_rect
), gl_uv
);
1879 PrepareGeometry(SHARED_BINDING
);
1881 float gl_quad
[8] = {
1891 gl_
->Uniform2fv(uniforms
.quad_location
, 4, gl_quad
);
1893 static float gl_matrix
[16];
1894 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad
->quadTransform());
1895 gl_
->UniformMatrix4fv(uniforms
.matrix_location
, 1, false, &gl_matrix
[0]);
1897 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
1900 void GLRenderer::DrawYUVVideoQuad(const DrawingFrame
* frame
,
1901 const YUVVideoDrawQuad
* quad
,
1902 const gfx::QuadF
* clip_region
) {
1903 SetBlendEnabled(quad
->ShouldDrawWithBlending());
1905 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
1907 &highp_threshold_cache_
,
1908 highp_threshold_min_
,
1909 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
1911 bool use_alpha_plane
= quad
->a_plane_resource_id
!= 0;
1913 ResourceProvider::ScopedSamplerGL
y_plane_lock(
1914 resource_provider_
, quad
->y_plane_resource_id
, GL_TEXTURE1
, GL_LINEAR
);
1915 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), y_plane_lock
.target());
1916 ResourceProvider::ScopedSamplerGL
u_plane_lock(
1917 resource_provider_
, quad
->u_plane_resource_id
, GL_TEXTURE2
, GL_LINEAR
);
1918 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), u_plane_lock
.target());
1919 ResourceProvider::ScopedSamplerGL
v_plane_lock(
1920 resource_provider_
, quad
->v_plane_resource_id
, GL_TEXTURE3
, GL_LINEAR
);
1921 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), v_plane_lock
.target());
1922 scoped_ptr
<ResourceProvider::ScopedSamplerGL
> a_plane_lock
;
1923 if (use_alpha_plane
) {
1924 a_plane_lock
.reset(new ResourceProvider::ScopedSamplerGL(
1925 resource_provider_
, quad
->a_plane_resource_id
, GL_TEXTURE4
, GL_LINEAR
));
1926 DCHECK_EQ(static_cast<GLenum
>(GL_TEXTURE_2D
), a_plane_lock
->target());
1929 int matrix_location
= -1;
1930 int tex_scale_location
= -1;
1931 int tex_offset_location
= -1;
1932 int ya_clamp_rect_location
= -1;
1933 int uv_clamp_rect_location
= -1;
1934 int y_texture_location
= -1;
1935 int u_texture_location
= -1;
1936 int v_texture_location
= -1;
1937 int a_texture_location
= -1;
1938 int yuv_matrix_location
= -1;
1939 int yuv_adj_location
= -1;
1940 int alpha_location
= -1;
1941 if (use_alpha_plane
) {
1942 const VideoYUVAProgram
* program
= GetVideoYUVAProgram(tex_coord_precision
);
1943 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1944 SetUseProgram(program
->program());
1945 matrix_location
= program
->vertex_shader().matrix_location();
1946 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1947 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1948 y_texture_location
= program
->fragment_shader().y_texture_location();
1949 u_texture_location
= program
->fragment_shader().u_texture_location();
1950 v_texture_location
= program
->fragment_shader().v_texture_location();
1951 a_texture_location
= program
->fragment_shader().a_texture_location();
1952 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1953 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1954 ya_clamp_rect_location
=
1955 program
->fragment_shader().ya_clamp_rect_location();
1956 uv_clamp_rect_location
=
1957 program
->fragment_shader().uv_clamp_rect_location();
1958 alpha_location
= program
->fragment_shader().alpha_location();
1960 const VideoYUVProgram
* program
= GetVideoYUVProgram(tex_coord_precision
);
1961 DCHECK(program
&& (program
->initialized() || IsContextLost()));
1962 SetUseProgram(program
->program());
1963 matrix_location
= program
->vertex_shader().matrix_location();
1964 tex_scale_location
= program
->vertex_shader().tex_scale_location();
1965 tex_offset_location
= program
->vertex_shader().tex_offset_location();
1966 y_texture_location
= program
->fragment_shader().y_texture_location();
1967 u_texture_location
= program
->fragment_shader().u_texture_location();
1968 v_texture_location
= program
->fragment_shader().v_texture_location();
1969 yuv_matrix_location
= program
->fragment_shader().yuv_matrix_location();
1970 yuv_adj_location
= program
->fragment_shader().yuv_adj_location();
1971 ya_clamp_rect_location
=
1972 program
->fragment_shader().ya_clamp_rect_location();
1973 uv_clamp_rect_location
=
1974 program
->fragment_shader().uv_clamp_rect_location();
1975 alpha_location
= program
->fragment_shader().alpha_location();
1978 gl_
->Uniform2f(tex_scale_location
, quad
->tex_coord_rect
.width(),
1979 quad
->tex_coord_rect
.height());
1980 gl_
->Uniform2f(tex_offset_location
, quad
->tex_coord_rect
.x(),
1981 quad
->tex_coord_rect
.y());
1982 // Clamping to half a texel inside the tex coord rect prevents bilinear
1983 // filtering from filtering outside the tex coord rect.
1984 gfx::RectF
ya_clamp_rect(quad
->tex_coord_rect
);
1985 // Special case: empty texture size implies no clamping.
1986 if (!quad
->ya_tex_size
.IsEmpty()) {
1987 ya_clamp_rect
.Inset(0.5f
/ quad
->ya_tex_size
.width(),
1988 0.5f
/ quad
->ya_tex_size
.height());
1990 gfx::RectF
uv_clamp_rect(quad
->tex_coord_rect
);
1991 if (!quad
->uv_tex_size
.IsEmpty()) {
1992 uv_clamp_rect
.Inset(0.5f
/ quad
->uv_tex_size
.width(),
1993 0.5f
/ quad
->uv_tex_size
.height());
1995 gl_
->Uniform4f(ya_clamp_rect_location
, ya_clamp_rect
.x(), ya_clamp_rect
.y(),
1996 ya_clamp_rect
.right(), ya_clamp_rect
.bottom());
1997 gl_
->Uniform4f(uv_clamp_rect_location
, uv_clamp_rect
.x(), uv_clamp_rect
.y(),
1998 uv_clamp_rect
.right(), uv_clamp_rect
.bottom());
2000 gl_
->Uniform1i(y_texture_location
, 1);
2001 gl_
->Uniform1i(u_texture_location
, 2);
2002 gl_
->Uniform1i(v_texture_location
, 3);
2003 if (use_alpha_plane
)
2004 gl_
->Uniform1i(a_texture_location
, 4);
2006 // These values are magic numbers that are used in the transformation from YUV
2007 // to RGB color values. They are taken from the following webpage:
2008 // http://www.fourcc.org/fccyvrgb.php
2009 float yuv_to_rgb_rec601
[9] = {
2010 1.164f
, 1.164f
, 1.164f
, 0.0f
, -.391f
, 2.018f
, 1.596f
, -.813f
, 0.0f
,
2012 float yuv_to_rgb_jpeg
[9] = {
2013 1.f
, 1.f
, 1.f
, 0.0f
, -.34414f
, 1.772f
, 1.402f
, -.71414f
, 0.0f
,
2015 float yuv_to_rgb_rec709
[9] = {
2016 1.164f
, 1.164f
, 1.164f
, 0.0f
, -0.213f
, 2.112f
, 1.793f
, -0.533f
, 0.0f
,
2019 // These values map to 16, 128, and 128 respectively, and are computed
2020 // as a fraction over 256 (e.g. 16 / 256 = 0.0625).
2021 // They are used in the YUV to RGBA conversion formula:
2022 // Y - 16 : Gives 16 values of head and footroom for overshooting
2023 // U - 128 : Turns unsigned U into signed U [-128,127]
2024 // V - 128 : Turns unsigned V into signed V [-128,127]
2025 float yuv_adjust_constrained
[3] = {
2026 -0.0625f
, -0.5f
, -0.5f
,
2029 // Same as above, but without the head and footroom.
2030 float yuv_adjust_full
[3] = {
2034 float* yuv_to_rgb
= NULL
;
2035 float* yuv_adjust
= NULL
;
2037 switch (quad
->color_space
) {
2038 case YUVVideoDrawQuad::REC_601
:
2039 yuv_to_rgb
= yuv_to_rgb_rec601
;
2040 yuv_adjust
= yuv_adjust_constrained
;
2042 case YUVVideoDrawQuad::REC_709
:
2043 yuv_to_rgb
= yuv_to_rgb_rec709
;
2044 yuv_adjust
= yuv_adjust_constrained
;
2046 case YUVVideoDrawQuad::JPEG
:
2047 yuv_to_rgb
= yuv_to_rgb_jpeg
;
2048 yuv_adjust
= yuv_adjust_full
;
2052 // The transform and vertex data are used to figure out the extents that the
2053 // un-antialiased quad should have and which vertex this is and the float
2054 // quad passed in via uniform is the actual geometry that gets used to draw
2055 // it. This is why this centered rect is used and not the original quad_rect.
2056 gfx::RectF tile_rect
= quad
->rect
;
2057 gl_
->UniformMatrix3fv(yuv_matrix_location
, 1, 0, yuv_to_rgb
);
2058 gl_
->Uniform3fv(yuv_adj_location
, 1, yuv_adjust
);
2060 SetShaderOpacity(quad
->opacity(), alpha_location
);
2062 DrawQuadGeometry(frame
, quad
->quadTransform(), tile_rect
, matrix_location
);
2065 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2066 gfx::QuadF region_quad
= *clip_region
;
2067 region_quad
.Scale(1.0f
/ tile_rect
.width(), 1.0f
/ tile_rect
.height());
2068 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2069 DrawQuadGeometryClippedByQuadF(frame
, quad
->quadTransform(), tile_rect
,
2070 region_quad
, matrix_location
, uvs
);
2074 void GLRenderer::DrawStreamVideoQuad(const DrawingFrame
* frame
,
2075 const StreamVideoDrawQuad
* quad
,
2076 const gfx::QuadF
* clip_region
) {
2077 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2079 static float gl_matrix
[16];
2081 DCHECK(capabilities_
.using_egl_image
);
2083 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2085 &highp_threshold_cache_
,
2086 highp_threshold_min_
,
2087 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2089 const VideoStreamTextureProgram
* program
=
2090 GetVideoStreamTextureProgram(tex_coord_precision
);
2091 SetUseProgram(program
->program());
2093 ToGLMatrix(&gl_matrix
[0], quad
->matrix
);
2094 gl_
->UniformMatrix4fv(program
->vertex_shader().tex_matrix_location(), 1,
2097 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2099 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2100 gl_
->BindTexture(GL_TEXTURE_EXTERNAL_OES
, lock
.texture_id());
2102 gl_
->Uniform1i(program
->fragment_shader().sampler_location(), 0);
2104 SetShaderOpacity(quad
->opacity(),
2105 program
->fragment_shader().alpha_location());
2107 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
,
2108 program
->vertex_shader().matrix_location());
2110 gfx::QuadF
region_quad(*clip_region
);
2111 region_quad
.Scale(1.0f
/ quad
->rect
.width(), 1.0f
/ quad
->rect
.height());
2112 region_quad
-= gfx::Vector2dF(0.5f
, 0.5f
);
2114 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2115 DrawQuadGeometryClippedByQuadF(
2116 frame
, quad
->quadTransform(), quad
->rect
, region_quad
,
2117 program
->vertex_shader().matrix_location(), uvs
);
2121 struct TextureProgramBinding
{
2122 template <class Program
>
2123 void Set(Program
* program
) {
2125 program_id
= program
->program();
2126 sampler_location
= program
->fragment_shader().sampler_location();
2127 matrix_location
= program
->vertex_shader().matrix_location();
2128 background_color_location
=
2129 program
->fragment_shader().background_color_location();
2132 int sampler_location
;
2133 int matrix_location
;
2134 int transform_location
;
2135 int background_color_location
;
2138 struct TexTransformTextureProgramBinding
: TextureProgramBinding
{
2139 template <class Program
>
2140 void Set(Program
* program
) {
2141 TextureProgramBinding::Set(program
);
2142 tex_transform_location
= program
->vertex_shader().tex_transform_location();
2143 vertex_opacity_location
=
2144 program
->vertex_shader().vertex_opacity_location();
2146 int tex_transform_location
;
2147 int vertex_opacity_location
;
2150 void GLRenderer::FlushTextureQuadCache(BoundGeometry flush_binding
) {
2151 // Check to see if we have anything to draw.
2152 if (draw_cache_
.program_id
== -1)
2155 PrepareGeometry(flush_binding
);
2157 // Set the correct blending mode.
2158 SetBlendEnabled(draw_cache_
.needs_blending
);
2160 // Bind the program to the GL state.
2161 SetUseProgram(draw_cache_
.program_id
);
2163 // Bind the correct texture sampler location.
2164 gl_
->Uniform1i(draw_cache_
.sampler_location
, 0);
2166 // Assume the current active textures is 0.
2167 ResourceProvider::ScopedSamplerGL
locked_quad(
2169 draw_cache_
.resource_id
,
2170 draw_cache_
.nearest_neighbor
? GL_NEAREST
: GL_LINEAR
);
2171 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2172 gl_
->BindTexture(GL_TEXTURE_2D
, locked_quad
.texture_id());
2174 static_assert(sizeof(Float4
) == 4 * sizeof(float),
2175 "Float4 struct should be densely packed");
2176 static_assert(sizeof(Float16
) == 16 * sizeof(float),
2177 "Float16 struct should be densely packed");
2179 // Upload the tranforms for both points and uvs.
2180 gl_
->UniformMatrix4fv(
2181 static_cast<int>(draw_cache_
.matrix_location
),
2182 static_cast<int>(draw_cache_
.matrix_data
.size()), false,
2183 reinterpret_cast<float*>(&draw_cache_
.matrix_data
.front()));
2184 gl_
->Uniform4fv(static_cast<int>(draw_cache_
.uv_xform_location
),
2185 static_cast<int>(draw_cache_
.uv_xform_data
.size()),
2186 reinterpret_cast<float*>(&draw_cache_
.uv_xform_data
.front()));
2188 if (draw_cache_
.background_color
!= SK_ColorTRANSPARENT
) {
2189 Float4 background_color
= PremultipliedColor(draw_cache_
.background_color
);
2190 gl_
->Uniform4fv(draw_cache_
.background_color_location
, 1,
2191 background_color
.data
);
2195 static_cast<int>(draw_cache_
.vertex_opacity_location
),
2196 static_cast<int>(draw_cache_
.vertex_opacity_data
.size()),
2197 static_cast<float*>(&draw_cache_
.vertex_opacity_data
.front()));
2200 gl_
->DrawElements(GL_TRIANGLES
, 6 * draw_cache_
.matrix_data
.size(),
2201 GL_UNSIGNED_SHORT
, 0);
2204 draw_cache_
.program_id
= -1;
2205 draw_cache_
.uv_xform_data
.resize(0);
2206 draw_cache_
.vertex_opacity_data
.resize(0);
2207 draw_cache_
.matrix_data
.resize(0);
2209 // If we had a clipped binding, prepare the shared binding for the
2211 if (flush_binding
== CLIPPED_BINDING
) {
2212 PrepareGeometry(SHARED_BINDING
);
2216 void GLRenderer::EnqueueTextureQuad(const DrawingFrame
* frame
,
2217 const TextureDrawQuad
* quad
,
2218 const gfx::QuadF
* clip_region
) {
2219 // If we have a clip_region then we have to render the next quad
2220 // with dynamic geometry, therefore we must flush all pending
2223 // We send in false here because we want to flush what's currently in the
2224 // queue using the shared_geometry and not clipped_geometry
2225 FlushTextureQuadCache(SHARED_BINDING
);
2228 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2230 &highp_threshold_cache_
,
2231 highp_threshold_min_
,
2232 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2234 // Choose the correct texture program binding
2235 TexTransformTextureProgramBinding binding
;
2236 if (quad
->premultiplied_alpha
) {
2237 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2238 binding
.Set(GetTextureProgram(tex_coord_precision
));
2240 binding
.Set(GetTextureBackgroundProgram(tex_coord_precision
));
2243 if (quad
->background_color
== SK_ColorTRANSPARENT
) {
2244 binding
.Set(GetNonPremultipliedTextureProgram(tex_coord_precision
));
2247 GetNonPremultipliedTextureBackgroundProgram(tex_coord_precision
));
2251 int resource_id
= quad
->resource_id
;
2253 if (draw_cache_
.program_id
!= binding
.program_id
||
2254 draw_cache_
.resource_id
!= resource_id
||
2255 draw_cache_
.needs_blending
!= quad
->ShouldDrawWithBlending() ||
2256 draw_cache_
.nearest_neighbor
!= quad
->nearest_neighbor
||
2257 draw_cache_
.background_color
!= quad
->background_color
||
2258 draw_cache_
.matrix_data
.size() >= 8) {
2259 FlushTextureQuadCache(SHARED_BINDING
);
2260 draw_cache_
.program_id
= binding
.program_id
;
2261 draw_cache_
.resource_id
= resource_id
;
2262 draw_cache_
.needs_blending
= quad
->ShouldDrawWithBlending();
2263 draw_cache_
.nearest_neighbor
= quad
->nearest_neighbor
;
2264 draw_cache_
.background_color
= quad
->background_color
;
2266 draw_cache_
.uv_xform_location
= binding
.tex_transform_location
;
2267 draw_cache_
.background_color_location
= binding
.background_color_location
;
2268 draw_cache_
.vertex_opacity_location
= binding
.vertex_opacity_location
;
2269 draw_cache_
.matrix_location
= binding
.matrix_location
;
2270 draw_cache_
.sampler_location
= binding
.sampler_location
;
2273 // Generate the uv-transform
2275 draw_cache_
.uv_xform_data
.push_back(UVTransform(quad
));
2277 Float4 uv_transform
= {{0.0f
, 0.0f
, 1.0f
, 1.0f
}};
2278 draw_cache_
.uv_xform_data
.push_back(uv_transform
);
2281 // Generate the vertex opacity
2282 const float opacity
= quad
->opacity();
2283 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[0] * opacity
);
2284 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[1] * opacity
);
2285 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[2] * opacity
);
2286 draw_cache_
.vertex_opacity_data
.push_back(quad
->vertex_opacity
[3] * opacity
);
2288 // Generate the transform matrix
2289 gfx::Transform quad_rect_matrix
;
2290 QuadRectTransform(&quad_rect_matrix
, quad
->quadTransform(), quad
->rect
);
2291 quad_rect_matrix
= frame
->projection_matrix
* quad_rect_matrix
;
2294 quad_rect_matrix
.matrix().asColMajorf(m
.data
);
2295 draw_cache_
.matrix_data
.push_back(m
);
2298 gfx::QuadF scaled_region
;
2299 if (!GetScaledRegion(quad
->rect
, clip_region
, &scaled_region
)) {
2300 scaled_region
= SharedGeometryQuad().BoundingBox();
2302 // Both the scaled region and the SharedGeomtryQuad are in the space
2303 // -0.5->0.5. We need to move that to the space 0->1.
2305 uv
[0] = scaled_region
.p1().x() + 0.5f
;
2306 uv
[1] = scaled_region
.p1().y() + 0.5f
;
2307 uv
[2] = scaled_region
.p2().x() + 0.5f
;
2308 uv
[3] = scaled_region
.p2().y() + 0.5f
;
2309 uv
[4] = scaled_region
.p3().x() + 0.5f
;
2310 uv
[5] = scaled_region
.p3().y() + 0.5f
;
2311 uv
[6] = scaled_region
.p4().x() + 0.5f
;
2312 uv
[7] = scaled_region
.p4().y() + 0.5f
;
2313 PrepareGeometry(CLIPPED_BINDING
);
2314 clipped_geometry_
->InitializeCustomQuadWithUVs(scaled_region
, uv
);
2315 FlushTextureQuadCache(CLIPPED_BINDING
);
2319 void GLRenderer::DrawIOSurfaceQuad(const DrawingFrame
* frame
,
2320 const IOSurfaceDrawQuad
* quad
,
2321 const gfx::QuadF
* clip_region
) {
2322 SetBlendEnabled(quad
->ShouldDrawWithBlending());
2324 TexCoordPrecision tex_coord_precision
= TexCoordPrecisionRequired(
2326 &highp_threshold_cache_
,
2327 highp_threshold_min_
,
2328 quad
->shared_quad_state
->visible_content_rect
.bottom_right());
2330 TexTransformTextureProgramBinding binding
;
2331 binding
.Set(GetTextureIOSurfaceProgram(tex_coord_precision
));
2333 SetUseProgram(binding
.program_id
);
2334 gl_
->Uniform1i(binding
.sampler_location
, 0);
2335 if (quad
->orientation
== IOSurfaceDrawQuad::FLIPPED
) {
2337 binding
.tex_transform_location
, 0, quad
->io_surface_size
.height(),
2338 quad
->io_surface_size
.width(), quad
->io_surface_size
.height() * -1.0f
);
2340 gl_
->Uniform4f(binding
.tex_transform_location
, 0, 0,
2341 quad
->io_surface_size
.width(),
2342 quad
->io_surface_size
.height());
2345 const float vertex_opacity
[] = {quad
->opacity(), quad
->opacity(),
2346 quad
->opacity(), quad
->opacity()};
2347 gl_
->Uniform1fv(binding
.vertex_opacity_location
, 4, vertex_opacity
);
2349 ResourceProvider::ScopedReadLockGL
lock(resource_provider_
,
2350 quad
->io_surface_resource_id
);
2351 DCHECK_EQ(GL_TEXTURE0
, GetActiveTextureUnit(gl_
));
2352 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, lock
.texture_id());
2355 DrawQuadGeometry(frame
, quad
->quadTransform(), quad
->rect
,
2356 binding
.matrix_location
);
2359 GetScaledUVs(quad
->visible_rect
, clip_region
, uvs
);
2360 DrawQuadGeometryClippedByQuadF(frame
, quad
->quadTransform(), quad
->rect
,
2361 *clip_region
, binding
.matrix_location
, uvs
);
2364 gl_
->BindTexture(GL_TEXTURE_RECTANGLE_ARB
, 0);
2367 void GLRenderer::FinishDrawingFrame(DrawingFrame
* frame
) {
2368 if (use_sync_query_
) {
2369 DCHECK(current_sync_query_
);
2370 current_sync_query_
->End();
2371 pending_sync_queries_
.push_back(current_sync_query_
.Pass());
2374 current_framebuffer_lock_
= nullptr;
2375 swap_buffer_rect_
.Union(gfx::ToEnclosingRect(frame
->root_damage_rect
));
2377 gl_
->Disable(GL_BLEND
);
2378 blend_shadow_
= false;
2380 ScheduleOverlays(frame
);
2383 void GLRenderer::FinishDrawingQuadList() {
2384 FlushTextureQuadCache(SHARED_BINDING
);
2387 bool GLRenderer::FlippedFramebuffer(const DrawingFrame
* frame
) const {
2388 if (frame
->current_render_pass
!= frame
->root_render_pass
)
2390 return FlippedRootFramebuffer();
2393 bool GLRenderer::FlippedRootFramebuffer() const {
2394 // GL is normally flipped, so a flipped output results in an unflipping.
2395 return !output_surface_
->capabilities().flipped_output_surface
;
2398 void GLRenderer::EnsureScissorTestEnabled() {
2399 if (is_scissor_enabled_
)
2402 FlushTextureQuadCache(SHARED_BINDING
);
2403 gl_
->Enable(GL_SCISSOR_TEST
);
2404 is_scissor_enabled_
= true;
2407 void GLRenderer::EnsureScissorTestDisabled() {
2408 if (!is_scissor_enabled_
)
2411 FlushTextureQuadCache(SHARED_BINDING
);
2412 gl_
->Disable(GL_SCISSOR_TEST
);
2413 is_scissor_enabled_
= false;
2416 void GLRenderer::CopyCurrentRenderPassToBitmap(
2417 DrawingFrame
* frame
,
2418 scoped_ptr
<CopyOutputRequest
> request
) {
2419 TRACE_EVENT0("cc", "GLRenderer::CopyCurrentRenderPassToBitmap");
2420 gfx::Rect copy_rect
= frame
->current_render_pass
->output_rect
;
2421 if (request
->has_area())
2422 copy_rect
.Intersect(request
->area());
2423 GetFramebufferPixelsAsync(frame
, copy_rect
, request
.Pass());
2426 void GLRenderer::ToGLMatrix(float* gl_matrix
, const gfx::Transform
& transform
) {
2427 transform
.matrix().asColMajorf(gl_matrix
);
2430 void GLRenderer::SetShaderQuadF(const gfx::QuadF
& quad
, int quad_location
) {
2431 if (quad_location
== -1)
2435 gl_quad
[0] = quad
.p1().x();
2436 gl_quad
[1] = quad
.p1().y();
2437 gl_quad
[2] = quad
.p2().x();
2438 gl_quad
[3] = quad
.p2().y();
2439 gl_quad
[4] = quad
.p3().x();
2440 gl_quad
[5] = quad
.p3().y();
2441 gl_quad
[6] = quad
.p4().x();
2442 gl_quad
[7] = quad
.p4().y();
2443 gl_
->Uniform2fv(quad_location
, 4, gl_quad
);
2446 void GLRenderer::SetShaderOpacity(float opacity
, int alpha_location
) {
2447 if (alpha_location
!= -1)
2448 gl_
->Uniform1f(alpha_location
, opacity
);
2451 void GLRenderer::SetStencilEnabled(bool enabled
) {
2452 if (enabled
== stencil_shadow_
)
2456 gl_
->Enable(GL_STENCIL_TEST
);
2458 gl_
->Disable(GL_STENCIL_TEST
);
2459 stencil_shadow_
= enabled
;
2462 void GLRenderer::SetBlendEnabled(bool enabled
) {
2463 if (enabled
== blend_shadow_
)
2467 gl_
->Enable(GL_BLEND
);
2469 gl_
->Disable(GL_BLEND
);
2470 blend_shadow_
= enabled
;
2473 void GLRenderer::SetUseProgram(unsigned program
) {
2474 if (program
== program_shadow_
)
2476 gl_
->UseProgram(program
);
2477 program_shadow_
= program
;
2480 void GLRenderer::DrawQuadGeometryClippedByQuadF(
2481 const DrawingFrame
* frame
,
2482 const gfx::Transform
& draw_transform
,
2483 const gfx::RectF
& quad_rect
,
2484 const gfx::QuadF
& clipping_region_quad
,
2485 int matrix_location
,
2487 PrepareGeometry(CLIPPED_BINDING
);
2489 clipped_geometry_
->InitializeCustomQuadWithUVs(clipping_region_quad
, uvs
);
2491 clipped_geometry_
->InitializeCustomQuad(clipping_region_quad
);
2493 gfx::Transform quad_rect_matrix
;
2494 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2495 static float gl_matrix
[16];
2496 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2497 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2499 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
,
2500 reinterpret_cast<const void*>(0));
2503 void GLRenderer::DrawQuadGeometry(const DrawingFrame
* frame
,
2504 const gfx::Transform
& draw_transform
,
2505 const gfx::RectF
& quad_rect
,
2506 int matrix_location
) {
2507 PrepareGeometry(SHARED_BINDING
);
2508 gfx::Transform quad_rect_matrix
;
2509 QuadRectTransform(&quad_rect_matrix
, draw_transform
, quad_rect
);
2510 static float gl_matrix
[16];
2511 ToGLMatrix(&gl_matrix
[0], frame
->projection_matrix
* quad_rect_matrix
);
2512 gl_
->UniformMatrix4fv(matrix_location
, 1, false, &gl_matrix
[0]);
2514 gl_
->DrawElements(GL_TRIANGLES
, 6, GL_UNSIGNED_SHORT
, 0);
2517 void GLRenderer::Finish() {
2518 TRACE_EVENT0("cc", "GLRenderer::Finish");
2522 void GLRenderer::SwapBuffers(const CompositorFrameMetadata
& metadata
) {
2523 DCHECK(!is_backbuffer_discarded_
);
2525 TRACE_EVENT0("cc,benchmark", "GLRenderer::SwapBuffers");
2526 // We're done! Time to swapbuffers!
2528 gfx::Size surface_size
= output_surface_
->SurfaceSize();
2530 CompositorFrame compositor_frame
;
2531 compositor_frame
.metadata
= metadata
;
2532 compositor_frame
.gl_frame_data
= make_scoped_ptr(new GLFrameData
);
2533 compositor_frame
.gl_frame_data
->size
= surface_size
;
2534 if (capabilities_
.using_partial_swap
) {
2535 // If supported, we can save significant bandwidth by only swapping the
2536 // damaged/scissored region (clamped to the viewport).
2537 swap_buffer_rect_
.Intersect(gfx::Rect(surface_size
));
2538 int flipped_y_pos_of_rect_bottom
= surface_size
.height() -
2539 swap_buffer_rect_
.y() -
2540 swap_buffer_rect_
.height();
2541 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2542 gfx::Rect(swap_buffer_rect_
.x(),
2543 FlippedRootFramebuffer() ? flipped_y_pos_of_rect_bottom
2544 : swap_buffer_rect_
.y(),
2545 swap_buffer_rect_
.width(),
2546 swap_buffer_rect_
.height());
2548 compositor_frame
.gl_frame_data
->sub_buffer_rect
=
2549 gfx::Rect(output_surface_
->SurfaceSize());
2551 output_surface_
->SwapBuffers(&compositor_frame
);
2553 // Release previously used overlay resources and hold onto the pending ones
2554 // until the next swap buffers.
2555 in_use_overlay_resources_
.clear();
2556 in_use_overlay_resources_
.swap(pending_overlay_resources_
);
2558 swap_buffer_rect_
= gfx::Rect();
2561 void GLRenderer::EnforceMemoryPolicy() {
2563 TRACE_EVENT0("cc", "GLRenderer::EnforceMemoryPolicy dropping resources");
2564 ReleaseRenderPassTextures();
2565 DiscardBackbuffer();
2566 resource_provider_
->ReleaseCachedData();
2567 output_surface_
->context_provider()->DeleteCachedResources();
2570 PrepareGeometry(NO_BINDING
);
2573 void GLRenderer::DiscardBackbuffer() {
2574 if (is_backbuffer_discarded_
)
2577 output_surface_
->DiscardBackbuffer();
2579 is_backbuffer_discarded_
= true;
2581 // Damage tracker needs a full reset every time framebuffer is discarded.
2582 client_
->SetFullRootLayerDamage();
2585 void GLRenderer::EnsureBackbuffer() {
2586 if (!is_backbuffer_discarded_
)
2589 output_surface_
->EnsureBackbuffer();
2590 is_backbuffer_discarded_
= false;
2593 void GLRenderer::GetFramebufferPixelsAsync(
2594 const DrawingFrame
* frame
,
2595 const gfx::Rect
& rect
,
2596 scoped_ptr
<CopyOutputRequest
> request
) {
2597 DCHECK(!request
->IsEmpty());
2598 if (request
->IsEmpty())
2603 gfx::Rect window_rect
= MoveFromDrawToWindowSpace(frame
, rect
);
2604 DCHECK_GE(window_rect
.x(), 0);
2605 DCHECK_GE(window_rect
.y(), 0);
2606 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2607 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2609 if (!request
->force_bitmap_result()) {
2610 bool own_mailbox
= !request
->has_texture_mailbox();
2612 GLuint texture_id
= 0;
2613 gpu::Mailbox mailbox
;
2615 gl_
->GenMailboxCHROMIUM(mailbox
.name
);
2616 gl_
->GenTextures(1, &texture_id
);
2617 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2619 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2620 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2621 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2622 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2623 gl_
->ProduceTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2625 mailbox
= request
->texture_mailbox().mailbox();
2626 DCHECK_EQ(static_cast<unsigned>(GL_TEXTURE_2D
),
2627 request
->texture_mailbox().target());
2628 DCHECK(!mailbox
.IsZero());
2629 unsigned incoming_sync_point
= request
->texture_mailbox().sync_point();
2630 if (incoming_sync_point
)
2631 gl_
->WaitSyncPointCHROMIUM(incoming_sync_point
);
2634 gl_
->CreateAndConsumeTextureCHROMIUM(GL_TEXTURE_2D
, mailbox
.name
);
2636 GetFramebufferTexture(texture_id
, RGBA_8888
, window_rect
);
2638 unsigned sync_point
= gl_
->InsertSyncPointCHROMIUM();
2639 TextureMailbox
texture_mailbox(mailbox
, GL_TEXTURE_2D
, sync_point
);
2641 scoped_ptr
<SingleReleaseCallback
> release_callback
;
2643 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2644 release_callback
= texture_mailbox_deleter_
->GetReleaseCallback(
2645 output_surface_
->context_provider(), texture_id
);
2647 gl_
->DeleteTextures(1, &texture_id
);
2650 request
->SendTextureResult(
2651 window_rect
.size(), texture_mailbox
, release_callback
.Pass());
2655 DCHECK(request
->force_bitmap_result());
2657 scoped_ptr
<PendingAsyncReadPixels
> pending_read(new PendingAsyncReadPixels
);
2658 pending_read
->copy_request
= request
.Pass();
2659 pending_async_read_pixels_
.insert(pending_async_read_pixels_
.begin(),
2660 pending_read
.Pass());
2662 bool do_workaround
= NeedsIOSurfaceReadbackWorkaround();
2664 unsigned temporary_texture
= 0;
2665 unsigned temporary_fbo
= 0;
2667 if (do_workaround
) {
2668 // On Mac OS X, calling glReadPixels() against an FBO whose color attachment
2669 // is an IOSurface-backed texture causes corruption of future glReadPixels()
2670 // calls, even those on different OpenGL contexts. It is believed that this
2671 // is the root cause of top crasher
2672 // http://crbug.com/99393. <rdar://problem/10949687>
2674 gl_
->GenTextures(1, &temporary_texture
);
2675 gl_
->BindTexture(GL_TEXTURE_2D
, temporary_texture
);
2676 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MIN_FILTER
, GL_LINEAR
);
2677 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_MAG_FILTER
, GL_LINEAR
);
2678 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_S
, GL_CLAMP_TO_EDGE
);
2679 gl_
->TexParameteri(GL_TEXTURE_2D
, GL_TEXTURE_WRAP_T
, GL_CLAMP_TO_EDGE
);
2680 // Copy the contents of the current (IOSurface-backed) framebuffer into a
2681 // temporary texture.
2682 GetFramebufferTexture(
2683 temporary_texture
, RGBA_8888
, gfx::Rect(current_surface_size_
));
2684 gl_
->GenFramebuffers(1, &temporary_fbo
);
2685 // Attach this texture to an FBO, and perform the readback from that FBO.
2686 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, temporary_fbo
);
2687 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
,
2688 GL_TEXTURE_2D
, temporary_texture
, 0);
2690 DCHECK_EQ(static_cast<unsigned>(GL_FRAMEBUFFER_COMPLETE
),
2691 gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
));
2695 gl_
->GenBuffers(1, &buffer
);
2696 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, buffer
);
2697 gl_
->BufferData(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
,
2698 4 * window_rect
.size().GetArea(), NULL
, GL_STREAM_READ
);
2701 gl_
->GenQueriesEXT(1, &query
);
2702 gl_
->BeginQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
, query
);
2704 gl_
->ReadPixels(window_rect
.x(), window_rect
.y(), window_rect
.width(),
2705 window_rect
.height(), GL_RGBA
, GL_UNSIGNED_BYTE
, NULL
);
2707 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2709 if (do_workaround
) {
2711 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, 0);
2712 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2713 gl_
->DeleteFramebuffers(1, &temporary_fbo
);
2714 gl_
->DeleteTextures(1, &temporary_texture
);
2717 base::Closure finished_callback
= base::Bind(&GLRenderer::FinishedReadback
,
2718 base::Unretained(this),
2721 window_rect
.size());
2722 // Save the finished_callback so it can be cancelled.
2723 pending_async_read_pixels_
.front()->finished_read_pixels_callback
.Reset(
2725 base::Closure cancelable_callback
=
2726 pending_async_read_pixels_
.front()->
2727 finished_read_pixels_callback
.callback();
2729 // Save the buffer to verify the callbacks happen in the expected order.
2730 pending_async_read_pixels_
.front()->buffer
= buffer
;
2732 gl_
->EndQueryEXT(GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM
);
2733 context_support_
->SignalQuery(query
, cancelable_callback
);
2735 EnforceMemoryPolicy();
2738 void GLRenderer::FinishedReadback(unsigned source_buffer
,
2740 const gfx::Size
& size
) {
2741 DCHECK(!pending_async_read_pixels_
.empty());
2744 gl_
->DeleteQueriesEXT(1, &query
);
2747 PendingAsyncReadPixels
* current_read
= pending_async_read_pixels_
.back();
2748 // Make sure we service the readbacks in order.
2749 DCHECK_EQ(source_buffer
, current_read
->buffer
);
2751 uint8
* src_pixels
= NULL
;
2752 scoped_ptr
<SkBitmap
> bitmap
;
2754 if (source_buffer
!= 0) {
2755 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, source_buffer
);
2756 src_pixels
= static_cast<uint8
*>(gl_
->MapBufferCHROMIUM(
2757 GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, GL_READ_ONLY
));
2760 bitmap
.reset(new SkBitmap
);
2761 bitmap
->allocN32Pixels(size
.width(), size
.height());
2762 scoped_ptr
<SkAutoLockPixels
> lock(new SkAutoLockPixels(*bitmap
));
2763 uint8
* dest_pixels
= static_cast<uint8
*>(bitmap
->getPixels());
2765 size_t row_bytes
= size
.width() * 4;
2766 int num_rows
= size
.height();
2767 size_t total_bytes
= num_rows
* row_bytes
;
2768 for (size_t dest_y
= 0; dest_y
< total_bytes
; dest_y
+= row_bytes
) {
2770 size_t src_y
= total_bytes
- dest_y
- row_bytes
;
2771 // Swizzle OpenGL -> Skia byte order.
2772 for (size_t x
= 0; x
< row_bytes
; x
+= 4) {
2773 dest_pixels
[dest_y
+ x
+ SK_R32_SHIFT
/ 8] =
2774 src_pixels
[src_y
+ x
+ 0];
2775 dest_pixels
[dest_y
+ x
+ SK_G32_SHIFT
/ 8] =
2776 src_pixels
[src_y
+ x
+ 1];
2777 dest_pixels
[dest_y
+ x
+ SK_B32_SHIFT
/ 8] =
2778 src_pixels
[src_y
+ x
+ 2];
2779 dest_pixels
[dest_y
+ x
+ SK_A32_SHIFT
/ 8] =
2780 src_pixels
[src_y
+ x
+ 3];
2784 gl_
->UnmapBufferCHROMIUM(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
);
2786 gl_
->BindBuffer(GL_PIXEL_PACK_TRANSFER_BUFFER_CHROMIUM
, 0);
2787 gl_
->DeleteBuffers(1, &source_buffer
);
2791 current_read
->copy_request
->SendBitmapResult(bitmap
.Pass());
2792 pending_async_read_pixels_
.pop_back();
2795 void GLRenderer::GetFramebufferTexture(unsigned texture_id
,
2796 ResourceFormat texture_format
,
2797 const gfx::Rect
& window_rect
) {
2799 DCHECK_GE(window_rect
.x(), 0);
2800 DCHECK_GE(window_rect
.y(), 0);
2801 DCHECK_LE(window_rect
.right(), current_surface_size_
.width());
2802 DCHECK_LE(window_rect
.bottom(), current_surface_size_
.height());
2804 gl_
->BindTexture(GL_TEXTURE_2D
, texture_id
);
2805 gl_
->CopyTexImage2D(GL_TEXTURE_2D
, 0, GLDataFormat(texture_format
),
2806 window_rect
.x(), window_rect
.y(), window_rect
.width(),
2807 window_rect
.height(), 0);
2808 gl_
->BindTexture(GL_TEXTURE_2D
, 0);
2811 bool GLRenderer::UseScopedTexture(DrawingFrame
* frame
,
2812 const ScopedResource
* texture
,
2813 const gfx::Rect
& viewport_rect
) {
2814 DCHECK(texture
->id());
2815 frame
->current_render_pass
= NULL
;
2816 frame
->current_texture
= texture
;
2818 return BindFramebufferToTexture(frame
, texture
, viewport_rect
);
2821 void GLRenderer::BindFramebufferToOutputSurface(DrawingFrame
* frame
) {
2822 current_framebuffer_lock_
= nullptr;
2823 output_surface_
->BindFramebuffer();
2825 if (output_surface_
->HasExternalStencilTest()) {
2826 SetStencilEnabled(true);
2827 gl_
->StencilFunc(GL_EQUAL
, 1, 1);
2829 SetStencilEnabled(false);
2833 bool GLRenderer::BindFramebufferToTexture(DrawingFrame
* frame
,
2834 const ScopedResource
* texture
,
2835 const gfx::Rect
& target_rect
) {
2836 DCHECK(texture
->id());
2838 // Explicitly release lock, otherwise we can crash when try to lock
2839 // same texture again.
2840 current_framebuffer_lock_
= nullptr;
2842 SetStencilEnabled(false);
2843 gl_
->BindFramebuffer(GL_FRAMEBUFFER
, offscreen_framebuffer_id_
);
2844 current_framebuffer_lock_
=
2845 make_scoped_ptr(new ResourceProvider::ScopedWriteLockGL(
2846 resource_provider_
, texture
->id()));
2847 unsigned texture_id
= current_framebuffer_lock_
->texture_id();
2848 gl_
->FramebufferTexture2D(GL_FRAMEBUFFER
, GL_COLOR_ATTACHMENT0
, GL_TEXTURE_2D
,
2851 DCHECK(gl_
->CheckFramebufferStatus(GL_FRAMEBUFFER
) ==
2852 GL_FRAMEBUFFER_COMPLETE
||
2857 void GLRenderer::SetScissorTestRect(const gfx::Rect
& scissor_rect
) {
2858 EnsureScissorTestEnabled();
2860 // Don't unnecessarily ask the context to change the scissor, because it
2861 // may cause undesired GPU pipeline flushes.
2862 if (scissor_rect
== scissor_rect_
&& !scissor_rect_needs_reset_
)
2865 scissor_rect_
= scissor_rect
;
2866 FlushTextureQuadCache(SHARED_BINDING
);
2867 gl_
->Scissor(scissor_rect
.x(), scissor_rect
.y(), scissor_rect
.width(),
2868 scissor_rect
.height());
2870 scissor_rect_needs_reset_
= false;
2873 void GLRenderer::SetViewport() {
2874 gl_
->Viewport(current_window_space_viewport_
.x(),
2875 current_window_space_viewport_
.y(),
2876 current_window_space_viewport_
.width(),
2877 current_window_space_viewport_
.height());
2880 void GLRenderer::InitializeSharedObjects() {
2881 TRACE_EVENT0("cc", "GLRenderer::InitializeSharedObjects");
2883 // Create an FBO for doing offscreen rendering.
2884 gl_
->GenFramebuffers(1, &offscreen_framebuffer_id_
);
2887 make_scoped_ptr(new StaticGeometryBinding(gl_
, QuadVertexRect()));
2888 clipped_geometry_
= make_scoped_ptr(new DynamicGeometryBinding(gl_
));
2891 void GLRenderer::PrepareGeometry(BoundGeometry binding
) {
2892 if (binding
== bound_geometry_
) {
2897 case SHARED_BINDING
:
2898 shared_geometry_
->PrepareForDraw();
2900 case CLIPPED_BINDING
:
2901 clipped_geometry_
->PrepareForDraw();
2906 bound_geometry_
= binding
;
2909 const GLRenderer::TileCheckerboardProgram
*
2910 GLRenderer::GetTileCheckerboardProgram() {
2911 if (!tile_checkerboard_program_
.initialized()) {
2912 TRACE_EVENT0("cc", "GLRenderer::checkerboardProgram::initalize");
2913 tile_checkerboard_program_
.Initialize(output_surface_
->context_provider(),
2914 TEX_COORD_PRECISION_NA
,
2917 return &tile_checkerboard_program_
;
2920 const GLRenderer::DebugBorderProgram
* GLRenderer::GetDebugBorderProgram() {
2921 if (!debug_border_program_
.initialized()) {
2922 TRACE_EVENT0("cc", "GLRenderer::debugBorderProgram::initialize");
2923 debug_border_program_
.Initialize(output_surface_
->context_provider(),
2924 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2926 return &debug_border_program_
;
2929 const GLRenderer::SolidColorProgram
* GLRenderer::GetSolidColorProgram() {
2930 if (!solid_color_program_
.initialized()) {
2931 TRACE_EVENT0("cc", "GLRenderer::solidColorProgram::initialize");
2932 solid_color_program_
.Initialize(output_surface_
->context_provider(),
2933 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2935 return &solid_color_program_
;
2938 const GLRenderer::SolidColorProgramAA
* GLRenderer::GetSolidColorProgramAA() {
2939 if (!solid_color_program_aa_
.initialized()) {
2940 TRACE_EVENT0("cc", "GLRenderer::solidColorProgramAA::initialize");
2941 solid_color_program_aa_
.Initialize(output_surface_
->context_provider(),
2942 TEX_COORD_PRECISION_NA
, SAMPLER_TYPE_NA
);
2944 return &solid_color_program_aa_
;
2947 const GLRenderer::RenderPassProgram
* GLRenderer::GetRenderPassProgram(
2948 TexCoordPrecision precision
,
2949 BlendMode blend_mode
) {
2950 DCHECK_GE(precision
, 0);
2951 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
2952 DCHECK_GE(blend_mode
, 0);
2953 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
2954 RenderPassProgram
* program
= &render_pass_program_
[precision
][blend_mode
];
2955 if (!program
->initialized()) {
2956 TRACE_EVENT0("cc", "GLRenderer::renderPassProgram::initialize");
2957 program
->Initialize(output_surface_
->context_provider(), precision
,
2958 SAMPLER_TYPE_2D
, blend_mode
);
2963 const GLRenderer::RenderPassProgramAA
* GLRenderer::GetRenderPassProgramAA(
2964 TexCoordPrecision precision
,
2965 BlendMode blend_mode
) {
2966 DCHECK_GE(precision
, 0);
2967 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
2968 DCHECK_GE(blend_mode
, 0);
2969 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
2970 RenderPassProgramAA
* program
=
2971 &render_pass_program_aa_
[precision
][blend_mode
];
2972 if (!program
->initialized()) {
2973 TRACE_EVENT0("cc", "GLRenderer::renderPassProgramAA::initialize");
2974 program
->Initialize(output_surface_
->context_provider(), precision
,
2975 SAMPLER_TYPE_2D
, blend_mode
);
2980 const GLRenderer::RenderPassMaskProgram
* GLRenderer::GetRenderPassMaskProgram(
2981 TexCoordPrecision precision
,
2982 SamplerType sampler
,
2983 BlendMode blend_mode
,
2984 bool mask_for_background
) {
2985 DCHECK_GE(precision
, 0);
2986 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
2987 DCHECK_GE(sampler
, 0);
2988 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
2989 DCHECK_GE(blend_mode
, 0);
2990 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
2991 RenderPassMaskProgram
* program
=
2992 &render_pass_mask_program_
[precision
][sampler
][blend_mode
]
2993 [mask_for_background
? HAS_MASK
: NO_MASK
];
2994 if (!program
->initialized()) {
2995 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgram::initialize");
2996 program
->Initialize(
2997 output_surface_
->context_provider(), precision
,
2998 sampler
, blend_mode
, mask_for_background
);
3003 const GLRenderer::RenderPassMaskProgramAA
*
3004 GLRenderer::GetRenderPassMaskProgramAA(TexCoordPrecision precision
,
3005 SamplerType sampler
,
3006 BlendMode blend_mode
,
3007 bool mask_for_background
) {
3008 DCHECK_GE(precision
, 0);
3009 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3010 DCHECK_GE(sampler
, 0);
3011 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3012 DCHECK_GE(blend_mode
, 0);
3013 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3014 RenderPassMaskProgramAA
* program
=
3015 &render_pass_mask_program_aa_
[precision
][sampler
][blend_mode
]
3016 [mask_for_background
? HAS_MASK
: NO_MASK
];
3017 if (!program
->initialized()) {
3018 TRACE_EVENT0("cc", "GLRenderer::renderPassMaskProgramAA::initialize");
3019 program
->Initialize(
3020 output_surface_
->context_provider(), precision
,
3021 sampler
, blend_mode
, mask_for_background
);
3026 const GLRenderer::RenderPassColorMatrixProgram
*
3027 GLRenderer::GetRenderPassColorMatrixProgram(TexCoordPrecision precision
,
3028 BlendMode blend_mode
) {
3029 DCHECK_GE(precision
, 0);
3030 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3031 DCHECK_GE(blend_mode
, 0);
3032 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3033 RenderPassColorMatrixProgram
* program
=
3034 &render_pass_color_matrix_program_
[precision
][blend_mode
];
3035 if (!program
->initialized()) {
3036 TRACE_EVENT0("cc", "GLRenderer::renderPassColorMatrixProgram::initialize");
3037 program
->Initialize(output_surface_
->context_provider(), precision
,
3038 SAMPLER_TYPE_2D
, blend_mode
);
3043 const GLRenderer::RenderPassColorMatrixProgramAA
*
3044 GLRenderer::GetRenderPassColorMatrixProgramAA(TexCoordPrecision precision
,
3045 BlendMode blend_mode
) {
3046 DCHECK_GE(precision
, 0);
3047 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3048 DCHECK_GE(blend_mode
, 0);
3049 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3050 RenderPassColorMatrixProgramAA
* program
=
3051 &render_pass_color_matrix_program_aa_
[precision
][blend_mode
];
3052 if (!program
->initialized()) {
3054 "GLRenderer::renderPassColorMatrixProgramAA::initialize");
3055 program
->Initialize(output_surface_
->context_provider(), precision
,
3056 SAMPLER_TYPE_2D
, blend_mode
);
3061 const GLRenderer::RenderPassMaskColorMatrixProgram
*
3062 GLRenderer::GetRenderPassMaskColorMatrixProgram(
3063 TexCoordPrecision precision
,
3064 SamplerType sampler
,
3065 BlendMode blend_mode
,
3066 bool mask_for_background
) {
3067 DCHECK_GE(precision
, 0);
3068 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3069 DCHECK_GE(sampler
, 0);
3070 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3071 DCHECK_GE(blend_mode
, 0);
3072 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3073 RenderPassMaskColorMatrixProgram
* program
=
3074 &render_pass_mask_color_matrix_program_
[precision
][sampler
][blend_mode
]
3075 [mask_for_background
? HAS_MASK
: NO_MASK
];
3076 if (!program
->initialized()) {
3078 "GLRenderer::renderPassMaskColorMatrixProgram::initialize");
3079 program
->Initialize(
3080 output_surface_
->context_provider(), precision
,
3081 sampler
, blend_mode
, mask_for_background
);
3086 const GLRenderer::RenderPassMaskColorMatrixProgramAA
*
3087 GLRenderer::GetRenderPassMaskColorMatrixProgramAA(
3088 TexCoordPrecision precision
,
3089 SamplerType sampler
,
3090 BlendMode blend_mode
,
3091 bool mask_for_background
) {
3092 DCHECK_GE(precision
, 0);
3093 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3094 DCHECK_GE(sampler
, 0);
3095 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3096 DCHECK_GE(blend_mode
, 0);
3097 DCHECK_LE(blend_mode
, LAST_BLEND_MODE
);
3098 RenderPassMaskColorMatrixProgramAA
* program
=
3099 &render_pass_mask_color_matrix_program_aa_
[precision
][sampler
][blend_mode
]
3100 [mask_for_background
? HAS_MASK
: NO_MASK
];
3101 if (!program
->initialized()) {
3103 "GLRenderer::renderPassMaskColorMatrixProgramAA::initialize");
3104 program
->Initialize(
3105 output_surface_
->context_provider(), precision
,
3106 sampler
, blend_mode
, mask_for_background
);
3111 const GLRenderer::TileProgram
* GLRenderer::GetTileProgram(
3112 TexCoordPrecision precision
,
3113 SamplerType sampler
) {
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 TileProgram
* program
= &tile_program_
[precision
][sampler
];
3119 if (!program
->initialized()) {
3120 TRACE_EVENT0("cc", "GLRenderer::tileProgram::initialize");
3121 program
->Initialize(
3122 output_surface_
->context_provider(), precision
, sampler
);
3127 const GLRenderer::TileProgramOpaque
* GLRenderer::GetTileProgramOpaque(
3128 TexCoordPrecision precision
,
3129 SamplerType sampler
) {
3130 DCHECK_GE(precision
, 0);
3131 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3132 DCHECK_GE(sampler
, 0);
3133 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3134 TileProgramOpaque
* program
= &tile_program_opaque_
[precision
][sampler
];
3135 if (!program
->initialized()) {
3136 TRACE_EVENT0("cc", "GLRenderer::tileProgramOpaque::initialize");
3137 program
->Initialize(
3138 output_surface_
->context_provider(), precision
, sampler
);
3143 const GLRenderer::TileProgramAA
* GLRenderer::GetTileProgramAA(
3144 TexCoordPrecision precision
,
3145 SamplerType sampler
) {
3146 DCHECK_GE(precision
, 0);
3147 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3148 DCHECK_GE(sampler
, 0);
3149 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3150 TileProgramAA
* program
= &tile_program_aa_
[precision
][sampler
];
3151 if (!program
->initialized()) {
3152 TRACE_EVENT0("cc", "GLRenderer::tileProgramAA::initialize");
3153 program
->Initialize(
3154 output_surface_
->context_provider(), precision
, sampler
);
3159 const GLRenderer::TileProgramSwizzle
* GLRenderer::GetTileProgramSwizzle(
3160 TexCoordPrecision precision
,
3161 SamplerType sampler
) {
3162 DCHECK_GE(precision
, 0);
3163 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3164 DCHECK_GE(sampler
, 0);
3165 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3166 TileProgramSwizzle
* program
= &tile_program_swizzle_
[precision
][sampler
];
3167 if (!program
->initialized()) {
3168 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzle::initialize");
3169 program
->Initialize(
3170 output_surface_
->context_provider(), precision
, sampler
);
3175 const GLRenderer::TileProgramSwizzleOpaque
*
3176 GLRenderer::GetTileProgramSwizzleOpaque(TexCoordPrecision precision
,
3177 SamplerType sampler
) {
3178 DCHECK_GE(precision
, 0);
3179 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3180 DCHECK_GE(sampler
, 0);
3181 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3182 TileProgramSwizzleOpaque
* program
=
3183 &tile_program_swizzle_opaque_
[precision
][sampler
];
3184 if (!program
->initialized()) {
3185 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleOpaque::initialize");
3186 program
->Initialize(
3187 output_surface_
->context_provider(), precision
, sampler
);
3192 const GLRenderer::TileProgramSwizzleAA
* GLRenderer::GetTileProgramSwizzleAA(
3193 TexCoordPrecision precision
,
3194 SamplerType sampler
) {
3195 DCHECK_GE(precision
, 0);
3196 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3197 DCHECK_GE(sampler
, 0);
3198 DCHECK_LE(sampler
, LAST_SAMPLER_TYPE
);
3199 TileProgramSwizzleAA
* program
= &tile_program_swizzle_aa_
[precision
][sampler
];
3200 if (!program
->initialized()) {
3201 TRACE_EVENT0("cc", "GLRenderer::tileProgramSwizzleAA::initialize");
3202 program
->Initialize(
3203 output_surface_
->context_provider(), precision
, sampler
);
3208 const GLRenderer::TextureProgram
* GLRenderer::GetTextureProgram(
3209 TexCoordPrecision precision
) {
3210 DCHECK_GE(precision
, 0);
3211 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3212 TextureProgram
* program
= &texture_program_
[precision
];
3213 if (!program
->initialized()) {
3214 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3215 program
->Initialize(output_surface_
->context_provider(), precision
,
3221 const GLRenderer::NonPremultipliedTextureProgram
*
3222 GLRenderer::GetNonPremultipliedTextureProgram(TexCoordPrecision precision
) {
3223 DCHECK_GE(precision
, 0);
3224 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3225 NonPremultipliedTextureProgram
* program
=
3226 &nonpremultiplied_texture_program_
[precision
];
3227 if (!program
->initialized()) {
3229 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3230 program
->Initialize(output_surface_
->context_provider(), precision
,
3236 const GLRenderer::TextureBackgroundProgram
*
3237 GLRenderer::GetTextureBackgroundProgram(TexCoordPrecision precision
) {
3238 DCHECK_GE(precision
, 0);
3239 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3240 TextureBackgroundProgram
* program
= &texture_background_program_
[precision
];
3241 if (!program
->initialized()) {
3242 TRACE_EVENT0("cc", "GLRenderer::textureProgram::initialize");
3243 program
->Initialize(output_surface_
->context_provider(), precision
,
3249 const GLRenderer::NonPremultipliedTextureBackgroundProgram
*
3250 GLRenderer::GetNonPremultipliedTextureBackgroundProgram(
3251 TexCoordPrecision precision
) {
3252 DCHECK_GE(precision
, 0);
3253 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3254 NonPremultipliedTextureBackgroundProgram
* program
=
3255 &nonpremultiplied_texture_background_program_
[precision
];
3256 if (!program
->initialized()) {
3258 "GLRenderer::NonPremultipliedTextureProgram::Initialize");
3259 program
->Initialize(output_surface_
->context_provider(), precision
,
3265 const GLRenderer::TextureProgram
* GLRenderer::GetTextureIOSurfaceProgram(
3266 TexCoordPrecision precision
) {
3267 DCHECK_GE(precision
, 0);
3268 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3269 TextureProgram
* program
= &texture_io_surface_program_
[precision
];
3270 if (!program
->initialized()) {
3271 TRACE_EVENT0("cc", "GLRenderer::textureIOSurfaceProgram::initialize");
3272 program
->Initialize(output_surface_
->context_provider(), precision
,
3273 SAMPLER_TYPE_2D_RECT
);
3278 const GLRenderer::VideoYUVProgram
* GLRenderer::GetVideoYUVProgram(
3279 TexCoordPrecision precision
) {
3280 DCHECK_GE(precision
, 0);
3281 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3282 VideoYUVProgram
* program
= &video_yuv_program_
[precision
];
3283 if (!program
->initialized()) {
3284 TRACE_EVENT0("cc", "GLRenderer::videoYUVProgram::initialize");
3285 program
->Initialize(output_surface_
->context_provider(), precision
,
3291 const GLRenderer::VideoYUVAProgram
* GLRenderer::GetVideoYUVAProgram(
3292 TexCoordPrecision precision
) {
3293 DCHECK_GE(precision
, 0);
3294 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3295 VideoYUVAProgram
* program
= &video_yuva_program_
[precision
];
3296 if (!program
->initialized()) {
3297 TRACE_EVENT0("cc", "GLRenderer::videoYUVAProgram::initialize");
3298 program
->Initialize(output_surface_
->context_provider(), precision
,
3304 const GLRenderer::VideoStreamTextureProgram
*
3305 GLRenderer::GetVideoStreamTextureProgram(TexCoordPrecision precision
) {
3306 if (!Capabilities().using_egl_image
)
3308 DCHECK_GE(precision
, 0);
3309 DCHECK_LE(precision
, LAST_TEX_COORD_PRECISION
);
3310 VideoStreamTextureProgram
* program
=
3311 &video_stream_texture_program_
[precision
];
3312 if (!program
->initialized()) {
3313 TRACE_EVENT0("cc", "GLRenderer::streamTextureProgram::initialize");
3314 program
->Initialize(output_surface_
->context_provider(), precision
,
3315 SAMPLER_TYPE_EXTERNAL_OES
);
3320 void GLRenderer::CleanupSharedObjects() {
3321 shared_geometry_
= nullptr;
3323 for (int i
= 0; i
<= LAST_TEX_COORD_PRECISION
; ++i
) {
3324 for (int j
= 0; j
<= LAST_SAMPLER_TYPE
; ++j
) {
3325 tile_program_
[i
][j
].Cleanup(gl_
);
3326 tile_program_opaque_
[i
][j
].Cleanup(gl_
);
3327 tile_program_swizzle_
[i
][j
].Cleanup(gl_
);
3328 tile_program_swizzle_opaque_
[i
][j
].Cleanup(gl_
);
3329 tile_program_aa_
[i
][j
].Cleanup(gl_
);
3330 tile_program_swizzle_aa_
[i
][j
].Cleanup(gl_
);
3332 for (int k
= 0; k
<= LAST_BLEND_MODE
; k
++) {
3333 for (int l
= 0; l
<= LAST_MASK_VALUE
; ++l
) {
3334 render_pass_mask_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3335 render_pass_mask_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3336 render_pass_mask_color_matrix_program_aa_
[i
][j
][k
][l
].Cleanup(gl_
);
3337 render_pass_mask_color_matrix_program_
[i
][j
][k
][l
].Cleanup(gl_
);
3341 for (int j
= 0; j
<= LAST_BLEND_MODE
; j
++) {
3342 render_pass_program_
[i
][j
].Cleanup(gl_
);
3343 render_pass_program_aa_
[i
][j
].Cleanup(gl_
);
3344 render_pass_color_matrix_program_
[i
][j
].Cleanup(gl_
);
3345 render_pass_color_matrix_program_aa_
[i
][j
].Cleanup(gl_
);
3348 texture_program_
[i
].Cleanup(gl_
);
3349 nonpremultiplied_texture_program_
[i
].Cleanup(gl_
);
3350 texture_background_program_
[i
].Cleanup(gl_
);
3351 nonpremultiplied_texture_background_program_
[i
].Cleanup(gl_
);
3352 texture_io_surface_program_
[i
].Cleanup(gl_
);
3354 video_yuv_program_
[i
].Cleanup(gl_
);
3355 video_yuva_program_
[i
].Cleanup(gl_
);
3356 video_stream_texture_program_
[i
].Cleanup(gl_
);
3359 tile_checkerboard_program_
.Cleanup(gl_
);
3361 debug_border_program_
.Cleanup(gl_
);
3362 solid_color_program_
.Cleanup(gl_
);
3363 solid_color_program_aa_
.Cleanup(gl_
);
3365 if (offscreen_framebuffer_id_
)
3366 gl_
->DeleteFramebuffers(1, &offscreen_framebuffer_id_
);
3368 if (on_demand_tile_raster_resource_id_
)
3369 resource_provider_
->DeleteResource(on_demand_tile_raster_resource_id_
);
3371 ReleaseRenderPassTextures();
3374 void GLRenderer::ReinitializeGLState() {
3375 is_scissor_enabled_
= false;
3376 scissor_rect_needs_reset_
= true;
3377 stencil_shadow_
= false;
3378 blend_shadow_
= true;
3379 program_shadow_
= 0;
3384 void GLRenderer::RestoreGLState() {
3385 // This restores the current GLRenderer state to the GL context.
3386 bound_geometry_
= NO_BINDING
;
3387 PrepareGeometry(SHARED_BINDING
);
3389 gl_
->Disable(GL_DEPTH_TEST
);
3390 gl_
->Disable(GL_CULL_FACE
);
3391 gl_
->ColorMask(true, true, true, true);
3392 gl_
->BlendFunc(GL_ONE
, GL_ONE_MINUS_SRC_ALPHA
);
3393 gl_
->ActiveTexture(GL_TEXTURE0
);
3395 if (program_shadow_
)
3396 gl_
->UseProgram(program_shadow_
);
3398 if (stencil_shadow_
)
3399 gl_
->Enable(GL_STENCIL_TEST
);
3401 gl_
->Disable(GL_STENCIL_TEST
);
3404 gl_
->Enable(GL_BLEND
);
3406 gl_
->Disable(GL_BLEND
);
3408 if (is_scissor_enabled_
) {
3409 gl_
->Enable(GL_SCISSOR_TEST
);
3410 gl_
->Scissor(scissor_rect_
.x(), scissor_rect_
.y(), scissor_rect_
.width(),
3411 scissor_rect_
.height());
3413 gl_
->Disable(GL_SCISSOR_TEST
);
3417 void GLRenderer::RestoreFramebuffer(DrawingFrame
* frame
) {
3418 UseRenderPass(frame
, frame
->current_render_pass
);
3420 // Call SetViewport directly, rather than through PrepareSurfaceForPass.
3421 // PrepareSurfaceForPass also clears the surface, which is not desired when
3426 bool GLRenderer::IsContextLost() {
3427 return output_surface_
->context_provider()->IsContextLost();
3430 void GLRenderer::ScheduleOverlays(DrawingFrame
* frame
) {
3431 if (!frame
->overlay_list
.size())
3434 ResourceProvider::ResourceIdArray resources
;
3435 OverlayCandidateList
& overlays
= frame
->overlay_list
;
3436 OverlayCandidateList::iterator it
;
3437 for (it
= overlays
.begin(); it
!= overlays
.end(); ++it
) {
3438 const OverlayCandidate
& overlay
= *it
;
3439 // Skip primary plane.
3440 if (overlay
.plane_z_order
== 0)
3443 pending_overlay_resources_
.push_back(
3444 make_scoped_ptr(new ResourceProvider::ScopedReadLockGL(
3445 resource_provider_
, overlay
.resource_id
)));
3447 context_support_
->ScheduleOverlayPlane(
3448 overlay
.plane_z_order
,
3450 pending_overlay_resources_
.back()->texture_id(),
3451 overlay
.display_rect
,