aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/games/jogl/impl/windows/WindowsGLContext.java
blob: e938c802321ff104424075e5e07a406d25a0461d (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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
/*
 * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 * 
 * Sun gratefully acknowledges that this software was originally authored
 * and developed by Kenneth Bradley Russell and Christopher John Kline.
 */

package net.java.games.jogl.impl.windows;

import java.awt.Component;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.Rectangle;
import java.util.*;
import net.java.games.gluegen.runtime.*; // for PROCADDRESS_VAR_PREFIX
import net.java.games.jogl.*;
import net.java.games.jogl.impl.*;

public abstract class WindowsGLContext extends GLContext {
  private static JAWT jawt;
  protected long hglrc;
  protected long hdc;
  private boolean wglGetExtensionsStringEXTInitialized;
  private boolean wglGetExtensionsStringEXTAvailable;
  private static final Map/*<String, String>*/ functionNameMap;
  private static final Map/*<String, String>*/ extensionNameMap;
  // Table that holds the addresses of the native C-language entry points for
  // OpenGL functions.
  private GLProcAddressTable glProcAddressTable;
  // Handle to GLU32.dll
  private long hglu32;
  private boolean haveWGLARBPbuffer = true;

  private static final int MAX_PFORMATS = 256;
  private static final int MAX_ATTRIBS  = 256;

  static {
    functionNameMap = new HashMap();
    functionNameMap.put("glAllocateMemoryNV", "wglAllocateMemoryNV");
    functionNameMap.put("glFreeMemoryNV", "wglFreeMemoryNV");

    extensionNameMap = new HashMap();
    extensionNameMap.put("GL_ARB_pbuffer", "WGL_ARB_pbuffer");
    extensionNameMap.put("GL_ARB_pixel_format", "WGL_ARB_pixel_format");
  }

  public WindowsGLContext(Component component,
                          GLCapabilities capabilities,
                          GLCapabilitiesChooser chooser,
                          GLContext shareWith) {
    super(component, capabilities, chooser, shareWith);
  }
  
  protected GL createGL()
  {
    return new WindowsGLImpl(this);
  }
  
  protected String mapToRealGLFunctionName(String glFunctionName) {
    String lookup = (String) functionNameMap.get(glFunctionName);
    if (lookup != null) {
      return lookup;
    }
    return glFunctionName;
  }

  protected String mapToRealGLExtensionName(String glExtensionName) {
    String lookup = (String) extensionNameMap.get(glExtensionName);
    if (lookup != null) {
      return lookup;
    }
    return glExtensionName;
  }

  protected abstract boolean isOffscreen();
  
  public int getOffscreenContextWidth() {
    throw new GLException("Should not call this");
  }
  
  public int getOffscreenContextHeight() {
    throw new GLException("Should not call this");
  }
  
  public int getOffscreenContextPixelDataType() {
    throw new GLException("Should not call this");
  }

  public abstract int getOffscreenContextReadBuffer();

  public abstract boolean offscreenImageNeedsVerticalFlip();

  /**
   * Creates and initializes an appropriate OpenGL context. Should only be
   * called by {@link #makeCurrent(Runnable)}.
   */
  protected abstract void create();
  
  protected synchronized boolean makeCurrent(Runnable initAction) throws GLException {
    boolean created = false;
    if (hglrc == 0) {
      create();
      if (DEBUG) {
        System.err.println(getThreadName() + ": !!! Created GL context for " + getClass().getName());
      }
      created = true;
    }

    boolean skipMakeCurrent = false;
    if (NO_FREE) {
      if (WGL.wglGetCurrentContext() == hglrc) {
        if (DEBUG && VERBOSE) {
          System.err.println(getThreadName() + ": skipping wglMakeCurrent because context already current");
        }
        skipMakeCurrent = true;
      }
    }

    if (!skipMakeCurrent) {
      if (!WGL.wglMakeCurrent(hdc, hglrc)) {
        throw new GLException("Error making context current: " + WGL.GetLastError());
      } else {
        if (DEBUG && VERBOSE) {
          System.err.println(getThreadName() + ": wglMakeCurrent(hdc " + hdcToString(hdc) +
                             ", hglrc " + hdcToString(hglrc) + ") succeeded");
        }
      }
    }

    if (created) {
      resetGLFunctionAvailability();
      haveWGLARBPbuffer = (isExtensionAvailable("WGL_ARB_pbuffer") &&
                           isExtensionAvailable("WGL_ARB_pixel_format"));
      // Windows can set up sharing of display lists after creation time
      WindowsGLContext other = (WindowsGLContext) GLContextShareSet.getShareContext(this);
      if (other != null) {
        long hglrc2 = other.getHGLRC();
        if (hglrc2 == 0) {
          throw new GLException("GLContextShareSet returned an invalid OpenGL context");
        }
        if (!WGL.wglShareLists(hglrc2, hglrc)) {
          throw new GLException("wglShareLists(0x" + Long.toHexString(hglrc2) +
                                ", 0x" + Long.toHexString(hglrc) + ") failed: error code " +
                                WGL.GetLastError());
        }
      }
      GLContextShareSet.contextCreated(this);      

      initAction.run();
    }
    return true;
  }

  protected synchronized void free() throws GLException {
    if (!NO_FREE) {
      if (!WGL.wglMakeCurrent(0, 0)) {
        throw new GLException("Error freeing OpenGL context: " + WGL.GetLastError());
      }
    }
  }

  protected void destroyImpl() throws GLException {
    if (hglrc != 0) {
      if (!WGL.wglDeleteContext(hglrc)) {
        throw new GLException("Unable to delete OpenGL context");
      }
      if (DEBUG) {
        System.err.println(getThreadName() + ": !!! Destroyed OpenGL context " + hglrc);
      }
      hglrc = 0;
    }
  }

  public abstract void swapBuffers() throws GLException;

  protected long dynamicLookupFunction(String glFuncName) {
    long res = WGL.wglGetProcAddress(glFuncName);
    if (res == 0) {
      // GLU routines aren't known to the OpenGL function lookup
      if (hglu32 == 0) {
        hglu32 = WGL.LoadLibraryA("GLU32");
        if (hglu32 == 0) {
          throw new GLException("Error loading GLU32.DLL");
        }
      }
      res = WGL.GetProcAddress(hglu32, glFuncName);
    }
    return res;
  }

  public boolean isCreated() {
    return (hglrc != 0);
  }

  protected void resetGLFunctionAvailability() {
    super.resetGLFunctionAvailability();
    if (DEBUG) {
      System.err.println(getThreadName() + ": !!! Initializing OpenGL extension address table");
    }
    resetProcAddressTable(getGLProcAddressTable());
  }
  
  public GLProcAddressTable getGLProcAddressTable() {
    if (glProcAddressTable == null) {
      // FIXME: cache ProcAddressTables by capability bits so we can
      // share them among contexts with the same capabilities
      glProcAddressTable = new GLProcAddressTable();
    }          
    return glProcAddressTable;
  }
  
  public String getPlatformExtensionsString() {
    if (!wglGetExtensionsStringEXTInitialized) {
      wglGetExtensionsStringEXTAvailable = (WGL.wglGetProcAddress("wglGetExtensionsStringEXT") != 0);
      wglGetExtensionsStringEXTInitialized = true;
    }
    if (wglGetExtensionsStringEXTAvailable) {
      return gl.wglGetExtensionsStringEXT();
    } else {
      return "";
    }
  }

  protected boolean isFunctionAvailable(String glFunctionName)
  {
    boolean available = super.isFunctionAvailable(glFunctionName);
    
    // Sanity check for implementations that use proc addresses for run-time
    // linking: if the function IS available, then make sure there's a proc
    // address for it if it's an extension or not part of the OpenGL 1.1 core
    // (post GL 1.1 functions are run-time linked on windows).
    assert(!available ||
           (getGLProcAddressTable().getAddressFor(mapToRealGLFunctionName(glFunctionName)) != 0 ||
            FunctionAvailabilityCache.isPartOfGLCore("1.1", mapToRealGLFunctionName(glFunctionName)))
           );

    return available;
  }
  
  //----------------------------------------------------------------------
  // Internals only below this point
  //

  protected JAWT getJAWT() {
    if (jawt == null) {
      JAWT j = new JAWT();
      j.version(JAWTFactory.JAWT_VERSION_1_4);
      if (!JAWTFactory.JAWT_GetAWT(j)) {
        throw new RuntimeException("Unable to initialize JAWT");
      }
      jawt = j;
    }
    return jawt;
  }
  
  // Helper routine for the overridden create() to call
  protected void choosePixelFormatAndCreateContext(boolean onscreen) {
    PIXELFORMATDESCRIPTOR pfd = null;
    int pixelFormat = 0;
    if (onscreen) {
      GLCapabilities[] availableCaps = null;
      int numFormats = 0;
      pfd = newPixelFormatDescriptor();
      GraphicsConfiguration config = component.getGraphicsConfiguration();
      GraphicsDevice device = config.getDevice();
      // Produce a recommended pixel format selection for the GLCapabilitiesChooser.
      // Use wglChoosePixelFormatARB if user requested multisampling and if we have it available
      GL dummyGL = null;
      if (capabilities.getSampleBuffers()) {
        dummyGL = WindowsGLContextFactory.getDummyGL(device);
      }
      int recommendedPixelFormat = -1;
      boolean haveWGLChoosePixelFormatARB = false;
      boolean haveWGLARBMultisample = false;
      if (dummyGL != null) {
        String availableWGLExtensions = WindowsGLContextFactory.getDummyGLExtensions(device);
        if (availableWGLExtensions.indexOf("WGL_ARB_pixel_format") >= 0) {
          haveWGLChoosePixelFormatARB = true;
          if (availableWGLExtensions.indexOf("WGL_ARB_multisample") >= 0) {
            haveWGLARBMultisample = true;
          }
        }
      }
      Rectangle rect = config.getBounds();
      long dc = 0;
      long rc = 0;
      boolean freeWGLC = false;
      if( dummyGL != null ) {
        dc = WindowsGLContextFactory.getDummyGLContext( device ).hdc;
        rc = WindowsGLContextFactory.getDummyGLContext( device ).hglrc;
        if( !WGL.wglMakeCurrent( dc, rc ) ) {
          System.err.println(getThreadName() + ": Error Making WGLC Current: " + WGL.GetLastError() );
        } else {
          freeWGLC = true;
        }
      }
      // Fallback path for older cards, in particular Intel Extreme motherboard graphics
      boolean gotAvailableCaps = false;
      if (dummyGL != null && haveWGLChoosePixelFormatARB) {
        int[]   iattributes = new int  [2 * MAX_ATTRIBS];
        int[]   iresults    = new int  [2 * MAX_ATTRIBS];
        float[] fattributes = new float[2 * MAX_ATTRIBS];
        int niattribs = 0;
        int nfattribs = 0;
        iattributes[niattribs++] = GL.WGL_SUPPORT_OPENGL_ARB;
        iattributes[niattribs++] = GL.GL_TRUE;
        iattributes[niattribs++] = GL.WGL_DRAW_TO_WINDOW_ARB;
        iattributes[niattribs++] = GL.GL_TRUE;
        iattributes[niattribs++] = GL.WGL_PIXEL_TYPE_ARB;
        iattributes[niattribs++] = GL.WGL_TYPE_RGBA_ARB;
        iattributes[niattribs++] = GL.WGL_DOUBLE_BUFFER_ARB;
        if (capabilities.getDoubleBuffered()) {
          iattributes[niattribs++] = GL.GL_TRUE;
        } else {
          iattributes[niattribs++] = GL.GL_FALSE;
        }
        iattributes[niattribs++] = GL.WGL_STEREO_ARB;
        if (capabilities.getStereo()) {
          iattributes[niattribs++] = GL.GL_TRUE;
        } else {
          iattributes[niattribs++] = GL.GL_FALSE;
        }
        iattributes[niattribs++] = GL.WGL_DEPTH_BITS_ARB;
        iattributes[niattribs++] = capabilities.getDepthBits();
        iattributes[niattribs++] = GL.WGL_RED_BITS_ARB;
        iattributes[niattribs++] = capabilities.getRedBits();
        iattributes[niattribs++] = GL.WGL_GREEN_BITS_ARB;
        iattributes[niattribs++] = capabilities.getGreenBits();
        iattributes[niattribs++] = GL.WGL_BLUE_BITS_ARB;
        iattributes[niattribs++] = capabilities.getBlueBits();
        iattributes[niattribs++] = GL.WGL_ALPHA_BITS_ARB;
        iattributes[niattribs++] = capabilities.getAlphaBits();
        iattributes[niattribs++] = GL.WGL_STENCIL_BITS_ARB;
        iattributes[niattribs++] = capabilities.getStencilBits();
        if (capabilities.getAccumRedBits()   > 0 ||
            capabilities.getAccumGreenBits() > 0 ||
            capabilities.getAccumBlueBits()  > 0 ||
            capabilities.getAccumAlphaBits()  > 0) {
          iattributes[niattribs++] = GL.WGL_ACCUM_BITS_ARB;
          iattributes[niattribs++] = (capabilities.getAccumRedBits() +
                                      capabilities.getAccumGreenBits() +
                                      capabilities.getAccumBlueBits() +
                                      capabilities.getAccumAlphaBits());
          iattributes[niattribs++] = GL.WGL_ACCUM_RED_BITS_ARB;
          iattributes[niattribs++] = capabilities.getAccumRedBits();
          iattributes[niattribs++] = GL.WGL_ACCUM_GREEN_BITS_ARB;
          iattributes[niattribs++] = capabilities.getAccumGreenBits();
          iattributes[niattribs++] = GL.WGL_ACCUM_BLUE_BITS_ARB;
          iattributes[niattribs++] = capabilities.getAccumBlueBits();
          iattributes[niattribs++] = GL.WGL_ACCUM_ALPHA_BITS_ARB;
          iattributes[niattribs++] = capabilities.getAccumAlphaBits();
        }
        if (haveWGLARBMultisample) {
          if (capabilities.getSampleBuffers()) {
            iattributes[niattribs++] = GL.WGL_SAMPLE_BUFFERS_ARB;
            iattributes[niattribs++] = GL.GL_TRUE;
            iattributes[niattribs++] = GL.WGL_SAMPLES_ARB;
            iattributes[niattribs++] = capabilities.getNumSamples();
          }
        }
          
        int[] pformats = new int[MAX_PFORMATS];
        int[] numFormatsTmp = new int[1];
        if (dummyGL.wglChoosePixelFormatARB(hdc,
                                            iattributes, 0,
                                            fattributes, 0,
                                            MAX_PFORMATS,
                                            pformats, 0,
                                            numFormatsTmp, 0)) {
          numFormats = numFormatsTmp[0];
          if (numFormats > 0) {
            // Remove one-basing of pixel format (added on later)
            recommendedPixelFormat = pformats[0] - 1;
            if (DEBUG) {
              System.err.println(getThreadName() + ": Used wglChoosePixelFormatARB to recommend pixel format " + recommendedPixelFormat);
            }
          }
        } else {
          if (DEBUG) {
            System.err.println(getThreadName() + ": wglChoosePixelFormatARB failed: " + WGL.GetLastError() );
            Thread.dumpStack();
          }
        }
        if (DEBUG) {
          if (recommendedPixelFormat < 0) {
            System.err.print(getThreadName() + ": wglChoosePixelFormatARB didn't recommend a pixel format");
            if (capabilities.getSampleBuffers()) {
              System.err.print(" for multisampled GLCapabilities");
            }
            System.err.println();
          }
        }

        // Produce a list of GLCapabilities to give to the
        // GLCapabilitiesChooser.
        // Use wglGetPixelFormatAttribivARB instead of
        // DescribePixelFormat to get higher-precision information
        // about the pixel format (should make the GLCapabilities
        // more precise as well...i.e., remove the
        // "HardwareAccelerated" bit, which is basically
        // meaningless, and put in whether it can render to a
        // window, to a pbuffer, or to a pixmap)
        niattribs = 0;
        iattributes[0] = GL.WGL_NUMBER_PIXEL_FORMATS_ARB;
        if (dummyGL.wglGetPixelFormatAttribivARB(hdc, 0, 0, 1, iattributes, 0, iresults, 0)) {
          numFormats = iresults[0];
          // Should we be filtering out the pixel formats which aren't
          // applicable, as we are doing here?
          // We don't have enough information in the GLCapabilities to
          // represent those that aren't...
          iattributes[niattribs++] = GL.WGL_DRAW_TO_WINDOW_ARB;
          iattributes[niattribs++] = GL.WGL_ACCELERATION_ARB;
          iattributes[niattribs++] = GL.WGL_SUPPORT_OPENGL_ARB;
          iattributes[niattribs++] = GL.WGL_DEPTH_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_STENCIL_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_DOUBLE_BUFFER_ARB;
          iattributes[niattribs++] = GL.WGL_STEREO_ARB;
          iattributes[niattribs++] = GL.WGL_PIXEL_TYPE_ARB;
          iattributes[niattribs++] = GL.WGL_RED_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_GREEN_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_BLUE_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_ALPHA_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_ACCUM_RED_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_ACCUM_GREEN_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_ACCUM_BLUE_BITS_ARB;
          iattributes[niattribs++] = GL.WGL_ACCUM_ALPHA_BITS_ARB;
          if (haveWGLARBMultisample) {
            iattributes[niattribs++] = GL.WGL_SAMPLE_BUFFERS_ARB;
            iattributes[niattribs++] = GL.WGL_SAMPLES_ARB;
          }

          availableCaps = new GLCapabilities[numFormats];
          for (int i = 0; i < numFormats; i++) {
            if (!dummyGL.wglGetPixelFormatAttribivARB(hdc, i+1, 0, niattribs, iattributes, 0, iresults, 0)) {
              throw new GLException("Error getting pixel format attributes for pixel format " + (i + 1) + " of device context");
            }
            availableCaps[i] = iattributes2GLCapabilities(iattributes, iresults, niattribs, true);
          }
          if( freeWGLC ) {
            WGL.wglMakeCurrent( 0, 0 );
          }
          gotAvailableCaps = true;
        } else {
          int lastErr = WGL.GetLastError();
          // Intel Extreme graphics fails with a zero error code
          if (lastErr != 0) {
            throw new GLException("Unable to enumerate pixel formats of window using wglGetPixelFormatAttribivARB: error code " + WGL.GetLastError());
          }
        }
      }

      if (!gotAvailableCaps) {
        if (DEBUG) {
          if (!capabilities.getSampleBuffers()) {
            System.err.println(getThreadName() + ": Using ChoosePixelFormat because multisampling not requested");
          } else {
            System.err.println(getThreadName() + ": Using ChoosePixelFormat because no wglChoosePixelFormatARB: dummyGL = " + dummyGL);
          }
        }
        pfd = glCapabilities2PFD(capabilities, onscreen);
        // Remove one-basing of pixel format (added on later)
        recommendedPixelFormat = WGL.ChoosePixelFormat(hdc, pfd) - 1;

        numFormats = WGL.DescribePixelFormat(hdc, 1, 0, null);
        if (numFormats == 0) {
          throw new GLException("Unable to enumerate pixel formats of window for GLCapabilitiesChooser");
        }
        availableCaps = new GLCapabilities[numFormats];
        for (int i = 0; i < numFormats; i++) {
          if (WGL.DescribePixelFormat(hdc, 1 + i, pfd.size(), pfd) == 0) {
            throw new GLException("Error describing pixel format " + (1 + i) + " of device context");
          }
          availableCaps[i] = pfd2GLCapabilities(pfd);
        }
      }

      // Supply information to chooser
      pixelFormat = chooser.chooseCapabilities(capabilities, availableCaps, recommendedPixelFormat);
      if ((pixelFormat < 0) || (pixelFormat >= numFormats)) {
        throw new GLException("Invalid result " + pixelFormat +
                              " from GLCapabilitiesChooser (should be between 0 and " +
                              (numFormats - 1) + ")");
      }
      if (DEBUG) {
        System.err.println(getThreadName() + ": Chosen pixel format (" + pixelFormat + "):");
        System.err.println(availableCaps[pixelFormat]);
      }
      pixelFormat += 1; // one-base the index
      if (WGL.DescribePixelFormat(hdc, pixelFormat, pfd.size(), pfd) == 0) {
        throw new GLException("Error re-describing the chosen pixel format: " + WGL.GetLastError());
      }
    } else {
      // For now, use ChoosePixelFormat for offscreen surfaces until
      // we figure out how to properly choose an offscreen-
      // compatible pixel format
      pfd = glCapabilities2PFD(capabilities, onscreen);
      pixelFormat = WGL.ChoosePixelFormat(hdc, pfd);
    }
    if (!WGL.SetPixelFormat(hdc, pixelFormat, pfd)) {
      int lastError = WGL.GetLastError();
      if (DEBUG) {
        System.err.println(getThreadName() + ": SetPixelFormat failed: current context = " + WGL.wglGetCurrentContext() +
                           ", current DC = " + WGL.wglGetCurrentDC());
        System.err.println(getThreadName() + ": GetPixelFormat(hdc " + hdcToString(hdc) + ") returns " + WGL.GetPixelFormat(hdc));
      }
      throw new GLException("Unable to set pixel format " + pixelFormat + " for device context " + hdcToString(hdc) + ": error code " + lastError);
    }
    hglrc = WGL.wglCreateContext(hdc);
    if (DEBUG) {
      System.err.println(getThreadName() + ": !!! Created OpenGL context " + hglrc + " for device context " + hdcToString(hdc) + " using pixel format " + pixelFormat);
    }
    if (hglrc == 0) {
      throw new GLException("Unable to create OpenGL context");
    }
  }

  protected long getHGLRC() {
    return hglrc;
  }

  static PIXELFORMATDESCRIPTOR glCapabilities2PFD(GLCapabilities caps, boolean onscreen) {
    int colorDepth = (caps.getRedBits() +
                      caps.getGreenBits() +
                      caps.getBlueBits());
    if (colorDepth < 15) {
      throw new GLException("Bit depths < 15 (i.e., non-true-color) not supported");
    }
    PIXELFORMATDESCRIPTOR pfd = newPixelFormatDescriptor();
    int pfdFlags = (WGL.PFD_SUPPORT_OPENGL |
                    WGL.PFD_GENERIC_ACCELERATED);
    if (caps.getDoubleBuffered()) {
      pfdFlags |= WGL.PFD_DOUBLEBUFFER;
    }
    if (onscreen) {
      pfdFlags |= WGL.PFD_DRAW_TO_WINDOW;
    } else {
      pfdFlags |= WGL.PFD_DRAW_TO_BITMAP;
    }
    pfd.dwFlags(pfdFlags);
    pfd.iPixelType((byte) WGL.PFD_TYPE_RGBA);
    pfd.cColorBits((byte) colorDepth);
    pfd.cRedBits  ((byte) caps.getRedBits());
    pfd.cGreenBits((byte) caps.getGreenBits());
    pfd.cBlueBits ((byte) caps.getBlueBits());
    pfd.cAlphaBits((byte) caps.getAlphaBits());
    int accumDepth = (caps.getAccumRedBits() +
                      caps.getAccumGreenBits() +
                      caps.getAccumBlueBits());
    pfd.cAccumBits     ((byte) accumDepth);
    pfd.cAccumRedBits  ((byte) caps.getAccumRedBits());
    pfd.cAccumGreenBits((byte) caps.getAccumGreenBits());
    pfd.cAccumBlueBits ((byte) caps.getAccumBlueBits());
    pfd.cAccumAlphaBits((byte) caps.getAccumAlphaBits());
    pfd.cDepthBits((byte) caps.getDepthBits());
    pfd.cStencilBits((byte) caps.getStencilBits());
    pfd.iLayerType((byte) WGL.PFD_MAIN_PLANE);
    return pfd;
  }

  static PIXELFORMATDESCRIPTOR newPixelFormatDescriptor() {
    PIXELFORMATDESCRIPTOR pfd = new PIXELFORMATDESCRIPTOR();
    pfd.nSize((short) pfd.size());
    pfd.nVersion((short) 1);
    return pfd;
  }

  static GLCapabilities pfd2GLCapabilities(PIXELFORMATDESCRIPTOR pfd) {
    if ((pfd.dwFlags() & WGL.PFD_SUPPORT_OPENGL) == 0) {
      return null;
    }
    GLCapabilities res = new GLCapabilities();
    res.setRedBits       (pfd.cRedBits());
    res.setGreenBits     (pfd.cGreenBits());
    res.setBlueBits      (pfd.cBlueBits());
    res.setAlphaBits     (pfd.cAlphaBits());
    res.setAccumRedBits  (pfd.cAccumRedBits());
    res.setAccumGreenBits(pfd.cAccumGreenBits());
    res.setAccumBlueBits (pfd.cAccumBlueBits());
    res.setAccumAlphaBits(pfd.cAccumAlphaBits());
    res.setDepthBits     (pfd.cDepthBits());
    res.setStencilBits   (pfd.cStencilBits());
    res.setDoubleBuffered((pfd.dwFlags() & WGL.PFD_DOUBLEBUFFER) != 0);
    res.setStereo        ((pfd.dwFlags() & WGL.PFD_STEREO) != 0);
    res.setHardwareAccelerated(((pfd.dwFlags() & WGL.PFD_GENERIC_FORMAT) == 0) ||
			       ((pfd.dwFlags() & WGL.PFD_GENERIC_ACCELERATED) != 0));
    return res;
  }

  static GLCapabilities iattributes2GLCapabilities(int[] iattribs,
                                                   int[] iresults,
                                                   int   niattribs,
                                                   boolean requireRenderToWindow) {
    GLCapabilities res = new GLCapabilities();
    for (int i = 0; i < niattribs; i++) {
      switch (iattribs[i]) {
        case GL.WGL_DRAW_TO_WINDOW_ARB:
          if (iresults[i] != GL.GL_TRUE)
            return null;
          break;

        case GL.WGL_ACCELERATION_ARB:
          res.setHardwareAccelerated(iresults[i] == GL.WGL_FULL_ACCELERATION_ARB);
          break;

        case GL.WGL_SUPPORT_OPENGL_ARB:
          if (iresults[i] != GL.GL_TRUE)
            return null;
          break;

        case GL.WGL_DEPTH_BITS_ARB:
          res.setDepthBits(iresults[i]);
          break;

        case GL.WGL_STENCIL_BITS_ARB:
          res.setStencilBits(iresults[i]);
          break;

        case GL.WGL_DOUBLE_BUFFER_ARB:
          res.setDoubleBuffered(iresults[i] == GL.GL_TRUE);
          break;

        case GL.WGL_STEREO_ARB:
          res.setStereo(iresults[i] == GL.GL_TRUE);
          break;

        case GL.WGL_PIXEL_TYPE_ARB:
          if (iresults[i] != GL.WGL_TYPE_RGBA_ARB)
            return null;
          break;

        case GL.WGL_RED_BITS_ARB:
          res.setRedBits(iresults[i]);
          break;
          
        case GL.WGL_GREEN_BITS_ARB:
          res.setGreenBits(iresults[i]);
          break;

        case GL.WGL_BLUE_BITS_ARB:
          res.setBlueBits(iresults[i]);
          break;

        case GL.WGL_ALPHA_BITS_ARB:
          res.setAlphaBits(iresults[i]);
          break;

        case GL.WGL_ACCUM_RED_BITS_ARB:
          res.setAccumRedBits(iresults[i]);
          break;

        case GL.WGL_ACCUM_GREEN_BITS_ARB:
          res.setAccumGreenBits(iresults[i]);
          break;

        case GL.WGL_ACCUM_BLUE_BITS_ARB:
          res.setAccumBlueBits(iresults[i]);
          break;

        case GL.WGL_ACCUM_ALPHA_BITS_ARB:
          res.setAccumAlphaBits(iresults[i]);
          break;

        case GL.WGL_SAMPLE_BUFFERS_ARB:
          res.setSampleBuffers(iresults[i] == GL.GL_TRUE);
          break;

        case GL.WGL_SAMPLES_ARB:
          res.setNumSamples(iresults[i]);
          break;

        default:
          throw new GLException("Unknown pixel format attribute " + iattribs[i]);
      }
    }
    return res;
  }

  protected static String hdcToString(long hdc) {
    return "0x" + Long.toHexString(hdc);
  }

  protected boolean haveWGLARBPbuffer() {
    return haveWGLARBPbuffer;
  }
}