summaryrefslogtreecommitdiffstats
path: root/ui/gfx/compositor/compositor_gl.cc
blob: 7e6e297cf570ecb375d138b3b3c8b578434c573c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/compositor/compositor.h"

#include <GL/gl.h>

#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkMatrix.h"
#include "third_party/skia/include/core/SkScalar.h"
#include "ui/gfx/rect.h"
#include "ui/gfx/transform.h"
#include "ui/gfx/gl/gl_bindings.h"
#include "ui/gfx/gl/gl_context.h"
#include "ui/gfx/gl/gl_implementation.h"
#include "ui/gfx/gl/gl_surface.h"
#include "ui/gfx/gl/gl_surface_glx.h"

namespace ui {

#if defined COMPOSITOR_2
namespace glHidden {

class CompositorGL;

class TextureGL : public Texture {
 public:
  TextureGL(CompositorGL* compositor);
  virtual ~TextureGL();

  virtual void SetBitmap(const SkBitmap& bitmap,
                         const gfx::Point& origin,
                         const gfx::Size& overall_size) OVERRIDE;

  // Draws the texture.
  virtual void Draw(const ui::Transform& transform) OVERRIDE;

 private:
  unsigned int texture_id_;
  gfx::Size size_;
  CompositorGL* compositor_;
  DISALLOW_COPY_AND_ASSIGN(TextureGL);
};

class CompositorGL : public Compositor {
 public:
  explicit CompositorGL(gfx::AcceleratedWidget widget);
  virtual ~CompositorGL();

  void MakeCurrent();
  gfx::Size GetSize();

  GLuint program();
  GLuint a_pos_loc();
  GLuint a_tex_loc();
  GLuint u_tex_loc();
  GLuint u_mat_loc();

 private:
  // Overridden from Compositor.
  virtual Texture* CreateTexture() OVERRIDE;
  virtual void NotifyStart() OVERRIDE;
  virtual void NotifyEnd() OVERRIDE;

  // Specific to CompositorGL.
  bool InitShaders();

  // The GL context used for compositing.
  scoped_refptr<gfx::GLSurface> gl_surface_;
  scoped_refptr<gfx::GLContext> gl_context_;
  gfx::Size size_;

  // Shader program, attributes and uniforms.
  // TODO(wjmaclean): Make these static so they ca be shared in a single
  // context.
  GLuint program_;
  GLuint a_pos_loc_;
  GLuint a_tex_loc_;
  GLuint u_tex_loc_;
  GLuint u_mat_loc_;

  // Keep track of whether compositing has started or not.
  bool started_;

