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