aboutsummaryrefslogtreecommitdiffstats
path: root/src/mesa/main/matrix.c
blob: 7339b0ce4092a4b0d3c7883557a09afb3af523b3 (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
/*
 * Mesa 3-D graphics library
 * Version:  6.3
 *
 * Copyright (C) 1999-2005  Brian Paul   All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */


/**
 * \file matrix.c
 * Matrix operations.
 *
 * \note
 * -# 4x4 transformation matrices are stored in memory in column major order.
 * -# Points/vertices are to be thought of as column vectors.
 * -# Transformation of a point p by a matrix M is: p' = M * p
 */


#include "glheader.h"
#include "imports.h"
#include "context.h"
#include "enums.h"
#include "macros.h"
#include "matrix.h"
#include "mtypes.h"
#include "math/m_matrix.h"
#include "math/m_xform.h"


/**
 * Apply a perspective projection matrix.
 *
 * \param left left clipping plane coordinate.
 * \param right right clipping plane coordinate.
 * \param bottom bottom clipping plane coordinate.
 * \param top top clipping plane coordinate.
 * \param nearval distance to the near clipping plane.
 * \param farval distance to the far clipping plane.
 *
 * \sa glFrustum().
 *
 * Flushes vertices and validates parameters. Calls _math_matrix_frustum() with
 * the top matrix of the current matrix stack and sets
 * __GLcontextRec::NewState.
 */
void GLAPIENTRY
_mesa_Frustum( GLdouble left, GLdouble right,
               GLdouble bottom, GLdouble top,
               GLdouble nearval, GLdouble farval )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);

   if (nearval <= 0.0 ||
       farval <= 0.0 ||
       nearval == farval ||
       left == right ||
       top == bottom)
   {
      _mesa_error( ctx,  GL_INVALID_VALUE, "glFrustum" );
      return;
   }

   _math_matrix_frustum( ctx->CurrentStack->Top,
                         (GLfloat) left, (GLfloat) right, 
			 (GLfloat) bottom, (GLfloat) top, 
			 (GLfloat) nearval, (GLfloat) farval );
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Apply an orthographic projection matrix.
 *
 * \param left left clipping plane coordinate.
 * \param right right clipping plane coordinate.
 * \param bottom bottom clipping plane coordinate.
 * \param top top clipping plane coordinate.
 * \param nearval distance to the near clipping plane.
 * \param farval distance to the far clipping plane.
 *
 * \sa glOrtho().
 *
 * Flushes vertices and validates parameters. Calls _math_matrix_ortho() with
 * the top matrix of the current matrix stack and sets
 * __GLcontextRec::NewState.
 */
void GLAPIENTRY
_mesa_Ortho( GLdouble left, GLdouble right,
             GLdouble bottom, GLdouble top,
             GLdouble nearval, GLdouble farval )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glOrtho(%f, %f, %f, %f, %f, %f)\n",
                  left, right, bottom, top, nearval, farval);

   if (left == right ||
       bottom == top ||
       nearval == farval)
   {
      _mesa_error( ctx,  GL_INVALID_VALUE, "glOrtho" );
      return;
   }

   _math_matrix_ortho( ctx->CurrentStack->Top,
                       (GLfloat) left, (GLfloat) right, 
		       (GLfloat) bottom, (GLfloat) top, 
		       (GLfloat) nearval, (GLfloat) farval );
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Set the current matrix stack.
 *
 * \param mode matrix stack.
 *
 * \sa glMatrixMode().
 *
 * Flushes the vertices, validates the parameter and updates
 * __GLcontextRec::CurrentStack and gl_transform_attrib::MatrixMode with the
 * specified matrix stack.
 */
void GLAPIENTRY
_mesa_MatrixMode( GLenum mode )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END(ctx);

   if (ctx->Transform.MatrixMode == mode && mode != GL_TEXTURE)
      return;
   FLUSH_VERTICES(ctx, _NEW_TRANSFORM);

   switch (mode) {
   case GL_MODELVIEW:
      ctx->CurrentStack = &ctx->ModelviewMatrixStack;
      break;
   case GL_PROJECTION:
      ctx->CurrentStack = &ctx->ProjectionMatrixStack;
      break;
   case GL_TEXTURE:
      if (ctx->Texture.CurrentUnit >= ctx->Const.MaxTextureCoordUnits) {
         _mesa_error(ctx, GL_INVALID_OPERATION, "glMatrixMode(texcoord unit)");
         return;
      }
      ctx->CurrentStack = &ctx->TextureMatrixStack[ctx->Texture.CurrentUnit];
      break;
   case GL_COLOR:
      ctx->CurrentStack = &ctx->ColorMatrixStack;
      break;
   case GL_MATRIX0_NV:
   case GL_MATRIX1_NV:
   case GL_MATRIX2_NV:
   case GL_MATRIX3_NV:
   case GL_MATRIX4_NV:
   case GL_MATRIX5_NV:
   case GL_MATRIX6_NV:
   case GL_MATRIX7_NV:
      if (ctx->Extensions.NV_vertex_program) {
         ctx->CurrentStack = &ctx->ProgramMatrixStack[mode - GL_MATRIX0_NV];
      }
      else {
         _mesa_error( ctx,  GL_INVALID_ENUM, "glMatrixMode(mode)" );
         return;
      }
      break;
   case GL_MATRIX0_ARB:
   case GL_MATRIX1_ARB:
   case GL_MATRIX2_ARB:
   case GL_MATRIX3_ARB:
   case GL_MATRIX4_ARB:
   case GL_MATRIX5_ARB:
   case GL_MATRIX6_ARB:
   case GL_MATRIX7_ARB:
      if (ctx->Extensions.ARB_vertex_program ||
          ctx->Extensions.ARB_fragment_program) {
         const GLuint m = mode - GL_MATRIX0_ARB;
         if (m > ctx->Const.MaxProgramMatrices) {
            _mesa_error(ctx, GL_INVALID_ENUM,
                        "glMatrixMode(GL_MATRIX%d_ARB)", m);
            return;
         }
         ctx->CurrentStack = &ctx->ProgramMatrixStack[m];
      }
      else {
         _mesa_error( ctx,  GL_INVALID_ENUM, "glMatrixMode(mode)" );
         return;
      }
      break;
   default:
      _mesa_error( ctx,  GL_INVALID_ENUM, "glMatrixMode(mode)" );
      return;
   }

   ctx->Transform.MatrixMode = mode;
}


/**
 * Push the current matrix stack.
 *
 * \sa glPushMatrix().
 * 
 * Verifies the current matrix stack is not full, and duplicates the top-most
 * matrix in the stack. Marks __GLcontextRec::NewState with the stack dirty
 * flag.
 */
void GLAPIENTRY
_mesa_PushMatrix( void )
{
   GET_CURRENT_CONTEXT(ctx);
   struct matrix_stack *stack = ctx->CurrentStack;
   ASSERT_OUTSIDE_BEGIN_END(ctx);

   if (MESA_VERBOSE&VERBOSE_API)
      _mesa_debug(ctx, "glPushMatrix %s\n",
                  _mesa_lookup_enum_by_nr(ctx->Transform.MatrixMode));

   if (stack->Depth + 1 >= stack->MaxDepth) {
      if (ctx->Transform.MatrixMode == GL_TEXTURE) {
         _mesa_error(ctx,  GL_STACK_OVERFLOW,
                     "glPushMatrix(mode=GL_TEXTURE, unit=%d)",
                      ctx->Texture.CurrentUnit);
      }
      else {
         _mesa_error(ctx,  GL_STACK_OVERFLOW, "glPushMatrix(mode=%s)",
                     _mesa_lookup_enum_by_nr(ctx->Transform.MatrixMode));
      }
      return;
   }
   _math_matrix_copy( &stack->Stack[stack->Depth + 1],
                      &stack->Stack[stack->Depth] );
   stack->Depth++;
   stack->Top = &(stack->Stack[stack->Depth]);
   ctx->NewState |= stack->DirtyFlag;
}


/**
 * Pop the current matrix stack.
 *
 * \sa glPopMatrix().
 * 
 * Flushes the vertices, verifies the current matrix stack is not empty, and
 * moves the stack head down. Marks __GLcontextRec::NewState with the dirty
 * stack flag.
 */
