Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / cc / output / direct_renderer.cc
1 // Copyright 2012 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.
4
5 #include "cc/output/direct_renderer.h"
6
7 #include <utility>
8 #include <vector>
9
10 #include "base/containers/hash_tables.h"
11 #include "base/containers/scoped_ptr_hash_map.h"
12 #include "base/debug/trace_event.h"
13 #include "base/metrics/histogram.h"
14 #include "cc/base/math_util.h"
15 #include "cc/output/copy_output_request.h"
16 #include "cc/quads/draw_quad.h"
17 #include "ui/gfx/rect_conversions.h"
18 #include "ui/gfx/transform.h"
19
20 static gfx::Transform OrthoProjectionMatrix(float left,
21                                             float right,
22                                             float bottom,
23                                             float top) {
24   // Use the standard formula to map the clipping frustum to the cube from
25   // [-1, -1, -1] to [1, 1, 1].
26   float delta_x = right - left;
27   float delta_y = top - bottom;
28   gfx::Transform proj;
29   if (!delta_x || !delta_y)
30     return proj;
31   proj.matrix().set(0, 0, 2.0f / delta_x);
32   proj.matrix().set(0, 3, -(right + left) / delta_x);
33   proj.matrix().set(1, 1, 2.0f / delta_y);
34   proj.matrix().set(1, 3, -(top + bottom) / delta_y);
35
36   // Z component of vertices is always set to zero as we don't use the depth
37   // buffer while drawing.
38   proj.matrix().set(2, 2, 0);
39
40   return proj;
41 }
42
43 static gfx::Transform window_matrix(int x, int y, int width, int height) {
44   gfx::Transform canvas;
45
46   // Map to window position and scale up to pixel coordinates.
47   canvas.Translate3d(x, y, 0);
48   canvas.Scale3d(width, height, 0);
49
50   // Map from ([-1, -1] to [1, 1]) -> ([0, 0] to [1, 1])
51   canvas.Translate3d(0.5, 0.5, 0.5);
52   canvas.Scale3d(0.5, 0.5, 0.5);
53
54   return canvas;
55 }
56
57 namespace cc {
58
59 DirectRenderer::DrawingFrame::DrawingFrame()
60     : root_render_pass(NULL),
61       current_render_pass(NULL),
62       current_texture(NULL),
63       offscreen_context_provider(NULL) {}
64
65 DirectRenderer::DrawingFrame::~DrawingFrame() {}
66
67 //
68 // static
69 gfx::RectF DirectRenderer::QuadVertexRect() {
70   return gfx::RectF(-0.5f, -0.5f, 1.f, 1.f);
71 }
72
73 // static
74 void DirectRenderer::QuadRectTransform(gfx::Transform* quad_rect_transform,
75                                        const gfx::Transform& quad_transform,
76                                        const gfx::RectF& quad_rect) {
77   *quad_rect_transform = quad_transform;
78   quad_rect_transform->Translate(0.5 * quad_rect.width() + quad_rect.x(),
79                                  0.5 * quad_rect.height() + quad_rect.y());
80   quad_rect_transform->Scale(quad_rect.width(), quad_rect.height());
81 }
82
83 void DirectRenderer::InitializeViewport(DrawingFrame* frame,
84                                         const gfx::Rect& draw_rect,
85                                         const gfx::Rect& viewport_rect,
86                                         gfx::Size surface_size) {
87   bool flip_y = FlippedFramebuffer();
88
89   DCHECK_GE(viewport_rect.x(), 0);
90   DCHECK_GE(viewport_rect.y(), 0);
91   DCHECK_LE(viewport_rect.right(), surface_size.width());
92   DCHECK_LE(viewport_rect.bottom(), surface_size.height());
93   if (flip_y) {
94     frame->projection_matrix = OrthoProjectionMatrix(draw_rect.x(),
95                                                      draw_rect.right(),
96                                                      draw_rect.bottom(),
97                                                      draw_rect.y());
98   } else {
99     frame->projection_matrix = OrthoProjectionMatrix(draw_rect.x(),
100                                                      draw_rect.right(),
101                                                      draw_rect.y(),
102                                                      draw_rect.bottom());
103   }
104
105   gfx::Rect window_rect = viewport_rect;
106   if (flip_y)
107     window_rect.set_y(surface_size.height() - viewport_rect.bottom());
108   frame->window_matrix = window_matrix(window_rect.x(),
109                                        window_rect.y(),
110                                        window_rect.width(),
111                                        window_rect.height());
112   SetDrawViewport(window_rect);
113
114   current_draw_rect_ = draw_rect;
115   current_viewport_rect_ = viewport_rect;
116   current_surface_size_ = surface_size;
117 }
118
119 gfx::Rect DirectRenderer::MoveFromDrawToWindowSpace(
120     const gfx::RectF& draw_rect) const {
121   gfx::Rect window_rect = gfx::ToEnclosingRect(draw_rect);
122   window_rect -= current_draw_rect_.OffsetFromOrigin();
123   window_rect += current_viewport_rect_.OffsetFromOrigin();
124   if (FlippedFramebuffer())
125     window_rect.set_y(current_surface_size_.height() - window_rect.bottom());
126   return window_rect;
127 }
128
129 DirectRenderer::DirectRenderer(RendererClient* client,
130                                const LayerTreeSettings* settings,
131                                OutputSurface* output_surface,
132                                ResourceProvider* resource_provider)
133     : Renderer(client, settings),
134       output_surface_(output_surface),
135       resource_provider_(resource_provider) {}
136
137 DirectRenderer::~DirectRenderer() {}
138
139 bool DirectRenderer::CanReadPixels() const { return true; }
140
141 void DirectRenderer::SetEnlargePassTextureAmountForTesting(
142     gfx::Vector2d amount) {
143   enlarge_pass_texture_amount_ = amount;
144 }
145
146 void DirectRenderer::DecideRenderPassAllocationsForFrame(
147     const RenderPassList& render_passes_in_draw_order) {
148   if (!resource_provider_)
149     return;
150
151   base::hash_map<RenderPass::Id, gfx::Size> render_passes_in_frame;
152   for (size_t i = 0; i < render_passes_in_draw_order.size(); ++i)
153     render_passes_in_frame.insert(std::pair<RenderPass::Id, gfx::Size>(
154         render_passes_in_draw_order[i]->id,
155         RenderPassTextureSize(render_passes_in_draw_order[i])));
156
157   std::vector<RenderPass::Id> passes_to_delete;
158   base::ScopedPtrHashMap<RenderPass::Id, ScopedResource>::const_iterator
159       pass_iter;
160   for (pass_iter = render_pass_textures_.begin();
161        pass_iter != render_pass_textures_.end();
162        ++pass_iter) {
163     base::hash_map<RenderPass::Id, gfx::Size>::const_iterator it =
164         render_passes_in_frame.find(pass_iter->first);
165     if (it == render_passes_in_frame.end()) {
166       passes_to_delete.push_back(pass_iter->first);
167       continue;
168     }
169
170     gfx::Size required_size = it->second;
171     ScopedResource* texture = pass_iter->second;
172     DCHECK(texture);
173
174     bool size_appropriate = texture->size().width() >= required_size.width() &&
175                             texture->size().height() >= required_size.height();
176     if (texture->id() && !size_appropriate)
177       texture->Free();
178   }
179
180   // Delete RenderPass textures from the previous frame that will not be used
181   // again.
182   for (size_t i = 0; i < passes_to_delete.size(); ++i)
183     render_pass_textures_.erase(passes_to_delete[i]);
184
185   for (size_t i = 0; i < render_passes_in_draw_order.size(); ++i) {
186     if (!render_pass_textures_.contains(render_passes_in_draw_order[i]->id)) {
187       scoped_ptr<ScopedResource> texture =
188           ScopedResource::Create(resource_provider_);
189       render_pass_textures_.set(render_passes_in_draw_order[i]->id,
190                               texture.Pass());
191     }
192   }
193 }
194
195 void DirectRenderer::DrawFrame(RenderPassList* render_passes_in_draw_order,
196                                ContextProvider* offscreen_context_provider,
197                                float device_scale_factor,
198                                const gfx::Rect& device_viewport_rect,
199                                const gfx::Rect& device_clip_rect,
200                                bool allow_partial_swap,
201                                bool disable_picture_quad_image_filtering) {
202   TRACE_EVENT0("cc", "DirectRenderer::DrawFrame");
203   UMA_HISTOGRAM_COUNTS("Renderer4.renderPassCount",
204                        render_passes_in_draw_order->size());
205
206   const RenderPass* root_render_pass = render_passes_in_draw_order->back();
207   DCHECK(root_render_pass);
208
209   DrawingFrame frame;
210   frame.root_render_pass = root_render_pass;
211   frame.root_damage_rect =
212       Capabilities().using_partial_swap && allow_partial_swap
213           ? root_render_pass->damage_rect
214           : root_render_pass->output_rect;
215   frame.root_damage_rect.Intersect(gfx::Rect(device_viewport_rect.size()));
216   frame.device_viewport_rect = device_viewport_rect;
217   frame.device_clip_rect = device_clip_rect;
218   frame.offscreen_context_provider = offscreen_context_provider;
219   frame.disable_picture_quad_image_filtering =
220       disable_picture_quad_image_filtering;
221
222   EnsureBackbuffer();
223
224   // Only reshape when we know we are going to draw. Otherwise, the reshape
225   // can leave the window at the wrong size if we never draw and the proper
226   // viewport size is never set.
227   output_surface_->Reshape(device_viewport_rect.size(), device_scale_factor);
228
229   BeginDrawingFrame(&frame);
230   for (size_t i = 0; i < render_passes_in_draw_order->size(); ++i) {
231     RenderPass* pass = render_passes_in_draw_order->at(i);
232     DrawRenderPass(&frame, pass, allow_partial_swap);
233
234     for (ScopedPtrVector<CopyOutputRequest>::iterator it =
235              pass->copy_requests.begin();
236          it != pass->copy_requests.end();
237          ++it) {
238       if (i > 0) {
239         // Doing a readback is destructive of our state on Mac, so make sure
240         // we restore the state between readbacks. http://crbug.com/99393.
241         UseRenderPass(&frame, pass);
242       }
243       CopyCurrentRenderPassToBitmap(&frame, pass->copy_requests.take(it));
244     }
245   }
246   FinishDrawingFrame(&frame);
247
248   render_passes_in_draw_order->clear();
249 }
250
251 gfx::RectF DirectRenderer::ComputeScissorRectForRenderPass(
252     const DrawingFrame* frame) {
253   gfx::RectF render_pass_scissor = frame->current_render_pass->output_rect;
254
255   if (frame->root_damage_rect == frame->root_render_pass->output_rect)
256     return render_pass_scissor;
257
258   gfx::Transform inverse_transform(gfx::Transform::kSkipInitialization);
259   if (frame->current_render_pass->transform_to_root_target.GetInverse(
260           &inverse_transform)) {
261     // Only intersect inverse-projected damage if the transform is invertible.
262     gfx::RectF damage_rect_in_render_pass_space =
263         MathUtil::ProjectClippedRect(inverse_transform,
264                                      frame->root_damage_rect);
265     render_pass_scissor.Intersect(damage_rect_in_render_pass_space);
266   }
267
268   return render_pass_scissor;
269 }
270
271 bool DirectRenderer::NeedDeviceClip(const DrawingFrame* frame) const {
272   if (frame->current_render_pass != frame->root_render_pass)
273     return false;
274
275   return !frame->device_clip_rect.Contains(frame->device_viewport_rect);
276 }
277
278 gfx::Rect DirectRenderer::DeviceClipRectInWindowSpace(const DrawingFrame* frame)
279     const {
280   gfx::Rect device_clip_rect = frame->device_clip_rect;
281   if (FlippedFramebuffer())
282     device_clip_rect.set_y(current_surface_size_.height() -
283                            device_clip_rect.bottom());
284   return device_clip_rect;
285 }
286
287 void DirectRenderer::SetScissorStateForQuad(const DrawingFrame* frame,
288                                             const DrawQuad& quad) {
289   if (quad.isClipped()) {
290     SetScissorTestRectInDrawSpace(frame, quad.clipRect());
291     return;
292   }
293   if (NeedDeviceClip(frame)) {
294     SetScissorTestRect(DeviceClipRectInWindowSpace(frame));
295     return;
296   }
297
298   EnsureScissorTestDisabled();
299 }
300
301 void DirectRenderer::SetScissorStateForQuadWithRenderPassScissor(
302     const DrawingFrame* frame,
303     const DrawQuad& quad,
304     const gfx::RectF& render_pass_scissor,
305     bool* should_skip_quad) {
306   gfx::RectF quad_scissor_rect = render_pass_scissor;
307
308   if (quad.isClipped())
309     quad_scissor_rect.Intersect(quad.clipRect());
310
311   if (quad_scissor_rect.IsEmpty()) {
312     *should_skip_quad = true;
313     return;
314   }
315
316   *should_skip_quad = false;
317   SetScissorTestRectInDrawSpace(frame, quad_scissor_rect);
318 }
319
320 void DirectRenderer::SetScissorTestRectInDrawSpace(
321     const DrawingFrame* frame,
322     const gfx::RectF& draw_space_rect) {
323   gfx::Rect window_space_rect = MoveFromDrawToWindowSpace(draw_space_rect);
324   if (NeedDeviceClip(frame))
325     window_space_rect.Intersect(DeviceClipRectInWindowSpace(frame));
326   SetScissorTestRect(window_space_rect);
327 }
328
329 void DirectRenderer::FinishDrawingQuadList() {}
330
331 void DirectRenderer::DrawRenderPass(DrawingFrame* frame,
332                                     const RenderPass* render_pass,
333                                     bool allow_partial_swap) {
334   TRACE_EVENT0("cc", "DirectRenderer::DrawRenderPass");
335   if (!UseRenderPass(frame, render_pass))
336     return;
337
338   bool using_scissor_as_optimization =
339       Capabilities().using_partial_swap && allow_partial_swap;
340   gfx::RectF render_pass_scissor;
341   bool draw_rect_covers_full_surface = true;
342   if (frame->current_render_pass == frame->root_render_pass &&
343       !frame->device_viewport_rect.Contains(
344            gfx::Rect(output_surface_->SurfaceSize())))
345     draw_rect_covers_full_surface = false;
346
347   if (using_scissor_as_optimization) {
348     render_pass_scissor = ComputeScissorRectForRenderPass(frame);
349     SetScissorTestRectInDrawSpace(frame, render_pass_scissor);
350     if (!render_pass_scissor.Contains(frame->current_render_pass->output_rect))
351       draw_rect_covers_full_surface = false;
352   }
353
354   if (frame->current_render_pass != frame->root_render_pass ||
355       settings_->should_clear_root_render_pass) {
356     if (NeedDeviceClip(frame)) {
357       SetScissorTestRect(DeviceClipRectInWindowSpace(frame));
358       draw_rect_covers_full_surface = false;
359     } else if (!using_scissor_as_optimization) {
360       EnsureScissorTestDisabled();
361     }
362
363     bool has_external_stencil_test =
364         output_surface_->HasExternalStencilTest() &&
365         frame->current_render_pass == frame->root_render_pass;
366
367     DiscardPixels(has_external_stencil_test, draw_rect_covers_full_surface);
368     ClearFramebuffer(frame, has_external_stencil_test);
369   }
370
371   const QuadList& quad_list = render_pass->quad_list;
372   for (QuadList::ConstBackToFrontIterator it = quad_list.BackToFrontBegin();
373        it != quad_list.BackToFrontEnd();
374        ++it) {
375     const DrawQuad& quad = *(*it);
376     bool should_skip_quad = false;
377
378     if (using_scissor_as_optimization) {
379       SetScissorStateForQuadWithRenderPassScissor(
380           frame, quad, render_pass_scissor, &should_skip_quad);
381     } else {
382       SetScissorStateForQuad(frame, quad);
383     }
384
385     if (!should_skip_quad)
386       DoDrawQuad(frame, *it);
387   }
388   FinishDrawingQuadList();
389 }
390
391 bool DirectRenderer::UseRenderPass(DrawingFrame* frame,
392                                    const RenderPass* render_pass) {
393   frame->current_render_pass = render_pass;
394   frame->current_texture = NULL;
395
396   if (render_pass == frame->root_render_pass) {
397     BindFramebufferToOutputSurface(frame);
398     InitializeViewport(frame,
399                        render_pass->output_rect,
400                        frame->device_viewport_rect,
401                        output_surface_->SurfaceSize());
402     return true;
403   }
404
405   ScopedResource* texture = render_pass_textures_.get(render_pass->id);
406   DCHECK(texture);
407
408   gfx::Size size = RenderPassTextureSize(render_pass);
409   size.Enlarge(enlarge_pass_texture_amount_.x(),
410                enlarge_pass_texture_amount_.y());
411   if (!texture->id())
412     texture->Allocate(
413         size, ResourceProvider::TextureUsageFramebuffer, RGBA_8888);
414   DCHECK(texture->id());
415
416   return BindFramebufferToTexture(frame, texture, render_pass->output_rect);
417 }
418
419 bool DirectRenderer::HasAllocatedResourcesForTesting(RenderPass::Id id)
420     const {
421   ScopedResource* texture = render_pass_textures_.get(id);
422   return texture && texture->id();
423 }
424
425 // static
426 gfx::Size DirectRenderer::RenderPassTextureSize(const RenderPass* render_pass) {
427   return render_pass->output_rect.size();
428 }
429
430 }  // namespace cc