summaryrefslogtreecommitdiffstats
path: root/app/gfx/gl/gl_context_win.cc
blob: 8bbb6268a2957bb25ba1e8a63a2baf790daa3dc7 (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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
// Copyright (c) 2010 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.

// This file implements the NativeViewGLContext and PbufferGLContext classes.

#include <GL/glew.h>
#include <GL/osmew.h>
#include <GL/wglew.h>
#include <windows.h>

#include <algorithm>

#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "app/gfx/gl/gl_context.h"
#include "app/gfx/gl/gl_context_osmesa.h"

namespace gfx {

typedef HGLRC GLContextHandle;
typedef HPBUFFERARB PbufferHandle;

const wchar_t kNativeViewGLClass[] = L"NativeViewGLWindow";

// This class is a wrapper around a GL context that renders directly to a
// window.
class NativeViewGLContext : public GLContext {
 public:
  explicit NativeViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        content_window_(NULL),
        device_context_(NULL),
        context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize(bool multisampled);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  HWND CreateContentWindow(HWND parent);

  gfx::PluginWindowHandle window_;
  HWND content_window_;
  HDC device_context_;
  GLContextHandle context_;

  DISALLOW_COPY_AND_ASSIGN(NativeViewGLContext);
};

// This class is a wrapper around a GL context that uses OSMesa to render
// to an offscreen buffer and then blits it to a window.
class OSMesaViewGLContext : public GLContext {
 public:
  explicit OSMesaViewGLContext(gfx::PluginWindowHandle window)
      : window_(window),
        device_context_(NULL) {
    DCHECK(window);
  }

  // Initializes the GL context.
  bool Initialize();

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  void UpdateSize();

  gfx::PluginWindowHandle window_;
  HDC device_context_;
  OSMesaGLContext osmesa_context_;

  DISALLOW_COPY_AND_ASSIGN(OSMesaViewGLContext);
};

// This class is a wrapper around a GL context used for offscreen rendering.
// It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful
// rendering.
class PbufferGLContext : public GLContext {
 public:
  PbufferGLContext()
      : context_(NULL),
        device_context_(NULL),
        pbuffer_(NULL) {
  }

  // Initializes the GL context.
  bool Initialize(void* shared_handle);

  virtual void Destroy();
  virtual bool MakeCurrent();
  virtual bool IsCurrent();
  virtual bool IsOffscreen();
  virtual void SwapBuffers();
  virtual gfx::Size GetSize();
  virtual void* GetHandle();

 private:
  GLContextHandle context_;
  HDC device_context_;
  PbufferHandle pbuffer_;

  DISALLOW_COPY_AND_ASSIGN(PbufferGLContext);
};

static int g_regular_pixel_format = 0;
static int g_multisampled_pixel_format = 0;

const PIXELFORMATDESCRIPTOR kPixelFormatDescriptor = {
  sizeof(kPixelFormatDescriptor),    // Size of structure.
  1,                       // Default version.
  PFD_DRAW_TO_WINDOW |     // Window drawing support.
  PFD_SUPPORT_OPENGL |     // OpenGL support.
  PFD_DOUBLEBUFFER,        // Double buffering support (not stereo).
  PFD_TYPE_RGBA,           // RGBA color mode (not indexed).
  24,                      // 24 bit color mode.
  0, 0, 0, 0, 0, 0,        // Don't set RGB bits & shifts.
  8, 0,                    // 8 bit alpha
  0,                       // No accumulation buffer.
  0, 0, 0, 0,              // Ignore accumulation bits.
  24,                      // 24 bit z-buffer size.
  8,                       // 8-bit stencil buffer.
  0,                       // No aux buffer.
  PFD_MAIN_PLANE,          // Main drawing plane (not overlay).
  0,                       // Reserved.
  0, 0, 0,                 // Layer masks ignored.
};

LRESULT CALLBACK IntermediateWindowProc(HWND window,
                                        UINT message,
                                        WPARAM w_param,
                                        LPARAM l_param) {
  return ::DefWindowProc(window, message, w_param, l_param);
}

// Helper routine that does one-off initialization like determining the
// pixel format and initializing glew.
static bool InitializeOneOff() {
  static bool initialized = false;
  if (initialized)
    return true;

  osmewInit();
  if (!OSMesaCreateContext) {
    // We must initialize a GL context before we can determine the multi-
    // sampling supported on the current hardware, so we create an intermediate
    // window and context here.
    HINSTANCE module_handle;
    if (!::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
                             GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                             reinterpret_cast<wchar_t*>(IntermediateWindowProc),
                             &module_handle)) {
      return false;
    }

    WNDCLASS intermediate_class;
    intermediate_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    intermediate_class.lpfnWndProc = IntermediateWindowProc;
    intermediate_class.cbClsExtra = 0;
    intermediate_class.cbWndExtra = 0;
    intermediate_class.hInstance = module_handle;
    intermediate_class.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    intermediate_class.hCursor = LoadCursor(NULL, IDC_ARROW);
    intermediate_class.hbrBackground = NULL;
    intermediate_class.lpszMenuName = NULL;
    intermediate_class.lpszClassName = L"Intermediate GL Window";

    ATOM class_registration = ::RegisterClass(&intermediate_class);
    if (!class_registration) {
      return false;
    }

    HWND intermediate_window = ::CreateWindow(
        reinterpret_cast<wchar_t*>(class_registration),
        L"",
        WS_OVERLAPPEDWINDOW,
        0, 0,
        CW_USEDEFAULT, CW_USEDEFAULT,
        NULL,
        NULL,
        NULL,
        NULL);

    if (!intermediate_window) {
      ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
                        module_handle);
      return false;
    }

    HDC intermediate_dc = ::GetDC(intermediate_window);
    g_regular_pixel_format = ::ChoosePixelFormat(intermediate_dc,
                                                 &kPixelFormatDescriptor);
    if (g_regular_pixel_format == 0) {
      DLOG(ERROR) << "Unable to get the pixel format for GL context.";
      ::ReleaseDC(intermediate_window, intermediate_dc);
      ::DestroyWindow(intermediate_window);
      ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
                        module_handle);
      return false;
    }
    if (!::SetPixelFormat(intermediate_dc, g_regular_pixel_format,
                          &kPixelFormatDescriptor)) {
      DLOG(ERROR) << "Unable to set the pixel format for GL context.";
      ::ReleaseDC(intermediate_window, intermediate_dc);
      ::DestroyWindow(intermediate_window);
      ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
                        module_handle);
      return false;
    }

    // Create a temporary GL context to query for multisampled pixel formats.
    HGLRC gl_context = ::wglCreateContext(intermediate_dc);
    if (::wglMakeCurrent(intermediate_dc, gl_context)) {
      // GL context was successfully created and applied to the window's DC.
      // Startup GLEW, the GL extensions wrangler.
      if (InitializeGLEW()) {
        DLOG(INFO) << "Initialized GLEW " << glewGetString(GLEW_VERSION);
      } else {
        ::wglMakeCurrent(intermediate_dc, NULL);
        ::wglDeleteContext(gl_context);
        ::ReleaseDC(intermediate_window, intermediate_dc);
        ::DestroyWindow(intermediate_window);
        ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
                          module_handle);
        return false;
      }

      // If the multi-sample extensions are present, query the api to determine
      // the pixel format.
      if (WGLEW_ARB_pixel_format && WGLEW_ARB_multisample) {
        int pixel_attributes[] = {
          WGL_SAMPLES_ARB, 4,
          WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
          WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
          WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
          WGL_COLOR_BITS_ARB, 24,
          WGL_ALPHA_BITS_ARB, 8,
          WGL_DEPTH_BITS_ARB, 24,
          WGL_STENCIL_BITS_ARB, 8,
          WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
          WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
          0, 0};

        float pixel_attributes_f[] = {0, 0};
        unsigned int num_formats;

        // Query for the highest sampling rate supported, starting at 4x.
        static const int kSampleCount[] = {4, 2};
        static const int kNumSamples = 2;
        for (int sample = 0; sample < kNumSamples; ++sample) {
          pixel_attributes[1] = kSampleCount[sample];
          if (GL_TRUE == ::wglChoosePixelFormatARB(intermediate_dc,
                                                   pixel_attributes,
                                                   pixel_attributes_f,
                                                   1,
                                                   &g_multisampled_pixel_format,
                                                   &num_formats)) {
            break;
          }
        }
      }
    }

    ::wglMakeCurrent(intermediate_dc, NULL);
    ::wglDeleteContext(gl_context);
    ::ReleaseDC(intermediate_window, intermediate_dc);
    ::DestroyWindow(intermediate_window);
    ::UnregisterClass(reinterpret_cast<wchar_t*>(class_registration),
                      module_handle);
  }

  initialized = true;

  return true;
}