void GLAPIENTRY
_mesa_PopMatrix( void )
{
   GET_CURRENT_CONTEXT(ctx);
   struct matrix_stack *stack = ctx->CurrentStack;
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);

   if (MESA_VERBOSE&VERBOSE_API)
      _mesa_debug(ctx, "glPopMatrix %s\n",
                  _mesa_lookup_enum_by_nr(ctx->Transform.MatrixMode));

   if (stack->Depth == 0) {
      if (ctx->Transform.MatrixMode == GL_TEXTURE) {
         _mesa_error(ctx,  GL_STACK_UNDERFLOW,
                     "glPopMatrix(mode=GL_TEXTURE, unit=%d)",
                      ctx->Texture.CurrentUnit);
      }
      else {
         _mesa_error(ctx,  GL_STACK_UNDERFLOW, "glPopMatrix(mode=%s)",
                     _mesa_lookup_enum_by_nr(ctx->Transform.MatrixMode));
      }
      return;
   }
   stack->Depth--;
   stack->Top = &(stack->Stack[stack->Depth]);
   ctx->NewState |= stack->DirtyFlag;
}


/**
 * Replace the current matrix with the identity matrix.
 *
 * \sa glLoadIdentity().
 *
 * Flushes the vertices and calls _math_matrix_set_identity() with the top-most
 * matrix in the current stack. Marks __GLcontextRec::NewState with the stack
 * dirty flag.
 */
void GLAPIENTRY
_mesa_LoadIdentity( void )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);

   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glLoadIdentity()");

   _math_matrix_set_identity( ctx->CurrentStack->Top );
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Replace the current matrix with a given matrix.
 *
 * \param m matrix.
 *
 * \sa glLoadMatrixf().
 *
 * Flushes the vertices and calls _math_matrix_loadf() with the top-most matrix
 * in the current stack and the given matrix. Marks __GLcontextRec::NewState
 * with the dirty stack flag.
 */
void GLAPIENTRY
_mesa_LoadMatrixf( const GLfloat *m )
{
   GET_CURRENT_CONTEXT(ctx);
   if (!m) return;
   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx,
          "glLoadMatrix(%f %f %f %f, %f %f %f %f, %f %f %f %f, %f %f %f %f\n",
          m[0], m[4], m[8], m[12],
          m[1], m[5], m[9], m[13],
          m[2], m[6], m[10], m[14],
          m[3], m[7], m[11], m[15]);

   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   _math_matrix_loadf( ctx->CurrentStack->Top, m );
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Multiply the current matrix with a given matrix.
 *
 * \param m matrix.
 *
 * \sa glMultMatrixf().
 *
 * Flushes the vertices and calls _math_matrix_mul_floats() with the top-most
 * matrix in the current stack and the given matrix. Marks
 * __GLcontextRec::NewState with the dirty stack flag.
 */
void GLAPIENTRY
_mesa_MultMatrixf( const GLfloat *m )
{
   GET_CURRENT_CONTEXT(ctx);
   if (!m) return;
   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx,
          "glMultMatrix(%f %f %f %f, %f %f %f %f, %f %f %f %f, %f %f %f %f\n",
          m[0], m[4], m[8], m[12],
          m[1], m[5], m[9], m[13],
          m[2], m[6], m[10], m[14],
          m[3], m[7], m[11], m[15]);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   _math_matrix_mul_floats( ctx->CurrentStack->Top, m );
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Multiply the current matrix with a rotation matrix.
 *
 * \param angle angle of rotation, in degrees.
 * \param x rotation vector x coordinate.
 * \param y rotation vector y coordinate.
 * \param z rotation vector z coordinate.
 *
 * \sa glRotatef().
 *
 * Flushes the vertices and calls _math_matrix_rotate() with the top-most
 * matrix in the current stack and the given parameters. Marks
 * __GLcontextRec::NewState with the dirty stack flag.
 */
void GLAPIENTRY
_mesa_Rotatef( GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   if (angle != 0.0F) {
      _math_matrix_rotate( ctx->CurrentStack->Top, angle, x, y, z);
      ctx->NewState |= ctx->CurrentStack->DirtyFlag;
   }
}


/**
 * Multiply the current matrix with a general scaling matrix.
 *
 * \param x x axis scale factor.
 * \param y y axis scale factor.
 * \param z z axis scale factor.
 *
 * \sa glScalef().
 *
 * Flushes the vertices and calls _math_matrix_scale() with the top-most
 * matrix in the current stack and the given parameters. Marks
 * __GLcontextRec::NewState with the dirty stack flag.
 */
void GLAPIENTRY
_mesa_Scalef( GLfloat x, GLfloat y, GLfloat z )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   _math_matrix_scale( ctx->CurrentStack->Top, x, y, z);
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}


/**
 * Multiply the current matrix with a general scaling matrix.
 *
 * \param x translation vector x coordinate.
 * \param y translation vector y coordinate.
 * \param z translation vector z coordinate.
 *
 * \sa glTranslatef().
 *
 * Flushes the vertices and calls _math_matrix_translate() with the top-most
 * matrix in the current stack and the given parameters. Marks
 * __GLcontextRec::NewState with the dirty stack flag.
 */
void GLAPIENTRY
_mesa_Translatef( GLfloat x, GLfloat y, GLfloat z )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   _math_matrix_translate( ctx->CurrentStack->Top, x, y, z);
   ctx->NewState |= ctx->CurrentStack->DirtyFlag;
}

 
#if _HAVE_FULL_GL
void GLAPIENTRY
_mesa_LoadMatrixd( const GLdouble *m )
{
   GLint i;
   GLfloat f[16];
   if (!m) return;
   for (i = 0; i < 16; i++)
      f[i] = (GLfloat) m[i];
   _mesa_LoadMatrixf(f);
}

void GLAPIENTRY
_mesa_MultMatrixd( const GLdouble *m )
{
   GLint i;
   GLfloat f[16];
   if (!m) return;
   for (i = 0; i < 16; i++)
      f[i] = (GLfloat) m[i];
   _mesa_MultMatrixf( f );
}


void GLAPIENTRY
_mesa_Rotated( GLdouble angle, GLdouble x, GLdouble y, GLdouble z )
{
   _mesa_Rotatef((GLfloat) angle, (GLfloat) x, (GLfloat) y, (GLfloat) z);
}


void GLAPIENTRY
_mesa_Scaled( GLdouble x, GLdouble y, GLdouble z )
{
   _mesa_Scalef((GLfloat) x, (GLfloat) y, (GLfloat) z);
}


void GLAPIENTRY
_mesa_Translated( GLdouble x, GLdouble y, GLdouble z )
{
   _mesa_Translatef((GLfloat) x, (GLfloat) y, (GLfloat) z);
}
#endif


#if _HAVE_FULL_GL
void GLAPIENTRY
_mesa_LoadTransposeMatrixfARB( const GLfloat *m )
{
   GLfloat tm[16];
   if (!m) return;
   _math_transposef(tm, m);
   _mesa_LoadMatrixf(tm);
}


void GLAPIENTRY
_mesa_LoadTransposeMatrixdARB( const GLdouble *m )
{
   GLfloat tm[16];
   if (!m) return;
   _math_transposefd(tm, m);
   _mesa_LoadMatrixf(tm);
}


void GLAPIENTRY
_mesa_MultTransposeMatrixfARB( const GLfloat *m )
{
   GLfloat tm[16];
   if (!m) return;
   _math_transposef(tm, m);
   _mesa_MultMatrixf(tm);
}


void GLAPIENTRY
_mesa_MultTransposeMatrixdARB( const GLdouble *m )
{
   GLfloat tm[16];
   if (!m) return;
   _math_transposefd(tm, m);
   _mesa_MultMatrixf(tm);
}
#endif

/**
 * Set the viewport.
 * 
 * \param x, y coordinates of the lower-left corner of the viewport rectangle.
 * \param width width of the viewport rectangle.
 * \param height height of the viewport rectangle.
 *
 * \sa Called via glViewport() or display list execution.
 *
 * Flushes the vertices and calls _mesa_set_viewport() with the given
 * parameters.
 */