  DISALLOW_COPY_AND_ASSIGN(CompositorGL);
};

TextureGL::TextureGL(CompositorGL* compositor) : texture_id_(0),
                                                 compositor_(compositor) {
}

TextureGL::~TextureGL() {
  if (texture_id_) {
    compositor_->MakeCurrent();
    glDeleteTextures(1, &texture_id_);
  }
}

void TextureGL::SetBitmap(const SkBitmap& bitmap,
                          const gfx::Point& origin,
                          const gfx::Size& overall_size) {
  // Verify bitmap pixels are contiguous.
  DCHECK_EQ(bitmap.rowBytes(),
            SkBitmap::ComputeRowBytes(bitmap.config(), bitmap.width()));
  SkAutoLockPixels lock (bitmap);
  void* pixels = bitmap.getPixels();

  if (!texture_id_) {
    // Texture needs to be created. We assume the first call is for
    // a full-sized canvas.
    size_ = overall_size;

    glGenTextures(1, &texture_id_);
    glBindTexture(GL_TEXTURE_2D, texture_id_);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 size_.width(), size_.height(), 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, pixels);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  } else if (size_ != overall_size) {  // Size has changed.
    size_ = overall_size;
    glBindTexture(GL_TEXTURE_2D, texture_id_);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 size_.width(), size_.height(), 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  } else {  // Uploading partial texture.
    glBindTexture(GL_TEXTURE_2D, texture_id_);
    glTexSubImage2D(GL_TEXTURE_2D, 0, origin.x(), origin.y(),
                    bitmap.width(), bitmap.height(),
                    GL_RGBA, GL_UNSIGNED_BYTE, pixels);
  }
}

void TextureGL::Draw(const ui::Transform& transform) {
  gfx::Size window_size = compositor_->GetSize();

  ui::Transform t;
  t.ConcatTranslate(1,1);
  t.ConcatScale(size_.width()/2.0f, size_.height()/2.0f);
  t.ConcatTranslate(0, -size_.height());
  t.ConcatScale(1, -1);

  t.ConcatTransform(transform); // Add view transform.

  t.ConcatTranslate(0, -window_size.height());
  t.ConcatScale(1, -1);
  t.ConcatTranslate(-window_size.width()/2.0f, -window_size.height()/2.0f);
  t.ConcatScale(2.0f/window_size.width(), 2.0f/window_size.height());

  DCHECK(compositor_->program());
  glUseProgram(compositor_->program());

  glActiveTexture(GL_TEXTURE0);
  glUniform1i(compositor_->u_tex_loc(), 0);
  glBindTexture(GL_TEXTURE_2D, texture_id_);

  GLfloat m[16];
  const SkMatrix& matrix = t.matrix();

  // Convert 3x3 view transform matrix (row major) into 4x4 GL matrix (column
  // major). Assume 2-D rotations/translations restricted to XY plane.

  m[ 0] = matrix[0];
  m[ 1] = matrix[3];
  m[ 2] = 0;
  m[ 3] = matrix[6];

  m[ 4] = matrix[1];
  m[ 5] = matrix[4];
  m[ 6] = 0;
  m[ 7] = matrix[7];

  m[ 8] = 0;
  m[ 9] = 0;
  m[10] = 1;
  m[11] = 0;

  m[12] = matrix[2];
  m[13] = matrix[5];
  m[14] = 0;
  m[15] = matrix[8];

  const GLfloat vertices[] = { -1., -1., +0., +0., +1.,
                               +1., -1., +0., +1., +1.,
                               +1., +1., +0., +1., +0.,
                               -1., +1., +0., +0., +0. };

  glVertexAttribPointer(compositor_->a_pos_loc(), 3, GL_FLOAT,
                        GL_FALSE, 5 * sizeof(GLfloat), vertices);
  glVertexAttribPointer(compositor_->a_tex_loc(), 2, GL_FLOAT,
                        GL_FALSE, 5 * sizeof(GLfloat), &vertices[3]);
  glEnableVertexAttribArray(compositor_->a_pos_loc());
  glEnableVertexAttribArray(compositor_->a_tex_loc());

  glUniformMatrix4fv(compositor_->u_mat_loc(), 1, GL_FALSE, m);

  glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}

CompositorGL::CompositorGL(gfx::AcceleratedWidget widget)
    : started_(false) {
  gl_surface_ = gfx::GLSurface::CreateViewGLSurface(widget);
  gl_context_ = gfx::GLContext::CreateGLContext(NULL, gl_surface_.get());
  gl_context_->MakeCurrent(gl_surface_.get());
  if (!InitShaders())
    LOG(ERROR) << "Unable to initialize shaders (context = "
               << static_cast<void*>(gl_context_.get()) << ")" ;
  glColorMask(true, true, true, true);
  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

CompositorGL::~CompositorGL() {
}

void CompositorGL::MakeCurrent() {
  gl_context_->MakeCurrent(gl_surface_.get());
}

gfx::Size CompositorGL::GetSize() {
  return gl_surface_->GetSize();
}

GLuint CompositorGL::program() {
  return program_;
}

GLuint CompositorGL::a_pos_loc() {
  return a_pos_loc_;
}

GLuint CompositorGL::a_tex_loc() {
  return a_tex_loc_;
}

GLuint CompositorGL::u_tex_loc() {
  return u_tex_loc_;
}

GLuint CompositorGL::u_mat_loc() {
  return u_mat_loc_;
}

Texture* CompositorGL::CreateTexture() {
  Texture* texture = new TextureGL(this);
  return texture;
}

void CompositorGL::NotifyStart() {
  started_ = true;
  gl_context_->MakeCurrent(gl_surface_.get());
  glViewport(0, 0,
             gl_surface_->GetSize().width(), gl_surface_->GetSize().height());

  // Clear to 'psychedelic' purple to make it easy to spot un-rendered regions.
  glClearColor(223.0 / 255, 0, 1, 1);
  glColorMask(true, true, true, true);
  glClear(GL_COLOR_BUFFER_BIT);
  // Disable alpha writes, since we're using blending anyways.
  glColorMask(true, true, true, false);
}

void CompositorGL::NotifyEnd() {
  DCHECK(started_);
  gl_surface_->SwapBuffers();
  started_ = false;
}

namespace {

GLuint CompileShader(GLenum type, const GLchar* source) {
  GLuint shader = glCreateShader(type);
  if (!shader)
    return 0;

  glShaderSource(shader, 1, &source, 0);
  glCompileShader(shader);

  GLint compiled;
  glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
  if (!compiled) {
    GLint info_len = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &info_len);

    if (info_len > 0) {
      char* info_log = reinterpret_cast<char*> (
          malloc(sizeof(info_log[0]) * info_len));
      glGetShaderInfoLog(shader, info_len, NULL, info_log);

      LOG(ERROR) << "Compile error: " <<  info_log;
      free(info_log);
      return 0;
    }
  }
  return shader;
}

} // namespace (anonymous)

bool CompositorGL::InitShaders() {
  const GLchar* vertex_shader_source =
        "attribute vec4 a_position;"
        "attribute vec2 a_texCoord;"
        "uniform mat4 u_matViewProjection;"
        "varying vec2 v_texCoord;"
        "void main()"
        "{"
        "  gl_Position = u_matViewProjection * a_position;"
        "  v_texCoord = a_texCoord;"
        "}";
  GLuint vertex_shader = CompileShader(GL_VERTEX_SHADER, vertex_shader_source);
  if (!vertex_shader)
    return false;

  const GLchar* frag_shader_source =
        "#ifdef GL_ES\n"
        "precision mediump float;\n"
        "#endif\n"
        "uniform sampler2D u_tex;"
        "varying vec2 v_texCoord;"
        "void main()"
        "{"
        "  gl_FragColor = texture2D(u_tex, v_texCoord).zyxw;"
        "}";
  GLuint frag_shader = CompileShader(GL_FRAGMENT_SHADER, frag_shader_source);
  if (!frag_shader)
    return false;

  program_ = glCreateProgram();
  glAttachShader(program_, vertex_shader);
  glAttachShader(program_, frag_shader);
  glLinkProgram(program_);
  if (glGetError() != GL_NO_ERROR)
    return false;

  // Store locations of program inputs.
  a_pos_loc_ = glGetAttribLocation(program_, "a_position");
  a_tex_loc_ = glGetAttribLocation(program_, "a_texCoord");
  u_tex_loc_ = glGetUniformLocation(program_, "u_tex");
  u_mat_loc_ = glGetUniformLocation(program_, "u_matViewProjection");

  return true;
}

} // namespace