HWND NativeViewGLContext::CreateContentWindow(HWND parent) {
  WNDCLASS window_class = {0};
  if (!GetClassInfo(GetModuleHandle(0), kNativeViewGLClass, &window_class)) {
    window_class.style = CS_OWNDC;
    window_class.hInstance = GetModuleHandle(0);
    window_class.lpfnWndProc = DefWindowProc;
    window_class.lpszClassName = kNativeViewGLClass;
    if (!RegisterClass(&window_class)) {
        DLOG(ERROR) << "Failed to register window class";
        return 0;
    }
  }

  // The content window's size matches the size of the hosting window at
  // creation time. If the size of the hosting window changes, SwapBuffers
  // must be called to resize the content window appropriately.
  RECT rect;
  GetClientRect(window_, &rect);
  HWND content_window = CreateWindow(kNativeViewGLClass, L"NativeViewGLcontent",
      WS_CHILD | WS_VISIBLE | WS_DISABLED,
      0, 0, rect.right - rect.left, rect.bottom - rect.top, parent, 0,
      GetModuleHandle(0), 0);

  if (!content_window)
    UnregisterClass(kNativeViewGLClass, GetModuleHandle(0));

  return content_window;
}

bool NativeViewGLContext::Initialize(bool multisampled) {
  // Create a new window to be used by the GL context. The content window is a
  // child of hosting window and renders on top of it. Currently the content
  // window gets resized when SwapBuffers() gets called to match the size of
  // the host.
  content_window_ = CreateContentWindow(window_);
  if (!content_window_)
      return false;

  // The GL context will render to this window.
  device_context_ = GetDC(content_window_);

  int pixel_format =
      multisampled ? g_multisampled_pixel_format : g_regular_pixel_format;
  if (!SetPixelFormat(device_context_,
                      pixel_format,
                      &kPixelFormatDescriptor)) {
    DLOG(ERROR) << "Unable to set the pixel format for GL context.";
    Destroy();
    return false;
  }

  context_ = wglCreateContext(device_context_);
  if (!context_) {
    DLOG(ERROR) << "Failed to create GL context.";
    Destroy();
    return false;
  }

  if (!MakeCurrent()) {
    Destroy();
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void NativeViewGLContext::Destroy() {
  if (context_) {
    wglDeleteContext(context_);
    context_ = NULL;
  }

  if (content_window_ && device_context_) {
    ReleaseDC(content_window_, device_context_);
    ::DestroyWindow(content_window_);
    UnregisterClass(kNativeViewGLClass, GetModuleHandle(0));
  }
  content_window_ = NULL;
  device_context_ = NULL;
}

bool NativeViewGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  if (!wglMakeCurrent(device_context_, context_)) {
    DLOG(ERROR) << "Unable to make gl context current.";
    return false;
  }

  return true;
}

bool NativeViewGLContext::IsCurrent() {
  return wglGetCurrentDC() == device_context_ &&
      wglGetCurrentContext() == context_;
}

bool NativeViewGLContext::IsOffscreen() {
  return false;
}

void NativeViewGLContext::SwapBuffers() {
  DCHECK(device_context_);

  ::SwapBuffers(device_context_);

  // Adjust the size of the content window to always match that of the hosting
  // window.
  RECT host_window_rect;
  GetClientRect(window_, &host_window_rect);
  RECT content_window_rect;
  GetClientRect(content_window_, &content_window_rect);
  if (!EqualRect(&host_window_rect, &content_window_rect)){
    SetWindowPos(content_window_, NULL, 0, 0,
                 host_window_rect.right - host_window_rect.left,
                 host_window_rect.bottom - host_window_rect.top, 0);
  }
}

gfx::Size NativeViewGLContext::GetSize() {
  RECT rect;
  CHECK(GetClientRect(window_, &rect));
  return gfx::Size(rect.right - rect.left, rect.bottom - rect.top);
}

void* NativeViewGLContext::GetHandle() {
  return context_;
}

bool OSMesaViewGLContext::Initialize() {
  // The GL context will render to this window.
  device_context_ = GetDC(window_);

  if (!osmesa_context_.Initialize(NULL)) {
    Destroy();
    return false;
  }

  UpdateSize();

  return true;
}

void OSMesaViewGLContext::Destroy() {
  osmesa_context_.Destroy();

  if (window_ && device_context_)
    ReleaseDC(window_, device_context_);

  window_ = NULL;
  device_context_ = NULL;
}

bool OSMesaViewGLContext::MakeCurrent() {
  // TODO(apatrick): This is a bit of a hack. The window might have had zero
  // size when the context was initialized. Assume it has a valid size when
  // MakeCurrent is called and resize the back buffer if necessary.
  UpdateSize();
  return osmesa_context_.MakeCurrent();
}

bool OSMesaViewGLContext::IsCurrent() {
  return osmesa_context_.IsCurrent();
}

bool OSMesaViewGLContext::IsOffscreen() {
  return false;
}

void OSMesaViewGLContext::SwapBuffers() {
  DCHECK(device_context_);

  // Update the size before blitting so that the blit size is exactly the same
  // as the window.
  UpdateSize();

  gfx::Size size = osmesa_context_.GetSize();

  BITMAPV4HEADER info = { sizeof(BITMAPV4HEADER) };
  info.bV4Width = size.width();
  info.bV4Height = size.height();
  info.bV4Planes = 1;
  info.bV4BitCount = 32;
  info.bV4V4Compression = BI_BITFIELDS;
  info.bV4RedMask = 0xFF000000;
  info.bV4GreenMask = 0x00FF0000;
  info.bV4BlueMask = 0x0000FF00;
  info.bV4AlphaMask = 0x000000FF;

  // Copy the back buffer to the window's device context.
  StretchDIBits(device_context_,
                0, 0, size.width(), size.height(),
                0, 0, size.width(), size.height(),
                osmesa_context_.buffer(),
                reinterpret_cast<BITMAPINFO*>(&info),
                DIB_RGB_COLORS,
                SRCCOPY);
}

gfx::Size OSMesaViewGLContext::GetSize() {
  return osmesa_context_.GetSize();
}

void* OSMesaViewGLContext::GetHandle() {
  return osmesa_context_.GetHandle();
}

void OSMesaViewGLContext::UpdateSize() {
  // Change back buffer size to that of window.
  RECT rect;
  GetWindowRect(window_, &rect);
  gfx::Size window_size = gfx::Size(
    std::max(1, static_cast<int>(rect.right - rect.left)),
    std::max(1, static_cast<int>(rect.bottom - rect.top)));
  osmesa_context_.Resize(window_size);
}

GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window,
                                          bool multisampled) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaViewGLContext> context(new OSMesaViewGLContext(window));

    if (!context->Initialize())
      return NULL;

    return context.release();
  } else {
    scoped_ptr<NativeViewGLContext> context(new NativeViewGLContext(window));

    if (!context->Initialize(multisampled))
      return NULL;

    return context.release();
  }
}

