summaryrefslogtreecommitdiffstats
path: root/src/mesa/drivers/d3d/WGL.C
blob: 2d1a6a0c4d56d41f557827f86487a01636297c30 (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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
/*===========================================================================*/
/*                                                                           */
/* Mesa-3.0 Makefile for DirectX 6                                           */
/*                                                                           */
/* By Leigh McRae                                                            */
/*                                                                           */
/* http://www.altsoftware.com/                                               */
/*                                                                           */
/* Copyright (c) 1998-1997  alt.software inc.  All Rights Reserved           */
/*===========================================================================*/
#include "D3DMesa.h"
/*===========================================================================*/
/* Window managment.                                                         */
/*===========================================================================*/
static BOOL    InitOpenGL( HINSTANCE hInst );
static BOOL    TermOpenGL( HINSTANCE hInst );
static BOOL     ResizeContext( GLcontext *ctx );
static BOOL    MakeCurrent( D3DMESACONTEXT *pContext );
static void    DestroyContext( D3DMESACONTEXT *pContext );
static BOOL    UnBindWindow( D3DMESACONTEXT *pContext );
LONG APIENTRY  wglMonitorProc( HWND hwnd, UINT message, UINT wParam, LONG lParam );
/*===========================================================================*/
/* Mesa hooks.                                                               */
/*===========================================================================*/
static void SetupDDPointers( GLcontext *ctx );
static void SetupSWDDPointers( GLcontext *ctx );
static void SetupHWDDPointers( GLcontext *ctx );
static void SetupNULLDDPointers( GLcontext *ctx );
static const char *RendererString( void );

/* State Management hooks. */
static void       SetColor( GLcontext *ctx, GLubyte r, GLubyte g, GLubyte b, GLubyte a );
static void       ClearColor( GLcontext *ctx, GLubyte r, GLubyte g, GLubyte b, GLubyte a );
static GLboolean SetBuffer( GLcontext *ctx, GLenum buffer );

/* Window Management hooks. */
static void GetBufferSize( GLcontext *ctx, GLuint *width, GLuint *height );
static void SetViewport( GLcontext *ctx, GLint x, GLint y, GLsizei w, GLsizei h );
static void Flush( GLcontext *ctx );

/* Span rendering hooks. */
void WSpanRGB( const GLcontext* ctx, GLuint n, GLint x, GLint y, const GLubyte rgb[][3], const GLubyte mask[] );
void WSpanRGBA( const GLcontext* ctx, GLuint n, GLint x, GLint y, const GLubyte rgba[][4], const GLubyte mask[] );
void WSpanRGBAMono( const GLcontext* ctx, GLuint n, GLint x, GLint y, const GLubyte mask[] );
void WPixelsRGBA( const GLcontext* ctx, GLuint n, const GLint x[], const GLint y[], const GLubyte rgba[][4], const GLubyte mask[] );
void WPixelsRGBAMono( const GLcontext* ctx, GLuint n, const GLint x[], const GLint y[], const GLubyte mask[] );
void RSpanRGBA( const GLcontext* ctx, GLuint n, GLint x, GLint y, GLubyte rgba[][4] );
void RPixelsRGBA( const GLcontext* ctx, GLuint n, const GLint x[], const GLint y[], GLubyte rgba[][4], const GLubyte mask[] );
GLbitfield ClearBuffers( GLcontext *ctx, GLbitfield mask, GLboolean all, GLint x, GLint y, GLint width, GLint height );

/* Primitve rendering hooks. */
GLboolean  RenderVertexBuffer( GLcontext *ctx, GLboolean allDone );
void             RenderOneTriangle( GLcontext *ctx, GLuint v1, GLuint v2, GLuint v3, GLuint pv );
void     RenderOneLine( GLcontext *ctx, GLuint v1, GLuint v2, GLuint pv );
GLbitfield ClearBuffersD3D( GLcontext *ctx, GLbitfield mask, GLboolean all, GLint x, GLint y, GLint width, GLint height );

/* Texture Management hooks. */
static void TextureBind( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj );
static void TextureLoad( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj, GLint level, GLint internalFormat, const struct gl_texture_image *image );
static void TextureSubImage( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLint internalFormat, const struct gl_texture_image *image );
/*===========================================================================*/
/* Global variables.                                                         */
/*===========================================================================*/
D3DMESACONTEXT *pD3DCurrent,     
	       *pD3DDefault;     /* Thin support context. */

struct __extensions__   ext[] = {

    { (PROC)glPolygonOffsetEXT,        "glPolygonOffsetEXT"       },
    { (PROC)glBlendEquationEXT,        "glBlendEquationEXT"       },
    { (PROC)glBlendColorEXT,           "glBlendColorExt"          },
    { (PROC)glVertexPointerEXT,        "glVertexPointerEXT"       },
    { (PROC)glNormalPointerEXT,        "glNormalPointerEXT"       },
    { (PROC)glColorPointerEXT,         "glColorPointerEXT"        },
    { (PROC)glIndexPointerEXT,         "glIndexPointerEXT"        },
    { (PROC)glTexCoordPointerEXT,      "glTexCoordPointer"        },
    { (PROC)glEdgeFlagPointerEXT,      "glEdgeFlagPointerEXT"     },
    { (PROC)glGetPointervEXT,          "glGetPointervEXT"         },
    { (PROC)glArrayElementEXT,         "glArrayElementEXT"        },
    { (PROC)glDrawArraysEXT,           "glDrawArrayEXT"           },
    { (PROC)glAreTexturesResidentEXT,  "glAreTexturesResidentEXT" },
    { (PROC)glBindTextureEXT,          "glBindTextureEXT"         },
    { (PROC)glDeleteTexturesEXT,       "glDeleteTexturesEXT"      },
    { (PROC)glGenTexturesEXT,          "glGenTexturesEXT"         },
    { (PROC)glIsTextureEXT,            "glIsTextureEXT"           },
    { (PROC)glPrioritizeTexturesEXT,   "glPrioritizeTexturesEXT"  },
    { (PROC)glCopyTexSubImage3DEXT,    "glCopyTexSubImage3DEXT"   },
    { (PROC)glTexImage3DEXT,           "glTexImage3DEXT"          },
    { (PROC)glTexSubImage3DEXT,        "glTexSubImage3DEXT"       },
};

int             qt_ext = sizeof(ext) / sizeof(ext[0]);
float   g_DepthScale,
	  g_MaxDepth;
/*===========================================================================*/
/*  When a process loads this DLL we will setup the linked list for context  */
/* management and create a default context that will support the API until   */
/* the user creates and binds thier own.  This THIN default context is useful*/
/* to have around.                                                           */
/*  When the process terminates we will clean up all resources here.         */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
BOOL APIENTRY   DllMain( HINSTANCE hInst, DWORD reason, LPVOID reserved )
{
  switch( reason ) 
  {
    case DLL_PROCESS_ATTACH:
	 return InitOpenGL( hInst );

    case DLL_PROCESS_DETACH:
	 return TermOpenGL( hInst );
  }     

  return TRUE;
}
/*===========================================================================*/
/*  The first thing we do when this dll is hit is connect to the dll that has*/
/* handles all the DirectX 6 rendering.  I decided to use another dll as DX6 */
/* is all C++ and Mesa-3.0 is C (thats a good thing).  This way I can write  */
/* the DX6 in C++ and Mesa-3.0 in C without having to worry about linkage.   */
/* I feel this is easy and better then using static wrappers as it is likely */
/* faster and it allows me to just develope the one without compiling the    */
/* other.                                                                    */
/*  NOTE that at this point we don't have much other than a very thin context*/
/* that will support the API calls only to the point of not causing the app  */
/* to crash from the API table being empty.                                  */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
static BOOL  InitOpenGL( HINSTANCE hInst )
{
  /* Allocate and clear the default context. */
  pD3DDefault = (PD3DMESACONTEXT)ALLOC( sizeof(D3DMESACONTEXT) );
  if ( pD3DDefault == NULL )
    return FALSE;
  memset( pD3DDefault, 0, sizeof(D3DMESACONTEXT) );

  /*  Clear the D3D vertex buffer so that values not used will be zero.  This */
  /* save me from some redundant work.                                        */
  memset( &D3DTLVertices, 0, sizeof(D3DTLVertices) );

  /*  Update the link.  We uses a circular list so that it is easy to  */
  /* add and search.  This context will also be used for head and tail.*/
  pD3DDefault->next = pD3DDefault;

  /*========================================================================*/
  /* Do all core Mesa stuff.                                                */
  /*========================================================================*/
  pD3DDefault->gl_visual = gl_create_visual( TRUE,
									GL_FALSE,   /* software alpha */
									FALSE,      /* db_flag */
									GL_FALSE,   /* stereo */
									16,         /* depth_bits */
									8,          /* stencil_bits */
									8,          /* accum_bits */
									0,          /* index bits */
									8,8,8,8 );  /* r, g, b, a bits */

  if ( pD3DDefault->gl_visual == NULL)  
  {
    FREE( pD3DDefault );
    return FALSE;
  }

  /* Allocate a new Mesa context */
  pD3DDefault->gl_ctx = gl_create_context( pD3DDefault->gl_visual, NULL, pD3DDefault, GL_TRUE );
  if ( pD3DDefault->gl_ctx == NULL ) 
  {
    gl_destroy_visual( pD3DDefault->gl_visual );
    FREE( pD3DDefault );
    return FALSE;
  }

  /* Allocate a new Mesa frame buffer */
  pD3DDefault->gl_buffer = gl_create_framebuffer( pD3DDefault->gl_visual );
  if ( pD3DDefault->gl_buffer == NULL )
  {
    gl_destroy_visual( pD3DDefault->gl_visual );
    gl_destroy_context( pD3DDefault->gl_ctx );
    FREE( pD3DDefault );
    return FALSE;
  }
  SetupDDPointers( pD3DDefault->gl_ctx );
  gl_make_current( pD3DDefault->gl_ctx, pD3DDefault->gl_buffer );

  return TRUE;
}
/*===========================================================================*/
/*  This function will create a new D3D context but will not create the D3D  */
/* surfaces or even an instance of D3D (see at GetBufferSize). The only stuff*/
/* done here is the internal Mesa stuff and some Win32 handles.              */
/*===========================================================================*/
/* RETURN: casted pointer to the context, NULL.                              */
/*===========================================================================*/
HGLRC APIENTRY wglCreateContext( HDC hdc )
{
  D3DMESACONTEXT        *pNewContext;
  DWORD                 dwCoopFlags = DDSCL_NORMAL;
  RECT                  rectClient;
  POINT                 pt;

  /* ALLOC and clear the new context. */
  pNewContext = (PD3DMESACONTEXT)ALLOC( sizeof(D3DMESACONTEXT) );
  if ( pNewContext == NULL )
  {
    SetLastError( 0 );
    return (HGLRC)NULL;
  }
  memset( pNewContext, 0, sizeof(D3DMESACONTEXT) );

  /*========================================================================*/
  /* Do all core Mesa stuff.                                                */
  /*========================================================================*/

  /* TODO: support more then one visual. */
  pNewContext->gl_visual = gl_create_visual( TRUE,
									GL_TRUE,   /* software alpha */
									TRUE,       /* db_flag */
									GL_FALSE,   /* stereo */
									16,         /* depth_bits */
									8,          /* stencil_bits */
									8,          /* accum_bits */
									0,          /* index bits */
									8,8,8,8 );  /* r, g, b, a bits */
  if ( pNewContext->gl_visual == NULL) 
  {
    FREE( pNewContext );
    SetLastError( 0 );
    return (HGLRC)NULL;
  }

  /* Allocate a new Mesa context */
  pNewContext->gl_ctx = gl_create_context( pNewContext->gl_visual, NULL, pNewContext, GL_TRUE );
  if ( pNewContext->gl_ctx == NULL ) 
  {
    gl_destroy_visual( pNewContext->gl_visual );
    FREE( pNewContext );
    SetLastError( 0 );
    return (HGLRC)NULL;
  }

  /* Allocate a new Mesa frame buffer */
  pNewContext->gl_buffer = gl_create_framebuffer( pNewContext->gl_visual );
  if ( pNewContext->gl_buffer == NULL )
  {
    gl_destroy_visual( pNewContext->gl_visual );
    gl_destroy_context( pNewContext->gl_ctx );
    FREE( pNewContext );
    SetLastError( 0 );
    return (HGLRC)NULL;
  }

  /*========================================================================*/
  /* Do all the driver stuff.                                               */
  /*========================================================================*/
  pNewContext->hdc  = hdc;
  pNewContext->next = pD3DDefault->next;
  pD3DDefault->next = pNewContext; /* Add to circular list. */

  /* Create the HAL for the new context. */
  pNewContext->pShared = InitHAL( WindowFromDC(hdc) );

  return (HGLRC)pNewContext;
}
/*===========================================================================*/
/*  This is a wrapper function that is supported by MakeCurrent.             */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
BOOL APIENTRY  wglMakeCurrent( HDC hdc, HGLRC hglrc )
{
   return MakeCurrent((D3DMESACONTEXT *)hglrc);
}
/*===========================================================================*/
/*  MakeCurrent will unbind whatever context is current (if any) & then bind */
/* the supplied context.  A context that is bound has it's window proc hooked*/
/* with the wglMonitorProc and the context pointer is saved in pD3DCurrent.    */
/* Once the context is bound we update the Mesa-3.0 hooks (SetDDPointers) and*/
/* the viewport (Mesa-.30 and DX6).                                          */
/*                                                                           */
/* TODO: this function can't fail.                                           */
/*===========================================================================*/
/* RETURN: TRUE                                                              */
/*===========================================================================*/
static BOOL MakeCurrent( D3DMESACONTEXT *pContext )
{
   D3DMESACONTEXT *pNext;

   /*====================================================================*/
   /* This is a special case that is a request to have no context bound. */
   /*====================================================================*/
   if ( pContext == NULL )
   {
	/* Walk the whole list. We start and end at the Default context. */
	for( pNext = pD3DDefault->next; pNext != pD3DDefault; pNext = pNext->next )
	  UnBindWindow( pNext );
      
	return TRUE;
   }

   /*=================================================*/
   /* Make for a fast redundant use of this function. */
   /*=================================================*/
   if ( pD3DCurrent == pContext )
      return TRUE;

   /*=============================*/
   /* Unbind the current context. */
   /*=============================*/
   UnBindWindow( pD3DCurrent );

   /*=====================================*/
   /* Let Mesa-3.0 we have a new context. */
   /*=====================================*/
   SetupDDPointers( pContext->gl_ctx );
   gl_make_current( pContext->gl_ctx, pContext->gl_buffer );

   /*  We are done so set the internal current context. */
   if ( pContext != pD3DDefault )
   {
	ResizeContext( pContext->gl_ctx );
	pContext->hOldProc = (WNDPROC)GetWindowLong( pContext->pShared->hwnd, GWL_WNDPROC );
	SetWindowLong( pContext->pShared->hwnd, GWL_WNDPROC, (LONG)wglMonitorProc );
   }
   pD3DCurrent = pContext;

   return TRUE;
}
/*===========================================================================*/
/*  This function will only return the current window size.  I have re-done  */   
/* this function so that it doesn't check the current size and react to it as*/   
/* I should be able to have all the react code in the WM_SIZE message.  The  */   
/* old version would check the current window size and create/resize the HAL */   
/* surfaces if they have changed.  I needed to delay the creation if the     */   
/* surfaces because sometimes I wouldn't have a window size so this is where */   
/* I delayed it.  If you are reading this then all went ok!                  */   
/*  The default context will return a zero sized window and I'm not sure if  */
/* this is ok at this point (TODO).                                          */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void GetBufferSize( GLcontext *ctx, GLuint *width, GLuint *height )
{
  D3DMESACONTEXT        *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

  /* Fall through for the default because that is one of the uses for it. */
  if ( pContext == pD3DDefault )
  {
    *width  = 0;
    *height = 0;
  }
  else
  {
    *width  = pContext->pShared->dwWidth;
    *height = pContext->pShared->dwHeight;
  }
}
/*===========================================================================*/
/*                                                                           */
/*                                                                           */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static BOOL ResizeContext( GLcontext *ctx )
{
  D3DMESACONTEXT        *pContext = (D3DMESACONTEXT *)ctx->DriverCtx,
		    *pCurrentTemp;
  RECT                  rectClient;
  POINT                 pt;
  DWORD                 dwWidth,
		    dwHeight;
  static BOOL           bDDrawLock = FALSE;

  /* Make sure we have some values. */
  if ( (pContext->hdc == NULL ) || 
	  (pContext->pShared->hwnd != WindowFromDC(pContext->hdc)) ||
       (pContext == pD3DDefault) )
    return FALSE;

  /* Having problems with DDraw sending resize messages before I was done. */
  if( bDDrawLock == TRUE )
    return FALSE;

  // TODO: don't think I need this anymore.
  pCurrentTemp = pD3DCurrent;
  pD3DCurrent = pD3DDefault;
  bDDrawLock = TRUE;

  /* Get the current window dimentions. */
  UpdateScreenPosHAL( pContext->pShared );
  dwWidth  = pContext->pShared->rectW.right - pContext->pShared->rectW.left;
  dwHeight = pContext->pShared->rectW.bottom - pContext->pShared->rectW.top;

  /* Is the size of the OffScreen Render different? */
  if ( (dwWidth != pContext->pShared->dwWidth) || (dwHeight != pContext->pShared->dwHeight) )
  {
    /* Create all the D3D surfaces and device. */
    CreateHAL( pContext->pShared );

    /*  I did this so that software rendering would still work as */
    /* I don't need to scale the z values twice.                  */
    g_DepthScale        = (pContext->pShared->bHardware) ? 1.0 : ((float)0x00FFFFFF);
    g_MaxDepth          = (pContext->pShared->bHardware) ? 1.0 : ((float)0x00FFFFFF);
    gl_DepthRange( pContext->gl_ctx, ctx->Viewport.Near, ctx->Viewport.Far );

    /* Make sure we have a viewport. */
    gl_Viewport( pContext->gl_ctx, 0, 0, dwWidth, dwHeight );

    /* Update Mesa as we might have changed from SW <-> HW. */
    SetupDDPointers( pContext->gl_ctx );
    gl_make_current( pContext->gl_ctx, pContext->gl_buffer );

    /*  If we are in HW we need to load the current texture if there is one already. */
    //    if ( (ctx->Texture.Set[ctx->Texture.CurrentSet].Current != NULL) &&
    //      (pContext->pShared->bHardware == TRUE) )
    //    {
    //   CreateTMgrHAL( pContext->pShared,
    //                           ctx->Texture.Set[ctx->Texture.CurrentSet].Current->Name,
    //                           0,     
    //                           ctx->Texture.Set[ctx->Texture.CurrentSet].Current->Image[0]->Format,
    //                           (RECT *)NULL,
    //                           ctx->Texture.Set[ctx->Texture.CurrentSet].Current->Image[0]->Width,
    //                           ctx->Texture.Set[ctx->Texture.CurrentSet].Current->Image[0]->Height,
    //                           TM_ACTION_BIND,
    //                           (void *)ctx->Texture.Set[ctx->Texture.CurrentSet].Current->Image[0]->Data );
    //    }
  }

  // TODO: don't think I need this anymore.
  pD3DCurrent = pCurrentTemp;
  bDDrawLock = FALSE;

  return TRUE;
}

/*===========================================================================*
/*  This function will Blt the render buffer to the PRIMARY surface. I repeat*/
/* this code for the other SwapBuffer like functions and the flush (didn't   */
/* want the function calling overhead).  Thsi could have been a macro...     */
/*                                                                           */
/* TODO: there are some problems with viewport/scissoring.                   */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
BOOL APIENTRY  wglSwapBuffers( HDC hdc )
{
  /* Fall through for the default because that is one of the uses for it. */
  if ( pD3DCurrent == pD3DDefault )
    return FALSE;

  SwapBuffersHAL( pD3DCurrent->pShared );

  return TRUE;
}
/*===========================================================================*/
/*  Same as wglSwapBuffers.                                                  */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
BOOL APIENTRY  SwapBuffers( HDC hdc )
{
  /* Fall through for the default because that is one of the uses for it. */
  if ( pD3DCurrent == pD3DDefault )
    return FALSE;

  SwapBuffersHAL( pD3DCurrent->pShared );

  return TRUE;
}
/*===========================================================================*/
/*  This should be ok as none of the SwapBuffers will cause a redundant Blt  */
/* as none of my Swap functions will call flush.  This should also allow     */
/* sinlge buffered applications to work (not really worried though).  Some   */
/* applications may flush then swap but then this is there fault IMHO.       */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void Flush( GLcontext *ctx )
{
  /* Fall through for the default because that is one of the uses for it. */
  if ( pD3DCurrent == pD3DDefault )
    return;

  SwapBuffersHAL( pD3DCurrent->pShared );
}
/*===========================================================================*/
/*  For now this function will ignore the supplied PF. If I'm going to allow */
/* the user to choice the mode and device at startup I'm going to have to do */
/* something different.                                                      */
/*                                                                           */
/* TODO: use the linked list of modes to build a pixel format to be returned */
/*      to the caller.                                                       */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   wglChoosePixelFormat( HDC hdc, CONST PIXELFORMATDESCRIPTOR *ppfd )
{
   return 1;
}
/*===========================================================================*/
/*  See wglChoosePixelFormat.                                                */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   ChoosePixelFormat( HDC hdc, CONST PIXELFORMATDESCRIPTOR *ppfd )
{
  return wglChoosePixelFormat(hdc,ppfd);
}
/*===========================================================================*/
/*  This function (for now) returns a static PF everytime.  This is just to  */
/* allow things to continue.                                                 */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   wglDescribePixelFormat( HDC hdc, int iPixelFormat, UINT nBytes, LPPIXELFORMATDESCRIPTOR ppfd )
{
   static PIXELFORMATDESCRIPTOR  pfd = 
   {
      sizeof(PIXELFORMATDESCRIPTOR),   /* size */
      1,                               /* version */
      PFD_SUPPORT_OPENGL |
      PFD_DRAW_TO_WINDOW |
      PFD_DOUBLEBUFFER,                /* support double-buffering */
      PFD_TYPE_RGBA,                   /* color type */
      16,                              /* prefered color depth */
      0, 0, 0, 0, 0, 0,                /* color bits (ignored) */
      0,                               /* no alpha buffer */
      0,                               /* alpha bits (ignored) */
      0,                               /* no accumulation buffer */
      0, 0, 0, 0,                      /* accum bits (ignored) */
      16,                              /* depth buffer */
      0,                               /* no stencil buffer */
      0,                               /* no auxiliary buffers */
      PFD_MAIN_PLANE,                  /* main layer */
      0,                               /* reserved */
      0, 0, 0,                         /* no layer, visible, damage masks */
   };

   /* Return the address of this static PF if one was requested. */
   if ( ppfd != NULL )
      memcpy( ppfd, &pfd, sizeof(PIXELFORMATDESCRIPTOR) );

  return 1;
}
/*===========================================================================*/
/*  See wglDescribePixelFormat.                                              */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   DescribePixelFormat( HDC hdc, int iPixelFormat, UINT nBytes, LPPIXELFORMATDESCRIPTOR ppfd )
{
  return wglDescribePixelFormat(hdc,iPixelFormat,nBytes,ppfd);
}
/*===========================================================================*/
/*  This function will always return 1 for now.  Just to allow for support.  */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   wglGetPixelFormat( HDC hdc )
{
   return 1;
}
/*===========================================================================*/
/*  See wglGetPixelFormat.                                                   */
/*===========================================================================*/
/* RETURN: 1.                                                                */
/*===========================================================================*/
int APIENTRY   GetPixelFormat( HDC hdc )
{
   return wglGetPixelFormat(hdc);
}
/*===========================================================================*/
/*  This will aways work for now.                                            */
/*===========================================================================*/
/* RETURN: TRUE.                                                             */
/*===========================================================================*/
BOOL APIENTRY  wglSetPixelFormat( HDC hdc, int iPixelFormat, CONST PIXELFORMATDESCRIPTOR *ppfd )
{
   return TRUE;
}
/*===========================================================================*/
/*  See wglSetPixelFormat.                                                   */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
BOOL APIENTRY  SetPixelFormat( HDC hdc, int iPixelFormat, CONST PIXELFORMATDESCRIPTOR *ppfd )
{
   return wglSetPixelFormat(hdc,iPixelFormat,ppfd);
}
/*===========================================================================*/
/*  This is a wrapper function that is supported by my own internal function.*/
/* that takes my own D3D Mesa context structure.  This so I can reuse the    */
/* function (no need for speed).                                             */
/*===========================================================================*/
/* RETURN: TRUE.                                                             */
/*===========================================================================*/
BOOL APIENTRY  wglDeleteContext( HGLRC hglrc )
{
   DestroyContext( (D3DMESACONTEXT *)hglrc );

   return TRUE;
}
/*===========================================================================*/
/*  Simple getter function that uses a cast.                                 */
/*===========================================================================*/
/* RETURN: casted pointer to the context, NULL.                              */
/*===========================================================================*/
HGLRC APIENTRY wglGetCurrentContext( VOID )
{
   return (pD3DCurrent) ? (HGLRC)pD3DCurrent : (HGLRC)NULL;
}
/*===========================================================================*/
/* No support.                                                               */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglCopyContext( HGLRC hglrcSrc, HGLRC hglrcDst, UINT mask )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/* No support.                                                               */
/*===========================================================================*/
/* RETURN: NULL.                                                             */
/*===========================================================================*/
HGLRC APIENTRY wglCreateLayerContext( HDC hdc,int iLayerPlane )
{
   SetLastError( 0 );
   return (HGLRC)NULL;
}
/*===========================================================================*/
/*  Simple getter function.                                                  */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
HDC APIENTRY   wglGetCurrentDC( VOID )
{
   return (pD3DCurrent) ? pD3DCurrent->hdc : (HDC)NULL;
}
/*===========================================================================*/
/*  Simply call that searches the supported extensions for a match & returns */
/* the pointer to the function that lends support.                           */
/*===========================================================================*/
/* RETURN: pointer to API call, NULL.                                        */
/*===========================================================================*/
PROC APIENTRY  wglGetProcAddress( LPCSTR lpszProc )
{
   int   index;

   for( index = 0; index < qt_ext; index++ )
      if( !strcmp(lpszProc,ext[index].name) )
	 return ext[index].proc;

   SetLastError( 0 );
   return NULL;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglShareLists( HGLRC hglrc1, HGLRC hglrc2 )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglUseFontBitmaps( HDC fontDevice, DWORD firstChar, DWORD numChars, DWORD listBase )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglUseFontBitmapsW( HDC hdc,DWORD first,DWORD count,DWORD listBase )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglUseFontOutlinesA( HDC hdc, DWORD first, DWORD count, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglUseFontOutlinesW( HDC hdc,DWORD first,DWORD count, DWORD listBase,FLOAT deviation, FLOAT extrusion,int format, LPGLYPHMETRICSFLOAT lpgmf )
{
   SetLastError( 0 );
   return FALSE ;
}
/*===========================================================================*/
/*  No support.                                                              */
/*===========================================================================*/
/* RETURN: FALSE.                                                            */
/*===========================================================================*/
BOOL APIENTRY  wglSwapLayerBuffers( HDC hdc, UINT fuPlanes )
{
   SetLastError( 0 );
   return FALSE;
}
/*===========================================================================*/
/*  This function will be hooked into the window that has been bound.  Right */
/* now it is used to track the window size and position.  Also the we clean  */
/* up the currrent context when the window is close/destroyed.               */
/*                                                                           */
/* TODO: there might be something wrong here as some games (Heretic II) don't*/
/*      track the window quit right.                                         */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
LONG APIENTRY  wglMonitorProc( HWND hwnd, UINT message, UINT wParam, LONG lParam )
{
  WNDPROC       hOldProc;
  GLint width,
	  height;

  switch( message ) 
  {
//      case WM_PAINT:
//        break;
//      case WM_ACTIVATE:
//         break;
//      case WM_SHOWWINDOW:
//         break;

    case UM_FATALSHUTDOWN:
	 /* Support the API until we die... */
	 MakeCurrent( pD3DDefault );
	 break;

    case WM_MOVE:
    case WM_DISPLAYCHANGE:
    case WM_SIZE:
	 ResizeContext( pD3DCurrent->gl_ctx );
	 break;

    case WM_CLOSE:
    case WM_DESTROY:
	 /* Support the API until we die... */
	 hOldProc = pD3DCurrent->hOldProc;
	 DestroyContext( pD3DCurrent );
	 return (hOldProc)(hwnd,message,wParam,lParam);
  }

  return (pD3DCurrent->hOldProc)(hwnd,message,wParam,lParam);
}

/**********************************************************************/
/*****              Miscellaneous device driver funcs             *****/
/**********************************************************************/

/*===========================================================================*/
/*  Not reacting to this as I'm only supporting drawing to the back buffer   */
/* right now.                                                                */
/*===========================================================================*/
/* RETURN: TRUE.                                                             */
/*===========================================================================*/
static GLboolean SetBuffer( GLcontext *ctx, GLenum buffer )
{
   if (buffer == GL_BACK_LEFT)
      return GL_TRUE;
   else
      return GL_FALSE;
}
/*===========================================================================*/
/*  This proc will be called by Mesa when the viewport has been set.  So if  */
/* we have a context and it isn't the default then we should let D3D know of */
/* the change.                                                               */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void SetViewport( GLcontext *ctx, GLint x, GLint y, GLsizei w, GLsizei h )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;
   RECT           rect;

   /* Make sure we can set a viewport. */
   if ( pContext->pShared && (pContext != pD3DDefault) )
   {
	 // TODO: might be needed.
     UpdateScreenPosHAL( pContext->pShared );
	rect.left   = x;
	rect.right  = x + w;
	rect.top    = y;
	rect.bottom = y + h;

	// TODO: shared struct should make this call smaller
     SetViewportHAL( pContext->pShared, &rect, 0.0F, 1.0F );
   }
}
/*===========================================================================*/
/*  This function could be better I guess but I decided just to grab the four*/
/* components and store then seperately.  Makes it easier to use IMHO.       */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void ClearColor( GLcontext *ctx, GLubyte r, GLubyte g, GLubyte b, GLubyte a )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   pContext->aClear = a;
   pContext->bClear = b;
   pContext->gClear = g;
   pContext->rClear = r;
}
/*===========================================================================*/
/*  This function could be better I guess but I decided just to grab the four*/
/* components and store then seperately.  Makes it easier to use IMHO.       */
/* (is there an echo in here?)                                               */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void SetColor( GLcontext *ctx, GLubyte r, GLubyte g, GLubyte b, GLubyte a )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   pContext->aCurrent = a;
   pContext->bCurrent = b;
   pContext->gCurrent = g;
   pContext->rCurrent = r;
}
/*===========================================================================*/
/*                                                                           */
/*                                                                           */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static const char *RendererString( void )
{
  static char pszRender[64];

  strcpy( pszRender, "altD3D " );

  if ( pD3DCurrent->pShared->bHardware )
    strcat( pszRender, "(HW)");
  else
    strcat( pszRender, "(SW)");

  return (const char *)pszRender;
}
/*===========================================================================*/
/*  This function will choose which set of pointers Mesa will use based on   */
/* whether we hard using hardware or software.  I have added another set of  */
/* pointers that will do nothing but stop the API from crashing.             */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void SetupDDPointers( GLcontext *ctx )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   // TODO: write a generic NULL support for the span render. 
   if ( pContext->pShared && pContext->pShared->bHardware )
   {
	ctx->Driver.UpdateState = SetupHWDDPointers;
   }
   else if ( pContext == pD3DDefault )
   {
	ctx->Driver.UpdateState = SetupNULLDDPointers;
   }
   else
   {
	ctx->Driver.UpdateState = SetupSWDDPointers;
   }
}
/*===========================================================================*/
/*  This function will populate all the Mesa driver hooks. This version of   */
/* hooks will do nothing but support the API when we don't have a valid      */
/* context bound.  This is mostly for applications that don't behave right   */
/* and also to help exit as clean as possable when we have a FatalError.     */
/*===========================================================================*/
/* RETURN: pointer to the specific function.                                 */
/*===========================================================================*/
static void SetupNULLDDPointers( GLcontext *ctx )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   /* Initialize all the pointers in the DD struct.  Do this whenever */
   /* a new context is made current or we change buffers via set_buffer! */
   ctx->Driver.UpdateState          = SetupNULLDDPointers;

   /* State management hooks. */
   ctx->Driver.Color                = NULLSetColor;
   ctx->Driver.ClearColor           = NULLClearColor;
   ctx->Driver.Clear                = NULLClearBuffers;
   ctx->Driver.SetBuffer            = NULLSetBuffer;

   /* Window management hooks. */
   ctx->Driver.GetBufferSize        = NULLGetBufferSize;

   /* Primitive rendering hooks. */
   ctx->Driver.TriangleFunc         = NULL;
   ctx->Driver.RenderVB             = NULL;

   /* Pixel/span writing functions: */
   ctx->Driver.WriteRGBASpan        = NULLWrSpRGBA;
   ctx->Driver.WriteRGBSpan         = NULLWrSpRGB;
   ctx->Driver.WriteMonoRGBASpan    = NULLWrSpRGBAMono;
   ctx->Driver.WriteRGBAPixels      = NULLWrPiRGBA;
   ctx->Driver.WriteMonoRGBAPixels  = NULLWrPiRGBAMono;

   /* Pixel/span reading functions: */
   ctx->Driver.ReadRGBASpan         = NULLReSpRGBA;
   ctx->Driver.ReadRGBAPixels       = NULLRePiRGBA;

   /* Misc. hooks. */
   ctx->Driver.RendererString    = RendererString;
}
/*===========================================================================*/
/*  This function will populate all the Mesa driver hooks. There are two of  */
/* these functions.  One if we have hardware support and one is there is only*/
/* software.  These functions will be called by Mesa and by the wgl.c when we*/
/* have resized (or created) the buffers.  The thing is that if a window gets*/
/* resized we may loose hardware support or gain it...                       */
/*===========================================================================*/
/* RETURN: pointer to the specific function.                                 */
/*===========================================================================*/
static void SetupSWDDPointers( GLcontext *ctx )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   /* Initialize all the pointers in the DD struct.  Do this whenever */
   /* a new context is made current or we change buffers via set_buffer! */
   ctx->Driver.UpdateState          = SetupSWDDPointers;

   /* State management hooks. */
   ctx->Driver.Color                = SetColor;
   ctx->Driver.ClearColor           = ClearColor;
   ctx->Driver.Clear                = ClearBuffers;
   ctx->Driver.SetBuffer            = SetBuffer;

   /* Window management hooks. */
   ctx->Driver.GetBufferSize        = GetBufferSize;
   ctx->Driver.Viewport             = SetViewport;

   /* Primitive rendering hooks. */
   ctx->Driver.TriangleFunc         = NULL;
   ctx->Driver.RenderVB             = NULL;

   /* Texture management hooks. */

   /* Pixel/span writing functions: */
   ctx->Driver.WriteRGBASpan        = WSpanRGBA;
   ctx->Driver.WriteRGBSpan         = WSpanRGB;
   ctx->Driver.WriteMonoRGBASpan    = WSpanRGBAMono;
   ctx->Driver.WriteRGBAPixels      = WPixelsRGBA;
   ctx->Driver.WriteMonoRGBAPixels  = WPixelsRGBAMono;

   /* Pixel/span reading functions: */
   ctx->Driver.ReadRGBASpan         = RSpanRGBA;
   ctx->Driver.ReadRGBAPixels       = RPixelsRGBA;

   /* Misc. hooks. */
   ctx->Driver.Flush                = Flush;
   ctx->Driver.RendererString    = RendererString;
}
/*===========================================================================*/
/*  This function will populate all the Mesa driver hooks. There are two of  */
/* these functions.  One if we have hardware support and one is there is only*/
/* software.  These functions will be called by Mesa and by the wgl.c when we*/
/* have resized (or created) the buffers.  The thing is that if a window gets*/
/* resized we may loose hardware support or gain it...                       */
/*===========================================================================*/
/* RETURN: pointer to the specific function.                                 */
/*===========================================================================*/
static void SetupHWDDPointers( GLcontext *ctx )
{
   D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

   /* Initialize all the pointers in the DD struct.  Do this whenever */
   /* a new context is made current or we change buffers via set_buffer! */
   ctx->Driver.UpdateState          = SetupHWDDPointers;

   /* State management hooks. */
   ctx->Driver.Color                = SetColor;
   ctx->Driver.ClearColor           = ClearColor;
   ctx->Driver.Clear                = ClearBuffersD3D;
   ctx->Driver.SetBuffer            = SetBuffer;

   /* Window management hooks. */
   ctx->Driver.GetBufferSize        = GetBufferSize;
   ctx->Driver.Viewport             = SetViewport;

   /* Primitive rendering hooks. */
   ctx->Driver.TriangleFunc         = RenderOneTriangle;
   ctx->Driver.LineFunc                          = RenderOneLine;
   ctx->Driver.RenderVB             = RenderVertexBuffer;

   /* Pixel/span writing functions: */
   ctx->Driver.WriteRGBASpan        = WSpanRGBA;
   ctx->Driver.WriteRGBSpan         = WSpanRGB;
   ctx->Driver.WriteMonoRGBASpan    = WSpanRGBAMono;
   ctx->Driver.WriteRGBAPixels      = WPixelsRGBA;
   ctx->Driver.WriteMonoRGBAPixels  = WPixelsRGBAMono;

   /* Pixel/span reading functions: */
   ctx->Driver.ReadRGBASpan         = RSpanRGBA;
   ctx->Driver.ReadRGBAPixels       = RPixelsRGBA;

   /* Texture management hooks. */
   //   ctx->Driver.BindTexture          = TextureBind;
   ctx->Driver.TexImage             = TextureLoad;
   ctx->Driver.TexSubImage          = TextureSubImage;

   /* Misc. hooks. */
   ctx->Driver.Flush                = Flush;
   ctx->Driver.RendererString    = RendererString;
}
/*===========================================================================*/
/*  This function will release all resources used by the DLL.  Every context */
/* will be clobbered by releaseing all driver desources and then freeing the */
/* context memory.  Most all the work is done in DestroyContext.             */
/*===========================================================================*/
/* RETURN: TRUE.                                                             */
/*===========================================================================*/
static BOOL  TermOpenGL( HINSTANCE hInst )
{
  D3DMESACONTEXT *pTmp,
		 *pNext;

  /* Just incase we are still getting paint msg. */
  MakeCurrent( pD3DDefault );

  /* Walk the list until we get back to the default context. */
  for( pTmp = pD3DDefault->next; pTmp != pD3DDefault; pTmp = pNext )
  {
    pNext = pTmp->next;
    DestroyContext( pTmp );
  }
  DestroyContext( pD3DDefault );

  return TRUE;
}
/*===========================================================================*/
/*  This function is an internal function that will clean up all the Mesa    */
/* context bound to this D3D context.  Also any D3D stuff that this context  */
/* uses will be unloaded.                                                    */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
static void DestroyContext( D3DMESACONTEXT *pContext )
{
  D3DMESACONTEXT        *pTmp;

  /* Walk the list until we find the context before this one. */
  for( pTmp = pD3DDefault; pTmp && (pTmp->next != pContext); pTmp = pTmp->next )
    if ( pTmp == pTmp->next )
	 break;

  /* If we never found it it must already be deleted. */
  if ( pTmp->next != pContext )
    return;

  /* Make sure we are not using this context. */
  if ( pContext == pD3DCurrent )
    MakeCurrent( pD3DDefault );

   /* Free the Mesa stuff. */
   if ( pContext->gl_visual ) 
   {
      gl_destroy_visual( pContext->gl_visual );
      pContext->gl_visual = NULL;
   }
   if ( pContext->gl_buffer ) 
   {
      gl_destroy_framebuffer( pContext->gl_buffer );
      pContext->gl_buffer = NULL;
   }
   if ( pContext->gl_ctx )    
   {
      gl_destroy_context( pContext->gl_ctx );
      pContext->gl_ctx = NULL;
   }

   /* Now dump the D3D. */
   if ( pContext->pShared )
	TermHAL( pContext->pShared );

   /* Update the previous context's link. */
   pTmp->next = pContext->next;

   /* Gonzo. */
   FREE( pContext );
}
/*===========================================================================*/
/*  This function will pull the supplied context away from Win32.  Basicly it*/
/* will remove the hook from the window Proc.                                */
/*                                                                           */
/* TODO: might want to serialize this stuff...                               */
/*===========================================================================*/
/* RETURN: TRUE, FALSE.                                                      */
/*===========================================================================*/
static BOOL UnBindWindow( D3DMESACONTEXT *pContext )
{
  if ( pContext == NULL )
    return FALSE;

  if ( pContext == pD3DDefault )
    return TRUE;

  /* Make sure we always have a context bound. */
  if ( pContext == pD3DCurrent )
    pD3DCurrent = pD3DDefault;

  SetWindowLong( pContext->pShared->hwnd, GWL_WNDPROC, (LONG)pContext->hOldProc );
  pContext->hOldProc   = NULL;

  return TRUE;
}
/*===========================================================================*/
/*  There are two cases that allow for a faster clear when we know that the  */
/* whole buffer is cleared and that there is no clipping.                    */
/*===========================================================================*/
/* RETURN: the original mask with the bits cleared that represents the buffer*
/* or buffers we just cleared.                                               */
/*===========================================================================*/
GLbitfield ClearBuffersD3D( GLcontext *ctx, GLbitfield mask, GLboolean all, GLint x, GLint y, GLint width, GLint height )
{
  D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;
  DWORD          dwFlags = 0;

  if ( mask & GL_COLOR_BUFFER_BIT )
  {
    dwFlags |= D3DCLEAR_TARGET;
    mask &= ~GL_COLOR_BUFFER_BIT;
  }
  if ( mask & GL_DEPTH_BUFFER_BIT )
  {
    dwFlags |= D3DCLEAR_ZBUFFER;
    mask &= ~GL_DEPTH_BUFFER_BIT;
  }
  if ( dwFlags == 0 )
    return mask;

  ClearHAL( pContext->pShared, 
		  dwFlags, 
		  all, 
		  x, y, 
		  width, height, 
		  ((pContext->aClear<<24) | (pContext->rClear<<16) | (pContext->gClear<<8) | (pContext->bClear)), 
		  ctx->Depth.Clear, 
		  0 );

  return mask;
}