void GLAPIENTRY
_mesa_Viewport( GLint x, GLint y, GLsizei width, GLsizei height )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
   _mesa_set_viewport(ctx, x, y, width, height);
}


/**
 * Set new viewport parameters and update derived state (the _WindowMap
 * matrix).  Usually called from _mesa_Viewport().
 * 
 * \param ctx GL context.
 * \param x, y coordinates of the lower left corner of the viewport rectangle.
 * \param width width of the viewport rectangle.
 * \param height height of the viewport rectangle.
 */
void
_mesa_set_viewport( GLcontext *ctx, GLint x, GLint y,
                    GLsizei width, GLsizei height )
{
   if (MESA_VERBOSE & VERBOSE_API)
      _mesa_debug(ctx, "glViewport %d %d %d %d\n", x, y, width, height);

   if (width < 0 || height < 0) {
      _mesa_error( ctx,  GL_INVALID_VALUE,
                   "glViewport(%d, %d, %d, %d)", x, y, width, height );
      return;
   }

   /* clamp width and height to the implementation dependent range */
   width  = CLAMP(width,  1, (GLsizei) ctx->Const.MaxViewportWidth);
   height = CLAMP(height, 1, (GLsizei) ctx->Const.MaxViewportHeight);

   ctx->Viewport.X = x;
   ctx->Viewport.Width = width;
   ctx->Viewport.Y = y;
   ctx->Viewport.Height = height;
   ctx->NewState |= _NEW_VIEWPORT;

#if 1
   /* XXX remove this someday.  Currently the DRI drivers rely on
    * the WindowMap matrix being up to date in the driver's Viewport
    * and DepthRange functions.
    */
   _math_matrix_viewport(&ctx->Viewport._WindowMap,
                         ctx->Viewport.X, ctx->Viewport.Y,
                         ctx->Viewport.Width, ctx->Viewport.Height,
                         ctx->Viewport.Near, ctx->Viewport.Far,
                         ctx->DrawBuffer->_DepthMaxF);
#endif

   if (ctx->Driver.Viewport) {
      /* Many drivers will use this call to check for window size changes
       * and reallocate the z/stencil/accum/etc buffers if needed.
       */
      (*ctx->Driver.Viewport)( ctx, x, y, width, height );
   }
}


#if _HAVE_FULL_GL
/**
 * Called by glDepthRange
 *
 * \param nearval  specifies the Z buffer value which should correspond to
 *                 the near clip plane
 * \param farval  specifies the Z buffer value which should correspond to
 *                the far clip plane
 */
void GLAPIENTRY
_mesa_DepthRange( GLclampd nearval, GLclampd farval )
{
   GET_CURRENT_CONTEXT(ctx);
   ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);

   if (MESA_VERBOSE&VERBOSE_API)
      _mesa_debug(ctx, "glDepthRange %f %f\n", nearval, farval);

   ctx->Viewport.Near = (GLfloat) CLAMP( nearval, 0.0, 1.0 );
   ctx->Viewport.Far = (GLfloat) CLAMP( farval, 0.0, 1.0 );
   ctx->NewState |= _NEW_VIEWPORT;

#if 1
   /* XXX remove this someday.  Currently the DRI drivers rely on
    * the WindowMap matrix being up to date in the driver's Viewport
    * and DepthRange functions.
    */
   _math_matrix_viewport(&ctx->Viewport._WindowMap,
                         ctx->Viewport.X, ctx->Viewport.Y,
                         ctx->Viewport.Width, ctx->Viewport.Height,
                         ctx->Viewport.Near, ctx->Viewport.Far,
                         ctx->DrawBuffer->_DepthMaxF);
#endif

   if (ctx->Driver.DepthRange) {
      (*ctx->Driver.DepthRange)( ctx, nearval, farval );
   }
}
#endif



/**********************************************************************/
/** \name State management */
/*@{*/


/**
 * Update the projection matrix stack.
 *
 * \param ctx GL context.
 *
 * Calls _math_matrix_analyse() with the top-matrix of the projection matrix
 * stack, and recomputes user clip positions if necessary.
 * 
 * \note This routine references __GLcontextRec::Tranform attribute values to
 * compute userclip positions in clip space, but is only called on
 * _NEW_PROJECTION.  The _mesa_ClipPlane() function keeps these values up to
 * date across changes to the __GLcontextRec::Transform attributes.
 */
static void
update_projection( GLcontext *ctx )
{
   _math_matrix_analyse( ctx->ProjectionMatrixStack.Top );

#if FEATURE_userclip
   /* Recompute clip plane positions in clipspace.  This is also done
    * in _mesa_ClipPlane().
    */
   if (ctx->Transform.ClipPlanesEnabled) {
      GLuint p;
      for (p = 0; p < ctx->Const.MaxClipPlanes; p++) {
	 if (ctx->Transform.ClipPlanesEnabled & (1 << p)) {
	    _mesa_transform_vector( ctx->Transform._ClipUserPlane[p],
				 ctx->Transform.EyeUserPlane[p],
				 ctx->ProjectionMatrixStack.Top->inv );
	 }
      }
   }
#endif
}


/**
 * Calculate the combined modelview-projection matrix.
 *
 * \param ctx GL context.
 *
 * Multiplies the top matrices of the projection and model view stacks into
 * __GLcontextRec::_ModelProjectMatrix via _math_matrix_mul_matrix() and
 * analyzes the resulting matrix via _math_matrix_analyse().
 */
static void
calculate_model_project_matrix( GLcontext *ctx )
{
   _math_matrix_mul_matrix( &ctx->_ModelProjectMatrix,
                            ctx->ProjectionMatrixStack.Top,
                            ctx->ModelviewMatrixStack.Top );

   _math_matrix_analyse( &ctx->_ModelProjectMatrix );
}


/**
 * Updates the combined modelview-projection matrix.
 *
 * \param ctx GL context.
 * \param new_state new state bit mask.
 *
 * If there is a new model view matrix then analyzes it. If there is a new
 * projection matrix, updates it. Finally calls
 * calculate_model_project_matrix() to recalculate the modelview-projection
 * matrix.
 */
void _mesa_update_modelview_project( GLcontext *ctx, GLuint new_state )
{
   if (new_state & _NEW_MODELVIEW) {
      _math_matrix_analyse( ctx->ModelviewMatrixStack.Top );
    
      /* Bring cull position uptodate.
       */
      TRANSFORM_POINT3( ctx->Transform.CullObjPos, 
			ctx->ModelviewMatrixStack.Top->inv,
			ctx->Transform.CullEyePos );
   }


   if (new_state & _NEW_PROJECTION)
      update_projection( ctx );

   /* Keep ModelviewProject uptodate always to allow tnl
    * implementations that go model->clip even when eye is required.
    */
   calculate_model_project_matrix(ctx);
}

/*@}*/


/**********************************************************************/
/** Matrix stack initialization */
/*@{*/


/**
 * Initialize a matrix stack.
 *
 * \param stack matrix stack.
 * \param maxDepth maximum stack depth.
 * \param dirtyFlag dirty flag.
 * 
 * Allocates an array of \p maxDepth elements for the matrix stack and calls
 * _math_matrix_ctr() and _math_matrix_alloc_inv() for each element to
 * initialize it.
 */
static void
init_matrix_stack( struct matrix_stack *stack,
                   GLuint maxDepth, GLuint dirtyFlag )
{
   GLuint i;

   stack->Depth = 0;
   stack->MaxDepth = maxDepth;
   stack->DirtyFlag = dirtyFlag;
   /* The stack */
   stack->Stack = (GLmatrix *) CALLOC(maxDepth * sizeof(GLmatrix));
   for (i = 0; i < maxDepth; i++) {
      _math_matrix_ctr(&stack->Stack[i]);
      _math_matrix_alloc_inv(&stack->Stack[i]);
   }
   stack->Top = stack->Stack;
}

/**
 * Free matrix stack.
 * 
 * \param stack matrix stack.
 * 
 * Calls _math_matrix_dtr() for each element of the matrix stack and
 * frees the array.
 */