bool PbufferGLContext::Initialize(void* shared_handle) {
  // Create a device context compatible with the primary display.
  HDC display_device_context = ::CreateDC(L"DISPLAY", NULL, NULL, NULL);

  // Create a 1 x 1 pbuffer suitable for use with the device. This is just
  // a stepping stone towards creating a frame buffer object. It doesn't
  // matter what size it is.
  const int kNoAttributes[] = { 0 };
  pbuffer_ = ::wglCreatePbufferARB(display_device_context,
                                   g_regular_pixel_format,
                                   1, 1,
                                   kNoAttributes);
  ::DeleteDC(display_device_context);
  if (!pbuffer_) {
    DLOG(ERROR) << "Unable to create pbuffer.";
    Destroy();
    return false;
  }

  device_context_ = ::wglGetPbufferDCARB(pbuffer_);
  if (!device_context_) {
    DLOG(ERROR) << "Unable to get pbuffer device context.";
    Destroy();
    return false;
  }

  context_ = ::wglCreateContext(device_context_);
  if (!context_) {
    DLOG(ERROR) << "Failed to create GL context.";
    Destroy();
    return false;
  }

  if (shared_handle) {
    if (!wglShareLists(static_cast<GLContextHandle>(shared_handle), context_)) {
      DLOG(ERROR) << "Could not share GL contexts.";
      Destroy();
      return false;
    }
  }

  if (!MakeCurrent()) {
    Destroy();
    return false;
  }

  if (!InitializeGLEW()) {
    Destroy();
    return false;
  }

  if (!InitializeCommon()) {
    Destroy();
    return false;
  }

  return true;
}