/*===========================================================================*/
/*  TEXTURE MANAGER: ok here is how I did textures.  Mesa-3.0 will keep track*/
/* of all the textures for us.  So this means that at anytime we can go to   */
/* the Mesa context and get the current texture.  With this in mind this is  */
/* what I did.  I really don't care about what textures get or are loaded    */
/* until I actually have to draw a tri that is textured.  At this point I    */
/* must have the texture so I demand the texture by destorying all other     */
/* texture surfaces if need be and load the current one.  This allows for the*/
/* best preformance on low memory cards as time is not wasted loading and    */
/* unload textures.                                                          */
/*===========================================================================*/





/*===========================================================================*/
/*  TextureLoad will try and create a D3D surface from the supplied texture  */
/* object if its level 0 (first).  The surface will be fully filled with the */
/* texture.                                                                  */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void TextureLoad( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj, GLint level, GLint internalFormat, const struct gl_texture_image *image )
{
  D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

  /* TODO: only doing first LOD. */
  if ( (ctx->DriverCtx == NULL) || (level != 0) )
    return;

  CreateTMgrHAL( pContext->pShared, 
			  tObj->Name, 
			  level,
			  tObj->Image[level]->Format,
			  (RECT *)NULL,
			  tObj->Image[level]->Width, 
			  tObj->Image[level]->Height,
			  TM_ACTION_LOAD,
			  (void *)tObj->Image[level]->Data );
}
/*===========================================================================*/
/*  TextureBind make sure that the texture is on the card.  Thats it.        */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void TextureBind( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj )
{
  D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;

  /* TODO: only doing first LOD. */
  if ( (tObj->Image[0] == NULL) || (ctx->DriverCtx == NULL) )
    return;

  CreateTMgrHAL( pContext->pShared, 
			  tObj->Name, 
			  0,
			  tObj->Image[0]->Format,
			  (RECT *)NULL,
			  tObj->Image[0]->Width, 
			  tObj->Image[0]->Height,
			  TM_ACTION_BIND,
			  (void *)tObj->Image[0]->Data );
}
/*===========================================================================*/
/*  TextureSubImage will make sure that the texture being updated is updated */
/* if its on the card.                                                       */
/*===========================================================================*/
/* RETURN:                                                                   */
/*===========================================================================*/
static void TextureSubImage( GLcontext *ctx, GLenum target, struct gl_texture_object *tObj, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLint internalFormat, const struct gl_texture_image *image )
{
  D3DMESACONTEXT *pContext = (D3DMESACONTEXT *)ctx->DriverCtx;
  RECT           rect;

  /* TODO: only doing first LOD. */
  if ( (ctx->DriverCtx == NULL) || (level > 0) )
    return;

  /* Create a dirty rectangle structure. */
  rect.left   = xoffset;
  rect.right  = xoffset + width;
  rect.top    = yoffset;
  rect.bottom = yoffset + height;
  
  CreateTMgrHAL( pContext->pShared, 
			  tObj->Name, 
			  0,
			  tObj->Image[0]->Format, 
			  &rect,
			  tObj->Image[0]->Width, 
			  tObj->Image[0]->Height,
			  TM_ACTION_UPDATE,
			  (void *)tObj->Image[0]->Data );
}