static void
free_matrix_stack( struct matrix_stack *stack )
{
   GLuint i;
   for (i = 0; i < stack->MaxDepth; i++) {
      _math_matrix_dtr(&stack->Stack[i]);
   }
   FREE(stack->Stack);
   stack->Stack = stack->Top = NULL;
}

/*@}*/


/**********************************************************************/
/** \name Initialization */
/*@{*/


/**
 * Initialize the context matrix data.
 *
 * \param ctx GL context.
 *
 * Initializes each of the matrix stacks and the combined modelview-projection
 * matrix.
 */
void _mesa_init_matrix( GLcontext * ctx )
{
   GLint i;

   /* Initialize matrix stacks */
   init_matrix_stack(&ctx->ModelviewMatrixStack, MAX_MODELVIEW_STACK_DEPTH,
                     _NEW_MODELVIEW);
   init_matrix_stack(&ctx->ProjectionMatrixStack, MAX_PROJECTION_STACK_DEPTH,
                     _NEW_PROJECTION);
   init_matrix_stack(&ctx->ColorMatrixStack, MAX_COLOR_STACK_DEPTH,
                     _NEW_COLOR_MATRIX);
   for (i = 0; i < MAX_TEXTURE_UNITS; i++)
      init_matrix_stack(&ctx->TextureMatrixStack[i], MAX_TEXTURE_STACK_DEPTH,
                        _NEW_TEXTURE_MATRIX);
   for (i = 0; i < MAX_PROGRAM_MATRICES; i++)
      init_matrix_stack(&ctx->ProgramMatrixStack[i], 
		        MAX_PROGRAM_MATRIX_STACK_DEPTH, _NEW_TRACK_MATRIX);
   ctx->CurrentStack = &ctx->ModelviewMatrixStack;

   /* Init combined Modelview*Projection matrix */
   _math_matrix_ctr( &ctx->_ModelProjectMatrix );
}


/**
 * Free the context matrix data.
 * 
 * \param ctx GL context.
 *
 * Frees each of the matrix stacks and the combined modelview-projection
 * matrix.
 */
void _mesa_free_matrix_data( GLcontext *ctx )
{
   GLint i;

   free_matrix_stack(&ctx->ModelviewMatrixStack);
   free_matrix_stack(&ctx->ProjectionMatrixStack);
   free_matrix_stack(&ctx->ColorMatrixStack);
   for (i = 0; i < MAX_TEXTURE_UNITS; i++)
      free_matrix_stack(&ctx->TextureMatrixStack[i]);
   for (i = 0; i < MAX_PROGRAM_MATRICES; i++)
      free_matrix_stack(&ctx->ProgramMatrixStack[i]);
   /* combined Modelview*Projection matrix */
   _math_matrix_dtr( &ctx->_ModelProjectMatrix );

}


/** 
 * Initialize the context transform attribute group.
 *
 * \param ctx GL context.
 *
 * \todo Move this to a new file with other 'transform' routines.
 */
void _mesa_init_transform( GLcontext *ctx )
{
   GLint i;

   /* Transformation group */
   ctx->Transform.MatrixMode = GL_MODELVIEW;
   ctx->Transform.Normalize = GL_FALSE;
   ctx->Transform.RescaleNormals = GL_FALSE;
   ctx->Transform.RasterPositionUnclipped = GL_FALSE;
   for (i=0;i<MAX_CLIP_PLANES;i++) {
      ASSIGN_4V( ctx->Transform.EyeUserPlane[i], 0.0, 0.0, 0.0, 0.0 );
   }
   ctx->Transform.ClipPlanesEnabled = 0;

   ASSIGN_4V( ctx->Transform.CullObjPos, 0.0, 0.0, 1.0, 0.0 );
   ASSIGN_4V( ctx->Transform.CullEyePos, 0.0, 0.0, 1.0, 0.0 );
}


/** 
 * Initialize the context viewport attribute group.
 *
 * \param ctx GL context.
 * 
 * \todo Move this to a new file with other 'viewport' routines.
 */
void _mesa_init_viewport( GLcontext *ctx )
{
   GLfloat depthMax = 65535.0F; /* sorf of arbitrary */

   /* Viewport group */
   ctx->Viewport.X = 0;
   ctx->Viewport.Y = 0;
   ctx->Viewport.Width = 0;
   ctx->Viewport.Height = 0;
   ctx->Viewport.Near = 0.0;
   ctx->Viewport.Far = 1.0;
   _math_matrix_ctr(&ctx->Viewport._WindowMap);

   _math_matrix_viewport(&ctx->Viewport._WindowMap, 0, 0, 0, 0,
                         0.0F, 1.0F, depthMax);
}


/** 
 * Free the context viewport attribute group data.
 *
 * \param ctx GL context.
 * 
 * \todo Move this to a new file with other 'viewport' routines.
 */
void _mesa_free_viewport_data( GLcontext *ctx )
{
   _math_matrix_dtr(&ctx->Viewport._WindowMap);
}