void PbufferGLContext::Destroy() {
  if (context_) {
    wglDeleteContext(context_);
    context_ = NULL;
  }

  if (pbuffer_ && device_context_)
    wglReleasePbufferDCARB(pbuffer_, device_context_);

  device_context_ = NULL;

  if (pbuffer_) {
    wglDestroyPbufferARB(pbuffer_);
    pbuffer_ = NULL;
  }
}

bool PbufferGLContext::MakeCurrent() {
  if (IsCurrent()) {
    return true;
  }
  if (!wglMakeCurrent(device_context_, context_)) {
    DLOG(ERROR) << "Unable to make gl context current.";
    return false;
  }

  return true;
}

bool PbufferGLContext::IsCurrent() {
  return wglGetCurrentDC() == device_context_ &&
      wglGetCurrentContext() == context_;
}

bool PbufferGLContext::IsOffscreen() {
  return true;
}

void PbufferGLContext::SwapBuffers() {
  NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer.";
}

gfx::Size PbufferGLContext::GetSize() {
  NOTREACHED() << "Should not be requesting size of this pbuffer.";
  return gfx::Size(1, 1);
}

void* PbufferGLContext::GetHandle() {
  return context_;
}

GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) {
  if (!InitializeOneOff())
    return NULL;

  if (OSMesaCreateContext) {
    scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext);

    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  } else {
    scoped_ptr<PbufferGLContext> context(new PbufferGLContext);
    if (!context->Initialize(shared_handle))
      return NULL;

    return context.release();
  }
}

}  // namespace gfx