// static
Compositor* Compositor::Create(gfx::AcceleratedWidget widget) {
 gfx::GLSurface::InitializeOneOff();
 if (gfx::GetGLImplementation() != gfx::kGLImplementationNone)
   return new glHidden::CompositorGL(widget);
  return NULL;
}
#else
class CompositorGL : public Compositor {
 public:
  explicit CompositorGL(gfx::AcceleratedWidget widget);

 private:
  // Overridden from Compositor.
  void NotifyStart() OVERRIDE;
  void NotifyEnd() OVERRIDE;
  void DrawTextureWithTransform(TextureID txt,
                                const ui::Transform& transform) OVERRIDE;
  void SaveTransform() OVERRIDE;
  void RestoreTransform() OVERRIDE;

  // The GL context used for compositing.
  scoped_refptr<gfx::GLSurface> gl_surface_;
  scoped_refptr<gfx::GLContext> gl_context_;

  // Keep track of whether compositing has started or not.
  bool started_;

  DISALLOW_COPY_AND_ASSIGN(CompositorGL);
};

CompositorGL::CompositorGL(gfx::AcceleratedWidget widget)
    : started_(false) {
  gl_surface_ = gfx::GLSurface::CreateViewGLSurface(widget);
  gl_context_ = gfx::GLContext::CreateGLContext(NULL, gl_surface_.get());
}

void CompositorGL::NotifyStart() {
  started_ = true;
  gl_context_->MakeCurrent(gl_surface_.get());
}

void CompositorGL::NotifyEnd() {
  DCHECK(started_);
  gl_surface_->SwapBuffers();
  started_ = false;
}

void CompositorGL::DrawTextureWithTransform(TextureID txt,
                                            const ui::Transform& transform) {
  DCHECK(started_);

  // TODO(wjmaclean):
  NOTIMPLEMENTED();
}

void CompositorGL::SaveTransform() {
  // TODO(sadrul):
  NOTIMPLEMENTED();
}

void CompositorGL::RestoreTransform() {
  // TODO(sadrul):
  NOTIMPLEMENTED();
}

// static
Compositor* Compositor::Create(gfx::AcceleratedWidget widget) {
  if (gfx::GetGLImplementation() != gfx::kGLImplementationNone)
    return new CompositorGL(widget);
  return NULL;
}
#endif

}  // namespace ui