/*@}*/
lass="hl opt">->DefaultVertexProgram = ctx->Driver.NewProgram(ctx, GL_VERTEX_PROGRAM_ARB, 0); if (!ss->DefaultVertexProgram) goto cleanup; #endif #if FEATURE_ARB_fragment_program ss->DefaultFragmentProgram = ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0); if (!ss->DefaultFragmentProgram) goto cleanup; #endif #if FEATURE_ATI_fragment_shader ss->ATIShaders = _mesa_NewHashTable(); ss->DefaultFragmentShader = _mesa_new_ati_fragment_shader(ctx, 0); if (!ss->DefaultFragmentShader) goto cleanup; #endif #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object ss->BufferObjects = _mesa_NewHashTable(); #endif ss->ArrayObjects = _mesa_NewHashTable(); #if FEATURE_ARB_shader_objects ss->GL2Objects = _mesa_NewHashTable (); #endif ss->Default1D = (*ctx->Driver.NewTextureObject)(ctx, 0, GL_TEXTURE_1D); if (!ss->Default1D) goto cleanup; ss->Default2D = (*ctx->Driver.NewTextureObject)(ctx, 0, GL_TEXTURE_2D); if (!ss->Default2D) goto cleanup; ss->Default3D = (*ctx->Driver.NewTextureObject)(ctx, 0, GL_TEXTURE_3D); if (!ss->Default3D) goto cleanup; ss->DefaultCubeMap = (*ctx->Driver.NewTextureObject)(ctx, 0, GL_TEXTURE_CUBE_MAP_ARB); if (!ss->DefaultCubeMap) goto cleanup; ss->DefaultRect = (*ctx->Driver.NewTextureObject)(ctx, 0, GL_TEXTURE_RECTANGLE_NV); if (!ss->DefaultRect) goto cleanup; /* Effectively bind the default textures to all texture units */ ss->Default1D->RefCount += MAX_TEXTURE_IMAGE_UNITS; ss->Default2D->RefCount += MAX_TEXTURE_IMAGE_UNITS; ss->Default3D->RefCount += MAX_TEXTURE_IMAGE_UNITS; ss->DefaultCubeMap->RefCount += MAX_TEXTURE_IMAGE_UNITS; ss->DefaultRect->RefCount += MAX_TEXTURE_IMAGE_UNITS; #if FEATURE_EXT_framebuffer_object ss->FrameBuffers = _mesa_NewHashTable(); if (!ss->FrameBuffers) goto cleanup; ss->RenderBuffers = _mesa_NewHashTable(); if (!ss->RenderBuffers) goto cleanup; #endif return GL_TRUE; cleanup: /* Ran out of memory at some point. Free everything and return NULL */ if (ss->DisplayList) _mesa_DeleteHashTable(ss->DisplayList); if (ss->TexObjects) _mesa_DeleteHashTable(ss->TexObjects); #if FEATURE_NV_vertex_program if (ss->Programs) _mesa_DeleteHashTable(ss->Programs); #endif #if FEATURE_ARB_vertex_program if (ss->DefaultVertexProgram) ctx->Driver.DeleteProgram(ctx, ss->DefaultVertexProgram); #endif #if FEATURE_ARB_fragment_program if (ss->DefaultFragmentProgram) ctx->Driver.DeleteProgram(ctx, ss->DefaultFragmentProgram); #endif #if FEATURE_ATI_fragment_shader if (ss->DefaultFragmentShader) _mesa_delete_ati_fragment_shader(ctx, ss->DefaultFragmentShader); #endif #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object if (ss->BufferObjects) _mesa_DeleteHashTable(ss->BufferObjects); #endif if (ss->ArrayObjects) _mesa_DeleteHashTable (ss->ArrayObjects); #if FEATURE_ARB_shader_objects if (ss->GL2Objects) _mesa_DeleteHashTable (ss->GL2Objects); #endif #if FEATURE_EXT_framebuffer_object if (ss->FrameBuffers) _mesa_DeleteHashTable(ss->FrameBuffers); if (ss->RenderBuffers) _mesa_DeleteHashTable(ss->RenderBuffers); #endif if (ss->Default1D) (*ctx->Driver.DeleteTexture)(ctx, ss->Default1D); if (ss->Default2D) (*ctx->Driver.DeleteTexture)(ctx, ss->Default2D); if (ss->Default3D) (*ctx->Driver.DeleteTexture)(ctx, ss->Default3D); if (ss->DefaultCubeMap) (*ctx->Driver.DeleteTexture)(ctx, ss->DefaultCubeMap); if (ss->DefaultRect) (*ctx->Driver.DeleteTexture)(ctx, ss->DefaultRect); if (ss) _mesa_free(ss); return GL_FALSE; } /** * Callback for deleting a display list. Called by _mesa_HashDeleteAll(). */ static void delete_displaylist_cb(GLuint id, void *data, void *userData) { struct mesa_display_list *list = (struct mesa_display_list *) data; GLcontext *ctx = (GLcontext *) userData; _mesa_delete_list(ctx, list); } /** * Callback for deleting a texture object. Called by _mesa_HashDeleteAll(). */ static void delete_texture_cb(GLuint id, void *data, void *userData) { struct gl_texture_object *texObj = (struct gl_texture_object *) data; GLcontext *ctx = (GLcontext *) userData; ctx->Driver.DeleteTexture(ctx, texObj); } /** * Callback for deleting a program object. Called by _mesa_HashDeleteAll(). */ static void delete_program_cb(GLuint id, void *data, void *userData) { struct gl_program *prog = (struct gl_program *) data; GLcontext *ctx = (GLcontext *) userData; ctx->Driver.DeleteProgram(ctx, prog); } /** * Callback for deleting an ATI fragment shader object. * Called by _mesa_HashDeleteAll(). */ static void delete_fragshader_cb(GLuint id, void *data, void *userData) { struct ati_fragment_shader *shader = (struct ati_fragment_shader *) data; GLcontext *ctx = (GLcontext *) userData; _mesa_delete_ati_fragment_shader(ctx, shader); } /** * Callback for deleting a buffer object. Called by _mesa_HashDeleteAll(). */ static void delete_bufferobj_cb(GLuint id, void *data, void *userData) { struct gl_buffer_object *bufObj = (struct gl_buffer_object *) data; GLcontext *ctx = (GLcontext *) userData; ctx->Driver.DeleteBuffer(ctx, bufObj); } /** * Callback for deleting an array object. Called by _mesa_HashDeleteAll(). */ static void delete_arrayobj_cb(GLuint id, void *data, void *userData) { struct gl_array_object *arrayObj = (struct gl_array_object *) data; GLcontext *ctx = (GLcontext *) userData; _mesa_delete_array_object(ctx, arrayObj); } /** * Deallocate a shared state object and all children structures. * * \param ctx GL context. * \param ss shared state pointer. * * Frees the display lists, the texture objects (calling the driver texture * deletion callback to free its private data) and the vertex programs, as well * as their hash tables. * * \sa alloc_shared_state(). */ static void free_shared_state( GLcontext *ctx, struct gl_shared_state *ss ) { /* * Free display lists */ _mesa_HashDeleteAll(ss->DisplayList, delete_displaylist_cb, ctx); _mesa_DeleteHashTable(ss->DisplayList); /* * Free texture objects */ ASSERT(ctx->Driver.DeleteTexture); /* the default textures */ ctx->Driver.DeleteTexture(ctx, ss->Default1D); ctx->Driver.DeleteTexture(ctx, ss->Default2D); ctx->Driver.DeleteTexture(ctx, ss->Default3D); ctx->Driver.DeleteTexture(ctx, ss->DefaultCubeMap); ctx->Driver.DeleteTexture(ctx, ss->DefaultRect); /* all other textures */ _mesa_HashDeleteAll(ss->TexObjects, delete_texture_cb, ctx); _mesa_DeleteHashTable(ss->TexObjects); #if defined(FEATURE_NV_vertex_program) || defined(FEATURE_NV_fragment_program) _mesa_HashDeleteAll(ss->Programs, delete_program_cb, ctx); _mesa_DeleteHashTable(ss->Programs); #endif #if FEATURE_ARB_vertex_program _mesa_delete_program(ctx, ss->DefaultVertexProgram); #endif #if FEATURE_ARB_fragment_program _mesa_delete_program(ctx, ss->DefaultFragmentProgram); #endif #if FEATURE_ATI_fragment_shader _mesa_HashDeleteAll(ss->ATIShaders, delete_fragshader_cb, ctx); _mesa_DeleteHashTable(ss->ATIShaders); _mesa_delete_ati_fragment_shader(ctx, ss->DefaultFragmentShader); #endif #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object _mesa_HashDeleteAll(ss->BufferObjects, delete_bufferobj_cb, ctx); _mesa_DeleteHashTable(ss->BufferObjects); #endif _mesa_HashDeleteAll(ss->ArrayObjects, delete_arrayobj_cb, ctx); _mesa_DeleteHashTable(ss->ArrayObjects); #if FEATURE_ARB_shader_objects _mesa_DeleteHashTable(ss->GL2Objects); #endif #if FEATURE_EXT_framebuffer_object _mesa_DeleteHashTable(ss->FrameBuffers); _mesa_DeleteHashTable(ss->RenderBuffers); #endif _glthread_DESTROY_MUTEX(ss->Mutex); _mesa_free(ss); } /** * Initialize fields of gl_current_attrib (aka ctx->Current.*) */ static void _mesa_init_current( GLcontext *ctx ) { GLuint i; /* Init all to (0,0,0,1) */ for (i = 0; i < VERT_ATTRIB_MAX; i++) { ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 ); } /* redo special cases: */ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 1.0 ); ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 ); ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 ); ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 ); ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_FOG], 0.0, 0.0, 0.0, 0.0 ); ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX][0] = 1.0; ctx->Current.EdgeFlag = GL_TRUE; } /** * Init vertex/fragment program native limits from logical limits. */ static void init_natives(struct gl_program_constants *prog) { prog->MaxNativeInstructions = prog->MaxInstructions; prog->MaxNativeAluInstructions = prog->MaxAluInstructions; prog->MaxNativeTexInstructions = prog->MaxTexInstructions; prog->MaxNativeTexIndirections = prog->MaxTexIndirections; prog->MaxNativeAttribs = prog->MaxAttribs; prog->MaxNativeTemps = prog->MaxTemps; prog->MaxNativeAddressRegs = prog->MaxAddressRegs; prog->MaxNativeParameters = prog->MaxParameters; } /** * Initialize fields of gl_constants (aka ctx->Const.*). * Use defaults from config.h. The device drivers will often override * some of these values (such as number of texture units). */ static void _mesa_init_constants( GLcontext *ctx ) { assert(ctx); assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS); assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS); assert(MAX_TEXTURE_UNITS >= MAX_TEXTURE_COORD_UNITS); assert(MAX_TEXTURE_UNITS >= MAX_TEXTURE_IMAGE_UNITS); /* Constants, may be overriden (usually only reduced) by device drivers */ ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS; ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS; ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS; ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE; ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS; ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS; ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits, ctx->Const.MaxTextureImageUnits); ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY; ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS; ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE; ctx->Const.SubPixelBits = SUB_PIXEL_BITS; ctx->Const.MinPointSize = MIN_POINT_SIZE; ctx->Const.MaxPointSize = MAX_POINT_SIZE; ctx->Const.MinPointSizeAA = MIN_POINT_SIZE; ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE; ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY; ctx->Const.MinLineWidth = MIN_LINE_WIDTH; ctx->Const.MaxLineWidth = MAX_LINE_WIDTH; ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH; ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH; ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY; ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE; ctx->Const.MaxConvolutionWidth = MAX_CONVOLUTION_WIDTH; ctx->Const.MaxConvolutionHeight = MAX_CONVOLUTION_HEIGHT; ctx->Const.MaxClipPlanes = MAX_CLIP_PLANES; ctx->Const.MaxLights = MAX_LIGHTS; ctx->Const.MaxShininess = 128.0; ctx->Const.MaxSpotExponent = 128.0; ctx->Const.MaxViewportWidth = MAX_WIDTH; ctx->Const.MaxViewportHeight = MAX_HEIGHT; #if FEATURE_ARB_vertex_program ctx->Const.VertexProgram.MaxInstructions = MAX_NV_VERTEX_PROGRAM_INSTRUCTIONS; ctx->Const.VertexProgram.MaxAluInstructions = 0; ctx->Const.VertexProgram.MaxTexInstructions = 0; ctx->Const.VertexProgram.MaxTexIndirections = 0; ctx->Const.VertexProgram.MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS; ctx->Const.VertexProgram.MaxTemps = MAX_NV_VERTEX_PROGRAM_TEMPS; ctx->Const.VertexProgram.MaxParameters = MAX_NV_VERTEX_PROGRAM_PARAMS; ctx->Const.VertexProgram.MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS; ctx->Const.VertexProgram.MaxEnvParams = MAX_NV_VERTEX_PROGRAM_PARAMS; ctx->Const.VertexProgram.MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS; init_natives(&ctx->Const.VertexProgram); #endif #if FEATURE_ARB_fragment_program ctx->Const.FragmentProgram.MaxInstructions = MAX_NV_FRAGMENT_PROGRAM_INSTRUCTIONS; ctx->Const.FragmentProgram.MaxAluInstructions = MAX_FRAGMENT_PROGRAM_ALU_INSTRUCTIONS; ctx->Const.FragmentProgram.MaxTexInstructions = MAX_FRAGMENT_PROGRAM_TEX_INSTRUCTIONS; ctx->Const.FragmentProgram.MaxTexIndirections = MAX_FRAGMENT_PROGRAM_TEX_INDIRECTIONS; ctx->Const.FragmentProgram.MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS; ctx->Const.FragmentProgram.MaxTemps = MAX_NV_FRAGMENT_PROGRAM_TEMPS; ctx->Const.FragmentProgram.MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS; ctx->Const.FragmentProgram.MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS; ctx->Const.FragmentProgram.MaxEnvParams = MAX_NV_FRAGMENT_PROGRAM_PARAMS; ctx->Const.FragmentProgram.MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS; init_natives(&ctx->Const.FragmentProgram); #endif ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES; ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH; /* If we're running in the X server, do bounds checking to prevent * segfaults and server crashes! */ #if defined(XFree86LOADER) && defined(IN_MODULE) ctx->Const.CheckArrayBounds = GL_TRUE; #else ctx->Const.CheckArrayBounds = GL_FALSE; #endif /* GL_ARB_draw_buffers */ ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS; /* GL_OES_read_format */ ctx->Const.ColorReadFormat = GL_RGBA; ctx->Const.ColorReadType = GL_UNSIGNED_BYTE; #if FEATURE_EXT_framebuffer_object ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS; ctx->Const.MaxRenderbufferSize = MAX_WIDTH; #endif /* sanity checks */ ASSERT(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits, ctx->Const.MaxTextureCoordUnits)); ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS); ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS); } /** * Do some sanity checks on the limits/constants for the given context. * Only called the first time a context is bound. */ static void check_context_limits(GLcontext *ctx) { /* Many context limits/constants are limited by the size of * internal arrays. */ assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS); assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS); assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS); assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS); assert(ctx->Const.MaxViewportWidth <= MAX_WIDTH); assert(ctx->Const.MaxViewportHeight <= MAX_WIDTH); /* make sure largest texture image is <= MAX_WIDTH in size */ assert((1 << (ctx->Const.MaxTextureLevels -1 )) <= MAX_WIDTH); assert((1 << (ctx->Const.MaxCubeTextureLevels -1 )) <= MAX_WIDTH); assert((1 << (ctx->Const.Max3DTextureLevels -1 )) <= MAX_WIDTH); assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS); /* XXX probably add more tests */ } /** * Initialize the attribute groups in a GL context. * * \param ctx GL context. * * Initializes all the attributes, calling the respective <tt>init*</tt> * functions for the more complex data structures. */ static GLboolean init_attrib_groups( GLcontext *ctx ) { assert(ctx); /* Constants */ _mesa_init_constants( ctx ); /* Extensions */ _mesa_init_extensions( ctx ); /* Attribute Groups */ _mesa_init_accum( ctx ); _mesa_init_attrib( ctx ); _mesa_init_buffer_objects( ctx ); _mesa_init_color( ctx ); _mesa_init_colortables( ctx ); _mesa_init_current( ctx ); _mesa_init_depth( ctx ); _mesa_init_debug( ctx ); _mesa_init_display_list( ctx ); _mesa_init_eval( ctx ); _mesa_init_feedback( ctx ); _mesa_init_fog( ctx ); _mesa_init_histogram( ctx ); _mesa_init_hint( ctx ); _mesa_init_line( ctx ); _mesa_init_lighting( ctx ); _mesa_init_matrix( ctx ); _mesa_init_multisample( ctx ); _mesa_init_pixel( ctx ); _mesa_init_point( ctx ); _mesa_init_polygon( ctx ); _mesa_init_program( ctx ); _mesa_init_query( ctx ); _mesa_init_rastpos( ctx ); _mesa_init_scissor( ctx ); _mesa_init_shaderobjects (ctx); _mesa_init_stencil( ctx ); _mesa_init_transform( ctx ); _mesa_init_varray( ctx ); _mesa_init_viewport( ctx ); if (!_mesa_init_texture( ctx )) return GL_FALSE; _mesa_init_texture_s3tc( ctx ); _mesa_init_texture_fxt1( ctx ); /* Miscellaneous */ ctx->NewState = _NEW_ALL; ctx->ErrorValue = (GLenum) GL_NO_ERROR; ctx->_Facing = 0; return GL_TRUE; } /** * This is the default function we plug into all dispatch table slots * This helps prevents a segfault when someone calls a GL function without * first checking if the extension's supported. */ static int generic_nop(void) { _mesa_problem(NULL, "User called no-op dispatch function (an unsupported extension function?)"); return 0; } /** * Allocate and initialize a new dispatch table. */ static struct _glapi_table * alloc_dispatch_table(void) { /* Find the larger of Mesa's dispatch table and libGL's dispatch table. * In practice, this'll be the same for stand-alone Mesa. But for DRI * Mesa we do this to accomodate different versions of libGL and various * DRI drivers. */ GLint numEntries = MAX2(_glapi_get_dispatch_table_size(), sizeof(struct _glapi_table) / sizeof(_glapi_proc)); struct _glapi_table *table = (struct _glapi_table *) _mesa_malloc(numEntries * sizeof(_glapi_proc)); if (table) { _glapi_proc *entry = (_glapi_proc *) table; GLint i; for (i = 0; i < numEntries; i++) { entry[i] = (_glapi_proc) generic_nop; } } return table; } /** * Initialize a GLcontext struct (rendering context). * * This includes allocating all the other structs and arrays which hang off of * the context by pointers. * Note that the driver needs to pass in its dd_function_table here since * we need to at least call driverFunctions->NewTextureObject to create the * default texture objects. * * Called by _mesa_create_context(). * * Performs the imports and exports callback tables initialization, and * miscellaneous one-time initializations. If no shared context is supplied one * is allocated, and increase its reference count. Setups the GL API dispatch * tables. Initialize the TNL module. Sets the maximum Z buffer depth. * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables * for debug flags. * * \param ctx the context to initialize * \param visual describes the visual attributes for this context * \param share_list points to context to share textures, display lists, * etc with, or NULL * \param driverFunctions table of device driver functions for this context * to use * \param driverContext pointer to driver-specific context data */ GLboolean _mesa_initialize_context( GLcontext *ctx, const GLvisual *visual, GLcontext *share_list, const struct dd_function_table *driverFunctions, void *driverContext ) { ASSERT(driverContext); assert(driverFunctions->NewTextureObject); assert(driverFunctions->FreeTexImageData); /* If the driver wants core Mesa to use special imports, it'll have to * override these defaults. */ _mesa_init_default_imports( &(ctx->imports), driverContext ); /* initialize the exports (Mesa functions called by the window system) */ _mesa_init_default_exports( &(ctx->exports) ); /* misc one-time initializations */ one_time_init(ctx); ctx->Visual = *visual; ctx->DrawBuffer = NULL; ctx->ReadBuffer = NULL; ctx->WinSysDrawBuffer = NULL; ctx->WinSysReadBuffer = NULL; /* Plug in driver functions and context pointer here. * This is important because when we call alloc_shared_state() below * we'll call ctx->Driver.NewTextureObject() to create the default * textures. */ ctx->Driver = *driverFunctions; ctx->DriverCtx = driverContext; if (share_list) { /* share state with another context */ ctx->Shared = share_list->Shared; } else { /* allocate new, unshared state */ if (!alloc_shared_state( ctx )) { return GL_FALSE; } } _glthread_LOCK_MUTEX(ctx->Shared->Mutex); ctx->Shared->RefCount++; _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex); if (!init_attrib_groups( ctx )) { free_shared_state(ctx, ctx->Shared); return GL_FALSE; } /* setup the API dispatch tables */ ctx->Exec = alloc_dispatch_table(); ctx->Save = alloc_dispatch_table(); if (!ctx->Exec || !ctx->Save) { free_shared_state(ctx, ctx->Shared); if (ctx->Exec) _mesa_free(ctx->Exec); } _mesa_init_exec_table(ctx->Exec); ctx->CurrentDispatch = ctx->Exec; #if _HAVE_FULL_GL _mesa_init_dlist_table(ctx->Save); _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt ); /* Neutral tnl module stuff */ _mesa_init_exec_vtxfmt( ctx ); ctx->TnlModule.Current = NULL; ctx->TnlModule.SwapCount = 0; #endif ctx->_MaintainTexEnvProgram = (_mesa_getenv("MESA_TEX_PROG") != NULL); ctx->_UseTexEnvProgram = ctx->_MaintainTexEnvProgram; ctx->_MaintainTnlProgram = (_mesa_getenv("MESA_TNL_PROG") != NULL); if (ctx->_MaintainTnlProgram) ctx->_MaintainTexEnvProgram = 1; /* this is required... */ ctx->FirstTimeCurrent = GL_TRUE; return GL_TRUE; } /** * Allocate and initialize a GLcontext structure. * Note that the driver needs to pass in its dd_function_table here since * we need to at least call driverFunctions->NewTextureObject to initialize * the rendering context. * * \param visual a GLvisual pointer (we copy the struct contents) * \param share_list another context to share display lists with or NULL * \param driverFunctions points to the dd_function_table into which the * driver has plugged in all its special functions. * \param driverCtx points to the device driver's private context state * * \return pointer to a new __GLcontextRec or NULL if error. */ GLcontext * _mesa_create_context( const GLvisual *visual, GLcontext *share_list, const struct dd_function_table *driverFunctions, void *driverContext ) { GLcontext *ctx; ASSERT(visual); ASSERT(driverContext); ctx = (GLcontext *) _mesa_calloc(sizeof(GLcontext)); if (!ctx) return NULL; if (_mesa_initialize_context(ctx, visual, share_list, driverFunctions, driverContext)) { return ctx; } else { _mesa_free(ctx); return NULL; } } /** * Free the data associated with the given context. * * But doesn't free the GLcontext struct itself. * * \sa _mesa_initialize_context() and init_attrib_groups(). */ void _mesa_free_context_data( GLcontext *ctx ) { /* if we're destroying the current context, unbind it first */ if (ctx == _mesa_get_current_context()) { _mesa_make_current(NULL, NULL, NULL); } _mesa_free_lighting_data( ctx ); _mesa_free_eval_data( ctx ); _mesa_free_texture_data( ctx ); _mesa_free_matrix_data( ctx ); _mesa_free_viewport_data( ctx ); _mesa_free_colortables_data( ctx ); _mesa_free_program_data(ctx); _mesa_free_query_data(ctx); #if FEATURE_ARB_vertex_buffer_object _mesa_delete_buffer_object(ctx, ctx->Array.NullBufferObj); #endif _mesa_delete_array_object(ctx, ctx->Array.DefaultArrayObj); /* free dispatch tables */ _mesa_free(ctx->Exec); _mesa_free(ctx->Save); /* Shared context state (display lists, textures, etc) */ _glthread_LOCK_MUTEX(ctx->Shared->Mutex); ctx->Shared->RefCount--; assert(ctx->Shared->RefCount >= 0); _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex); if (ctx->Shared->RefCount == 0) { /* free shared state */ free_shared_state( ctx, ctx->Shared ); } if (ctx->Extensions.String) _mesa_free((void *) ctx->Extensions.String); } /** * Destroy a GLcontext structure. * * \param ctx GL context. * * Calls _mesa_free_context_data() and frees the GLcontext structure itself. */ void _mesa_destroy_context( GLcontext *ctx ) { if (ctx) { _mesa_free_context_data(ctx); _mesa_free( (void *) ctx ); } } #if _HAVE_FULL_GL /** * Copy attribute groups from one context to another. * * \param src source context * \param dst destination context * \param mask bitwise OR of GL_*_BIT flags * * According to the bits specified in \p mask, copies the corresponding * attributes from \p src into \p dst. For many of the attributes a simple \c * memcpy is not enough due to the existence of internal pointers in their data * structures. */ void _mesa_copy_context( const GLcontext *src, GLcontext *dst, GLuint mask ) { if (mask & GL_ACCUM_BUFFER_BIT) { /* OK to memcpy */ dst->Accum = src->Accum; } if (mask & GL_COLOR_BUFFER_BIT) { /* OK to memcpy */ dst->Color = src->Color; } if (mask & GL_CURRENT_BIT) { /* OK to memcpy */ dst->Current = src->Current; } if (mask & GL_DEPTH_BUFFER_BIT) { /* OK to memcpy */ dst->Depth = src->Depth; } if (mask & GL_ENABLE_BIT) { /* no op */ } if (mask & GL_EVAL_BIT) { /* OK to memcpy */ dst->Eval = src->Eval; } if (mask & GL_FOG_BIT) { /* OK to memcpy */ dst->Fog = src->Fog; } if (mask & GL_HINT_BIT) { /* OK to memcpy */ dst->Hint = src->Hint; } if (mask & GL_LIGHTING_BIT) { GLuint i; /* begin with memcpy */ dst->Light = src->Light; /* fixup linked lists to prevent pointer insanity */ make_empty_list( &(dst->Light.EnabledList) ); for (i = 0; i < MAX_LIGHTS; i++) { if (dst->Light.Light[i].Enabled) { insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i])); } } } if (mask & GL_LINE_BIT) { /* OK to memcpy */ dst->Line = src->Line; } if (mask & GL_LIST_BIT) { /* OK to memcpy */ dst->List = src->List; } if (mask & GL_PIXEL_MODE_BIT) { /* OK to memcpy */ dst->Pixel = src->Pixel; } if (mask & GL_POINT_BIT) { /* OK to memcpy */ dst->Point = src->Point; } if (mask & GL_POLYGON_BIT) { /* OK to memcpy */ dst->Polygon = src->Polygon; } if (mask & GL_POLYGON_STIPPLE_BIT) { /* Use loop instead of MEMCPY due to problem with Portland Group's * C compiler. Reported by John Stone. */ GLuint i; for (i = 0; i < 32; i++) { dst->PolygonStipple[i] = src->PolygonStipple[i]; } } if (mask & GL_SCISSOR_BIT) { /* OK to memcpy */ dst->Scissor = src->Scissor; } if (mask & GL_STENCIL_BUFFER_BIT) { /* OK to memcpy */ dst->Stencil = src->Stencil; } if (mask & GL_TEXTURE_BIT) { /* Cannot memcpy because of pointers */ _mesa_copy_texture_state(src, dst); } if (mask & GL_TRANSFORM_BIT) { /* OK to memcpy */ dst->Transform = src->Transform; } if (mask & GL_VIEWPORT_BIT) { /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */ dst->Viewport.X = src->Viewport.X; dst->Viewport.Y = src->Viewport.Y; dst->Viewport.Width = src->Viewport.Width; dst->Viewport.Height = src->Viewport.Height; dst->Viewport.Near = src->Viewport.Near; dst->Viewport.Far = src->Viewport.Far; _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap); } /* XXX FIXME: Call callbacks? */ dst->NewState = _NEW_ALL; } #endif /** * Check if the given context can render into the given framebuffer * by checking visual attributes. * * XXX this may go away someday because we're moving toward more freedom * in binding contexts to drawables with different visual attributes. * The GL_EXT_f_b_o extension is prompting some of that. * * \return GL_TRUE if compatible, GL_FALSE otherwise. */ static GLboolean check_compatible(const GLcontext *ctx, const GLframebuffer *buffer) { const GLvisual *ctxvis = &ctx->Visual; const GLvisual *bufvis = &buffer->Visual; if (ctxvis == bufvis) return GL_TRUE; if (ctxvis->rgbMode != bufvis->rgbMode) return GL_FALSE; #if 0 /* disabling this fixes the fgl_glxgears pbuffer demo */ if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode) return GL_FALSE; #endif if (ctxvis->stereoMode && !bufvis->stereoMode) return GL_FALSE; if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer) return GL_FALSE; if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer) return GL_FALSE; if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer) return GL_FALSE; if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask) return GL_FALSE; if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask) return GL_FALSE; if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask) return GL_FALSE; if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits) return GL_FALSE; if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits) return GL_FALSE; return GL_TRUE; } /** * Do one-time initialization for the given framebuffer. Specifically, * ask the driver for the window's current size and update the framebuffer * object to match. * Really, the device driver should totally take care of this. */ static void initialize_framebuffer_size(GLcontext *ctx, GLframebuffer *fb) { GLuint width, height; ASSERT(ctx->Driver.GetBufferSize); ctx->Driver.GetBufferSize(fb, &width, &height); if (ctx->Driver.ResizeBuffers) ctx->Driver.ResizeBuffers(ctx, fb, width, height); fb->Initialized = GL_TRUE; } /** * Bind the given context to the given drawBuffer and readBuffer and * make it the current context for the calling thread. * We'll render into the drawBuffer and read pixels from the * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc). * * We check that the context's and framebuffer's visuals are compatible * and return immediately if they're not. * * \param newCtx the new GL context. If NULL then there will be no current GL * context. * \param drawBuffer the drawing framebuffer * \param readBuffer the reading framebuffer */ void _mesa_make_current( GLcontext *newCtx, GLframebuffer *drawBuffer, GLframebuffer *readBuffer ) { if (MESA_VERBOSE & VERBOSE_API) _mesa_debug(newCtx, "_mesa_make_current()\n"); /* Check that the context's and framebuffer's visuals are compatible. */ if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) { if (!check_compatible(newCtx, drawBuffer)) { _mesa_warning(newCtx, "MakeCurrent: incompatible visuals for context and drawbuffer"); return; } } if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) { if (!check_compatible(newCtx, readBuffer)) { _mesa_warning(newCtx, "MakeCurrent: incompatible visuals for context and readbuffer"); return; } } /* We used to call _glapi_check_multithread() here. Now do it in drivers */ _glapi_set_context((void *) newCtx); ASSERT(_mesa_get_current_context() == newCtx); if (!newCtx) { _glapi_set_dispatch(NULL); /* none current */ } else { _glapi_set_dispatch(newCtx->CurrentDispatch); if (drawBuffer && readBuffer) { /* TODO: check if newCtx and buffer's visual match??? */ ASSERT(drawBuffer->Name == 0); ASSERT(readBuffer->Name == 0); newCtx->WinSysDrawBuffer = drawBuffer; newCtx->WinSysReadBuffer = readBuffer; /* * Only set the context's Draw/ReadBuffer fields if they're NULL * or not bound to a user-created FBO. */ if (!newCtx->DrawBuffer || newCtx->DrawBuffer->Name == 0) { newCtx->DrawBuffer = drawBuffer; } if (!newCtx->ReadBuffer || newCtx->ReadBuffer->Name == 0) { newCtx->ReadBuffer = readBuffer; } newCtx->NewState |= _NEW_BUFFERS; #if _HAVE_FULL_GL if (!drawBuffer->Initialized) { initialize_framebuffer_size(newCtx, drawBuffer); } if (readBuffer != drawBuffer && !readBuffer->Initialized) { initialize_framebuffer_size(newCtx, readBuffer); } #endif if (newCtx->FirstTimeCurrent) { /* set initial viewport and scissor size now */ _mesa_set_viewport(newCtx, 0, 0, drawBuffer->Width, drawBuffer->Height); _mesa_set_scissor(newCtx, 0, 0, drawBuffer->Width, drawBuffer->Height ); check_context_limits(newCtx); } } /* We can use this to help debug user's problems. Tell them to set * the MESA_INFO env variable before running their app. Then the * first time each context is made current we'll print some useful * information. */ if (newCtx->FirstTimeCurrent) { if (_mesa_getenv("MESA_INFO")) { _mesa_print_info(); } newCtx->FirstTimeCurrent = GL_FALSE; } } } /** * Make context 'ctx' share the display lists, textures and programs * that are associated with 'ctxToShare'. * Any display lists, textures or programs associated with 'ctx' will * be deleted if nobody else is sharing them. */ GLboolean _mesa_share_state(GLcontext *ctx, GLcontext *ctxToShare) { if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) { ctx->Shared->RefCount--; if (ctx->Shared->RefCount == 0) { free_shared_state(ctx, ctx->Shared); } ctx->Shared = ctxToShare->Shared; ctx->Shared->RefCount++; return GL_TRUE; } else { return GL_FALSE; } } /** * Get current context for the calling thread. * * \return pointer to the current GL context. * * Calls _glapi_get_context(). This isn't the fastest way to get the current * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in context.h. */ GLcontext * _mesa_get_current_context( void ) { return (GLcontext *) _glapi_get_context(); } /** * Get context's current API dispatch table. * * It'll either be the immediate-mode execute dispatcher or the display list * compile dispatcher. * * \param ctx GL context. * * \return pointer to dispatch_table. * * Simply returns __GLcontextRec::CurrentDispatch. */ struct _glapi_table * _mesa_get_dispatch(GLcontext *ctx) { return ctx->CurrentDispatch; } /*@}*/ /**********************************************************************/ /** \name Miscellaneous functions */ /**********************************************************************/ /*@{*/ /** * Record an error. * * \param ctx GL context. * \param error error code. * * Records the given error code and call the driver's dd_function_table::Error * function if defined. * * \sa * This is called via _mesa_error(). */ void _mesa_record_error( GLcontext *ctx, GLenum error ) { if (!ctx) return; if (ctx->ErrorValue == GL_NO_ERROR) { ctx->ErrorValue = error; } /* Call device driver's error handler, if any. This is used on the Mac. */ if (ctx->Driver.Error) { (*ctx->Driver.Error)( ctx ); } } /** * Execute glFinish(). * * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the * dd_function_table::Finish driver callback, if not NULL. */ void GLAPIENTRY _mesa_Finish( void ) { GET_CURRENT_CONTEXT(ctx); ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); if (ctx->Driver.Finish) { (*ctx->Driver.Finish)( ctx ); } } /** * Execute glFlush(). * * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the * dd_function_table::Flush driver callback, if not NULL. */ void GLAPIENTRY _mesa_Flush( void ) { GET_CURRENT_CONTEXT(ctx); ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); if (ctx->Driver.Flush) { (*ctx->Driver.Flush)( ctx ); } } /*@}*/