97ee925c0bb6d4ff523a2a2c42eeee3511e87b09
[mesa.git] / src / mesa / main / context.c
1 /*
2 * Mesa 3-D graphics library
3 * Version: 7.3
4 *
5 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
6 * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26 /**
27 * \file context.c
28 * Mesa context/visual/framebuffer management functions.
29 * \author Brian Paul
30 */
31
32 /**
33 * \mainpage Mesa Main Module
34 *
35 * \section MainIntroduction Introduction
36 *
37 * The Mesa Main module consists of all the files in the main/ directory.
38 * Among the features of this module are:
39 * <UL>
40 * <LI> Structures to represent most GL state </LI>
41 * <LI> State set/get functions </LI>
42 * <LI> Display lists </LI>
43 * <LI> Texture unit, object and image handling </LI>
44 * <LI> Matrix and attribute stacks </LI>
45 * </UL>
46 *
47 * Other modules are responsible for API dispatch, vertex transformation,
48 * point/line/triangle setup, rasterization, vertex array caching,
49 * vertex/fragment programs/shaders, etc.
50 *
51 *
52 * \section AboutDoxygen About Doxygen
53 *
54 * If you're viewing this information as Doxygen-generated HTML you'll
55 * see the documentation index at the top of this page.
56 *
57 * The first line lists the Mesa source code modules.
58 * The second line lists the indexes available for viewing the documentation
59 * for each module.
60 *
61 * Selecting the <b>Main page</b> link will display a summary of the module
62 * (this page).
63 *
64 * Selecting <b>Data Structures</b> will list all C structures.
65 *
66 * Selecting the <b>File List</b> link will list all the source files in
67 * the module.
68 * Selecting a filename will show a list of all functions defined in that file.
69 *
70 * Selecting the <b>Data Fields</b> link will display a list of all
71 * documented structure members.
72 *
73 * Selecting the <b>Globals</b> link will display a list
74 * of all functions, structures, global variables and macros in the module.
75 *
76 */
77
78
79 #include "glheader.h"
80 #include "mfeatures.h"
81 #include "imports.h"
82 #if FEATURE_accum
83 #include "accum.h"
84 #endif
85 #include "api_exec.h"
86 #include "arrayobj.h"
87 #if FEATURE_attrib_stack
88 #include "attrib.h"
89 #endif
90 #include "blend.h"
91 #include "buffers.h"
92 #include "bufferobj.h"
93 #if FEATURE_colortable
94 #include "colortab.h"
95 #endif
96 #include "context.h"
97 #include "debug.h"
98 #include "depth.h"
99 #if FEATURE_dlist
100 #include "dlist.h"
101 #endif
102 #if FEATURE_evaluators
103 #include "eval.h"
104 #endif
105 #include "enums.h"
106 #include "extensions.h"
107 #include "fbobject.h"
108 #if FEATURE_feedback
109 #include "feedback.h"
110 #endif
111 #include "fog.h"
112 #include "framebuffer.h"
113 #include "get.h"
114 #if FEATURE_histogram
115 #include "histogram.h"
116 #endif
117 #include "hint.h"
118 #include "hash.h"
119 #include "light.h"
120 #include "lines.h"
121 #include "macros.h"
122 #include "matrix.h"
123 #include "multisample.h"
124 #include "pixel.h"
125 #include "pixelstore.h"
126 #include "points.h"
127 #include "polygon.h"
128 #if FEATURE_ARB_occlusion_query
129 #include "queryobj.h"
130 #endif
131 #if FEATURE_drawpix
132 #include "rastpos.h"
133 #endif
134 #include "scissor.h"
135 #include "simple_list.h"
136 #include "state.h"
137 #include "stencil.h"
138 #include "texcompress.h"
139 #include "teximage.h"
140 #include "texobj.h"
141 #include "texstate.h"
142 #include "mtypes.h"
143 #include "varray.h"
144 #include "version.h"
145 #include "vtxfmt.h"
146 #include "glapi/glthread.h"
147 #include "glapi/glapioffsets.h"
148 #include "glapi/glapitable.h"
149 #include "shader/program.h"
150 #include "shader/shader_api.h"
151 #if FEATURE_ATI_fragment_shader
152 #include "shader/atifragshader.h"
153 #endif
154 #if _HAVE_FULL_GL
155 #include "math/m_matrix.h"
156 #endif
157
158 #ifdef USE_SPARC_ASM
159 #include "sparc/sparc.h"
160 #endif
161
162 #ifndef MESA_VERBOSE
163 int MESA_VERBOSE = 0;
164 #endif
165
166 #ifndef MESA_DEBUG_FLAGS
167 int MESA_DEBUG_FLAGS = 0;
168 #endif
169
170
171 /* ubyte -> float conversion */
172 GLfloat _mesa_ubyte_to_float_color_tab[256];
173
174
175
176 /**
177 * Swap buffers notification callback.
178 *
179 * \param gc GL context.
180 *
181 * Called by window system just before swapping buffers.
182 * We have to finish any pending rendering.
183 */
184 void
185 _mesa_notifySwapBuffers(__GLcontext *ctx)
186 {
187 FLUSH_VERTICES( ctx, 0 );
188 if (ctx->Driver.Flush) {
189 ctx->Driver.Flush(ctx);
190 }
191 }
192
193
194 /**********************************************************************/
195 /** \name GL Visual allocation/destruction */
196 /**********************************************************************/
197 /*@{*/
198
199 /**
200 * Allocates a GLvisual structure and initializes it via
201 * _mesa_initialize_visual().
202 *
203 * \param rgbFlag GL_TRUE for RGB(A) mode, GL_FALSE for Color Index mode.
204 * \param dbFlag double buffering
205 * \param stereoFlag stereo buffer
206 * \param depthBits requested bits per depth buffer value. Any value in [0, 32]
207 * is acceptable but the actual depth type will be GLushort or GLuint as
208 * needed.
209 * \param stencilBits requested minimum bits per stencil buffer value
210 * \param accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits number of bits per color component in accum buffer.
211 * \param indexBits number of bits per pixel if \p rgbFlag is GL_FALSE
212 * \param redBits number of bits per color component in frame buffer for RGB(A)
213 * mode. We always use 8 in core Mesa though.
214 * \param greenBits same as above.
215 * \param blueBits same as above.
216 * \param alphaBits same as above.
217 * \param numSamples not really used.
218 *
219 * \return pointer to new GLvisual or NULL if requested parameters can't be
220 * met.
221 *
222 * \note Need to add params for level and numAuxBuffers (at least)
223 */
224 GLvisual *
225 _mesa_create_visual( GLboolean rgbFlag,
226 GLboolean dbFlag,
227 GLboolean stereoFlag,
228 GLint redBits,
229 GLint greenBits,
230 GLint blueBits,
231 GLint alphaBits,
232 GLint indexBits,
233 GLint depthBits,
234 GLint stencilBits,
235 GLint accumRedBits,
236 GLint accumGreenBits,
237 GLint accumBlueBits,
238 GLint accumAlphaBits,
239 GLint numSamples )
240 {
241 GLvisual *vis = (GLvisual *) _mesa_calloc(sizeof(GLvisual));
242 if (vis) {
243 if (!_mesa_initialize_visual(vis, rgbFlag, dbFlag, stereoFlag,
244 redBits, greenBits, blueBits, alphaBits,
245 indexBits, depthBits, stencilBits,
246 accumRedBits, accumGreenBits,
247 accumBlueBits, accumAlphaBits,
248 numSamples)) {
249 _mesa_free(vis);
250 return NULL;
251 }
252 }
253 return vis;
254 }
255
256 /**
257 * Makes some sanity checks and fills in the fields of the
258 * GLvisual object with the given parameters. If the caller needs
259 * to set additional fields, he should just probably init the whole GLvisual
260 * object himself.
261 * \return GL_TRUE on success, or GL_FALSE on failure.
262 *
263 * \sa _mesa_create_visual() above for the parameter description.
264 */
265 GLboolean
266 _mesa_initialize_visual( GLvisual *vis,
267 GLboolean rgbFlag,
268 GLboolean dbFlag,
269 GLboolean stereoFlag,
270 GLint redBits,
271 GLint greenBits,
272 GLint blueBits,
273 GLint alphaBits,
274 GLint indexBits,
275 GLint depthBits,
276 GLint stencilBits,
277 GLint accumRedBits,
278 GLint accumGreenBits,
279 GLint accumBlueBits,
280 GLint accumAlphaBits,
281 GLint numSamples )
282 {
283 assert(vis);
284
285 if (depthBits < 0 || depthBits > 32) {
286 return GL_FALSE;
287 }
288 if (stencilBits < 0 || stencilBits > STENCIL_BITS) {
289 return GL_FALSE;
290 }
291 assert(accumRedBits >= 0);
292 assert(accumGreenBits >= 0);
293 assert(accumBlueBits >= 0);
294 assert(accumAlphaBits >= 0);
295
296 vis->rgbMode = rgbFlag;
297 vis->doubleBufferMode = dbFlag;
298 vis->stereoMode = stereoFlag;
299
300 vis->redBits = redBits;
301 vis->greenBits = greenBits;
302 vis->blueBits = blueBits;
303 vis->alphaBits = alphaBits;
304 vis->rgbBits = redBits + greenBits + blueBits;
305
306 vis->indexBits = indexBits;
307 vis->depthBits = depthBits;
308 vis->stencilBits = stencilBits;
309
310 vis->accumRedBits = accumRedBits;
311 vis->accumGreenBits = accumGreenBits;
312 vis->accumBlueBits = accumBlueBits;
313 vis->accumAlphaBits = accumAlphaBits;
314
315 vis->haveAccumBuffer = accumRedBits > 0;
316 vis->haveDepthBuffer = depthBits > 0;
317 vis->haveStencilBuffer = stencilBits > 0;
318
319 vis->numAuxBuffers = 0;
320 vis->level = 0;
321 vis->pixmapMode = 0;
322 vis->sampleBuffers = numSamples > 0 ? 1 : 0;
323 vis->samples = numSamples;
324
325 return GL_TRUE;
326 }
327
328
329 /**
330 * Destroy a visual and free its memory.
331 *
332 * \param vis visual.
333 *
334 * Frees the visual structure.
335 */
336 void
337 _mesa_destroy_visual( GLvisual *vis )
338 {
339 _mesa_free(vis);
340 }
341
342 /*@}*/
343
344
345 /**********************************************************************/
346 /** \name Context allocation, initialization, destroying
347 *
348 * The purpose of the most initialization functions here is to provide the
349 * default state values according to the OpenGL specification.
350 */
351 /**********************************************************************/
352 /*@{*/
353
354
355 /**
356 * This is lame. gdb only seems to recognize enum types that are
357 * actually used somewhere. We want to be able to print/use enum
358 * values such as TEXTURE_2D_INDEX in gdb. But we don't actually use
359 * the gl_texture_index type anywhere. Thus, this lame function.
360 */
361 static void
362 dummy_enum_func(void)
363 {
364 gl_buffer_index bi;
365 gl_colortable_index ci;
366 gl_face_index fi;
367 gl_frag_attrib fa;
368 gl_frag_result fr;
369 gl_texture_index ti;
370 gl_vert_attrib va;
371 gl_vert_result vr;
372
373 (void) bi;
374 (void) ci;
375 (void) fi;
376 (void) fa;
377 (void) fr;
378 (void) ti;
379 (void) va;
380 (void) vr;
381 }
382
383
384 /**
385 * One-time initialization mutex lock.
386 *
387 * \sa Used by one_time_init().
388 */
389 _glthread_DECLARE_STATIC_MUTEX(OneTimeLock);
390
391 /**
392 * Calls all the various one-time-init functions in Mesa.
393 *
394 * While holding a global mutex lock, calls several initialization functions,
395 * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
396 * defined.
397 *
398 * \sa _math_init().
399 */
400 static void
401 one_time_init( GLcontext *ctx )
402 {
403 static GLboolean alreadyCalled = GL_FALSE;
404 (void) ctx;
405 _glthread_LOCK_MUTEX(OneTimeLock);
406 if (!alreadyCalled) {
407 GLuint i;
408
409 /* do some implementation tests */
410 assert( sizeof(GLbyte) == 1 );
411 assert( sizeof(GLubyte) == 1 );
412 assert( sizeof(GLshort) == 2 );
413 assert( sizeof(GLushort) == 2 );
414 assert( sizeof(GLint) == 4 );
415 assert( sizeof(GLuint) == 4 );
416
417 _mesa_init_sqrt_table();
418
419 for (i = 0; i < 256; i++) {
420 _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
421 }
422
423 if (_mesa_getenv("MESA_DEBUG")) {
424 _glapi_noop_enable_warnings(GL_TRUE);
425 _glapi_set_warning_func( (_glapi_warning_func) _mesa_warning );
426 }
427 else {
428 _glapi_noop_enable_warnings(GL_FALSE);
429 }
430
431 #if defined(DEBUG) && defined(__DATE__) && defined(__TIME__)
432 _mesa_debug(ctx, "Mesa %s DEBUG build %s %s\n",
433 MESA_VERSION_STRING, __DATE__, __TIME__);
434 #endif
435
436 alreadyCalled = GL_TRUE;
437 }
438 _glthread_UNLOCK_MUTEX(OneTimeLock);
439
440 dummy_enum_func();
441 }
442
443
444 /**
445 * Allocate and initialize a shared context state structure.
446 * Initializes the display list, texture objects and vertex programs hash
447 * tables, allocates the texture objects. If it runs out of memory, frees
448 * everything already allocated before returning NULL.
449 *
450 * \return pointer to a gl_shared_state structure on success, or NULL on
451 * failure.
452 */
453 static GLboolean
454 alloc_shared_state( GLcontext *ctx )
455 {
456 GLuint i;
457 struct gl_shared_state *ss = CALLOC_STRUCT(gl_shared_state);
458 if (!ss)
459 return GL_FALSE;
460
461 ctx->Shared = ss;
462
463 _glthread_INIT_MUTEX(ss->Mutex);
464
465 ss->DisplayList = _mesa_NewHashTable();
466 ss->TexObjects = _mesa_NewHashTable();
467 ss->Programs = _mesa_NewHashTable();
468
469 #if FEATURE_ARB_vertex_program
470 ss->DefaultVertexProgram = (struct gl_vertex_program *)
471 ctx->Driver.NewProgram(ctx, GL_VERTEX_PROGRAM_ARB, 0);
472 if (!ss->DefaultVertexProgram)
473 goto cleanup;
474 #endif
475 #if FEATURE_ARB_fragment_program
476 ss->DefaultFragmentProgram = (struct gl_fragment_program *)
477 ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
478 if (!ss->DefaultFragmentProgram)
479 goto cleanup;
480 #endif
481 #if FEATURE_ATI_fragment_shader
482 ss->ATIShaders = _mesa_NewHashTable();
483 ss->DefaultFragmentShader = _mesa_new_ati_fragment_shader(ctx, 0);
484 if (!ss->DefaultFragmentShader)
485 goto cleanup;
486 #endif
487
488 #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object
489 ss->BufferObjects = _mesa_NewHashTable();
490 #endif
491
492 ss->ArrayObjects = _mesa_NewHashTable();
493
494 #if FEATURE_ARB_shader_objects
495 ss->ShaderObjects = _mesa_NewHashTable();
496 #endif
497
498 /* Create default texture objects */
499 for (i = 0; i < NUM_TEXTURE_TARGETS; i++) {
500 /* NOTE: the order of these enums matches the TEXTURE_x_INDEX values */
501 static const GLenum targets[NUM_TEXTURE_TARGETS] = {
502 GL_TEXTURE_2D_ARRAY_EXT,
503 GL_TEXTURE_1D_ARRAY_EXT,
504 GL_TEXTURE_CUBE_MAP,
505 GL_TEXTURE_3D,
506 GL_TEXTURE_RECTANGLE_NV,
507 GL_TEXTURE_2D,
508 GL_TEXTURE_1D
509 };
510 ss->DefaultTex[i] = ctx->Driver.NewTextureObject(ctx, 0, targets[i]);
511 if (!ss->DefaultTex[i])
512 goto cleanup;
513 }
514
515 /* sanity check */
516 assert(ss->DefaultTex[TEXTURE_1D_INDEX]->RefCount == 1);
517
518 _glthread_INIT_MUTEX(ss->TexMutex);
519 ss->TextureStateStamp = 0;
520
521 #if FEATURE_EXT_framebuffer_object
522 ss->FrameBuffers = _mesa_NewHashTable();
523 if (!ss->FrameBuffers)
524 goto cleanup;
525 ss->RenderBuffers = _mesa_NewHashTable();
526 if (!ss->RenderBuffers)
527 goto cleanup;
528 #endif
529
530 return GL_TRUE;
531
532 cleanup:
533 /* Ran out of memory at some point. Free everything and return NULL */
534 if (ss->DisplayList)
535 _mesa_DeleteHashTable(ss->DisplayList);
536 if (ss->TexObjects)
537 _mesa_DeleteHashTable(ss->TexObjects);
538 if (ss->Programs)
539 _mesa_DeleteHashTable(ss->Programs);
540 #if FEATURE_ARB_vertex_program
541 _mesa_reference_vertprog(ctx, &ss->DefaultVertexProgram, NULL);
542 #endif
543 #if FEATURE_ARB_fragment_program
544 _mesa_reference_fragprog(ctx, &ss->DefaultFragmentProgram, NULL);
545 #endif
546 #if FEATURE_ATI_fragment_shader
547 if (ss->DefaultFragmentShader)
548 _mesa_delete_ati_fragment_shader(ctx, ss->DefaultFragmentShader);
549 #endif
550 #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object
551 if (ss->BufferObjects)
552 _mesa_DeleteHashTable(ss->BufferObjects);
553 #endif
554
555 if (ss->ArrayObjects)
556 _mesa_DeleteHashTable (ss->ArrayObjects);
557
558 #if FEATURE_ARB_shader_objects
559 if (ss->ShaderObjects)
560 _mesa_DeleteHashTable (ss->ShaderObjects);
561 #endif
562
563 #if FEATURE_EXT_framebuffer_object
564 if (ss->FrameBuffers)
565 _mesa_DeleteHashTable(ss->FrameBuffers);
566 if (ss->RenderBuffers)
567 _mesa_DeleteHashTable(ss->RenderBuffers);
568 #endif
569
570 for (i = 0; i < NUM_TEXTURE_TARGETS; i++) {
571 if (ss->DefaultTex[i])
572 ctx->Driver.DeleteTexture(ctx, ss->DefaultTex[i]);
573 }
574
575 _mesa_free(ss);
576
577 return GL_FALSE;
578 }
579
580
581 /**
582 * Callback for deleting a display list. Called by _mesa_HashDeleteAll().
583 */
584 static void
585 delete_displaylist_cb(GLuint id, void *data, void *userData)
586 {
587 #if FEATURE_dlist
588 struct gl_display_list *list = (struct gl_display_list *) data;
589 GLcontext *ctx = (GLcontext *) userData;
590 _mesa_delete_list(ctx, list);
591 #endif
592 }
593
594 /**
595 * Callback for deleting a texture object. Called by _mesa_HashDeleteAll().
596 */
597 static void
598 delete_texture_cb(GLuint id, void *data, void *userData)
599 {
600 struct gl_texture_object *texObj = (struct gl_texture_object *) data;
601 GLcontext *ctx = (GLcontext *) userData;
602 ctx->Driver.DeleteTexture(ctx, texObj);
603 }
604
605 /**
606 * Callback for deleting a program object. Called by _mesa_HashDeleteAll().
607 */
608 static void
609 delete_program_cb(GLuint id, void *data, void *userData)
610 {
611 struct gl_program *prog = (struct gl_program *) data;
612 GLcontext *ctx = (GLcontext *) userData;
613 ASSERT(prog->RefCount == 1); /* should only be referenced by hash table */
614 prog->RefCount = 0; /* now going away */
615 ctx->Driver.DeleteProgram(ctx, prog);
616 }
617
618 #if FEATURE_ATI_fragment_shader
619 /**
620 * Callback for deleting an ATI fragment shader object.
621 * Called by _mesa_HashDeleteAll().
622 */
623 static void
624 delete_fragshader_cb(GLuint id, void *data, void *userData)
625 {
626 struct ati_fragment_shader *shader = (struct ati_fragment_shader *) data;
627 GLcontext *ctx = (GLcontext *) userData;
628 _mesa_delete_ati_fragment_shader(ctx, shader);
629 }
630 #endif
631
632 /**
633 * Callback for deleting a buffer object. Called by _mesa_HashDeleteAll().
634 */
635 static void
636 delete_bufferobj_cb(GLuint id, void *data, void *userData)
637 {
638 struct gl_buffer_object *bufObj = (struct gl_buffer_object *) data;
639 GLcontext *ctx = (GLcontext *) userData;
640 ctx->Driver.DeleteBuffer(ctx, bufObj);
641 }
642
643 /**
644 * Callback for deleting an array object. Called by _mesa_HashDeleteAll().
645 */
646 static void
647 delete_arrayobj_cb(GLuint id, void *data, void *userData)
648 {
649 struct gl_array_object *arrayObj = (struct gl_array_object *) data;
650 GLcontext *ctx = (GLcontext *) userData;
651 _mesa_delete_array_object(ctx, arrayObj);
652 }
653
654 /**
655 * Callback for freeing shader program data. Call it before delete_shader_cb
656 * to avoid memory access error.
657 */
658 static void
659 free_shader_program_data_cb(GLuint id, void *data, void *userData)
660 {
661 GLcontext *ctx = (GLcontext *) userData;
662 struct gl_shader_program *shProg = (struct gl_shader_program *) data;
663
664 if (shProg->Type == GL_SHADER_PROGRAM_MESA) {
665 _mesa_free_shader_program_data(ctx, shProg);
666 }
667 }
668
669 /**
670 * Callback for deleting shader and shader programs objects.
671 * Called by _mesa_HashDeleteAll().
672 */
673 static void
674 delete_shader_cb(GLuint id, void *data, void *userData)
675 {
676 GLcontext *ctx = (GLcontext *) userData;
677 struct gl_shader *sh = (struct gl_shader *) data;
678 if (sh->Type == GL_FRAGMENT_SHADER || sh->Type == GL_VERTEX_SHADER) {
679 _mesa_free_shader(ctx, sh);
680 }
681 else {
682 struct gl_shader_program *shProg = (struct gl_shader_program *) data;
683 ASSERT(shProg->Type == GL_SHADER_PROGRAM_MESA);
684 _mesa_free_shader_program(ctx, shProg);
685 }
686 }
687
688 /**
689 * Callback for deleting a framebuffer object. Called by _mesa_HashDeleteAll()
690 */
691 static void
692 delete_framebuffer_cb(GLuint id, void *data, void *userData)
693 {
694 struct gl_framebuffer *fb = (struct gl_framebuffer *) data;
695 /* The fact that the framebuffer is in the hashtable means its refcount
696 * is one, but we're removing from the hashtable now. So clear refcount.
697 */
698 /*assert(fb->RefCount == 1);*/
699 fb->RefCount = 0;
700
701 /* NOTE: Delete should always be defined but there are two reports
702 * of it being NULL (bugs 13507, 14293). Work-around for now.
703 */
704 if (fb->Delete)
705 fb->Delete(fb);
706 }
707
708 /**
709 * Callback for deleting a renderbuffer object. Called by _mesa_HashDeleteAll()
710 */
711 static void
712 delete_renderbuffer_cb(GLuint id, void *data, void *userData)
713 {
714 struct gl_renderbuffer *rb = (struct gl_renderbuffer *) data;
715 rb->RefCount = 0; /* see comment for FBOs above */
716 if (rb->Delete)
717 rb->Delete(rb);
718 }
719
720
721 /**
722 * Deallocate a shared state object and all children structures.
723 *
724 * \param ctx GL context.
725 * \param ss shared state pointer.
726 *
727 * Frees the display lists, the texture objects (calling the driver texture
728 * deletion callback to free its private data) and the vertex programs, as well
729 * as their hash tables.
730 *
731 * \sa alloc_shared_state().
732 */
733 static void
734 free_shared_state( GLcontext *ctx, struct gl_shared_state *ss )
735 {
736 GLuint i;
737
738 /*
739 * Free display lists
740 */
741 _mesa_HashDeleteAll(ss->DisplayList, delete_displaylist_cb, ctx);
742 _mesa_DeleteHashTable(ss->DisplayList);
743
744 #if FEATURE_ARB_shader_objects
745 _mesa_HashWalk(ss->ShaderObjects, free_shader_program_data_cb, ctx);
746 _mesa_HashDeleteAll(ss->ShaderObjects, delete_shader_cb, ctx);
747 _mesa_DeleteHashTable(ss->ShaderObjects);
748 #endif
749
750 _mesa_HashDeleteAll(ss->Programs, delete_program_cb, ctx);
751 _mesa_DeleteHashTable(ss->Programs);
752
753 #if FEATURE_ARB_vertex_program
754 _mesa_reference_vertprog(ctx, &ss->DefaultVertexProgram, NULL);
755 #endif
756 #if FEATURE_ARB_fragment_program
757 _mesa_reference_fragprog(ctx, &ss->DefaultFragmentProgram, NULL);
758 #endif
759
760 #if FEATURE_ATI_fragment_shader
761 _mesa_HashDeleteAll(ss->ATIShaders, delete_fragshader_cb, ctx);
762 _mesa_DeleteHashTable(ss->ATIShaders);
763 _mesa_delete_ati_fragment_shader(ctx, ss->DefaultFragmentShader);
764 #endif
765
766 #if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object
767 _mesa_HashDeleteAll(ss->BufferObjects, delete_bufferobj_cb, ctx);
768 _mesa_DeleteHashTable(ss->BufferObjects);
769 #endif
770
771 _mesa_HashDeleteAll(ss->ArrayObjects, delete_arrayobj_cb, ctx);
772 _mesa_DeleteHashTable(ss->ArrayObjects);
773
774 #if FEATURE_EXT_framebuffer_object
775 _mesa_HashDeleteAll(ss->FrameBuffers, delete_framebuffer_cb, ctx);
776 _mesa_DeleteHashTable(ss->FrameBuffers);
777 _mesa_HashDeleteAll(ss->RenderBuffers, delete_renderbuffer_cb, ctx);
778 _mesa_DeleteHashTable(ss->RenderBuffers);
779 #endif
780
781 /*
782 * Free texture objects (after FBOs since some textures might have
783 * been bound to FBOs).
784 */
785 ASSERT(ctx->Driver.DeleteTexture);
786 /* the default textures */
787 for (i = 0; i < NUM_TEXTURE_TARGETS; i++) {
788 ctx->Driver.DeleteTexture(ctx, ss->DefaultTex[i]);
789 }
790 /* all other textures */
791 _mesa_HashDeleteAll(ss->TexObjects, delete_texture_cb, ctx);
792 _mesa_DeleteHashTable(ss->TexObjects);
793
794 _glthread_DESTROY_MUTEX(ss->Mutex);
795
796 _mesa_free(ss);
797 }
798
799
800 /**
801 * Initialize fields of gl_current_attrib (aka ctx->Current.*)
802 */
803 static void
804 _mesa_init_current(GLcontext *ctx)
805 {
806 GLuint i;
807
808 /* Init all to (0,0,0,1) */
809 for (i = 0; i < VERT_ATTRIB_MAX; i++) {
810 ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
811 }
812
813 /* redo special cases: */
814 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 0.0 );
815 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
816 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
817 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
818 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
819 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
820 }
821
822
823 /**
824 * Init vertex/fragment program limits.
825 * Important: drivers should override these with actual limits.
826 */
827 static void
828 init_program_limits(GLenum type, struct gl_program_constants *prog)
829 {
830 prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
831 prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
832 prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
833 prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
834 prog->MaxTemps = MAX_PROGRAM_TEMPS;
835 prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
836 prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
837 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
838
839 if (type == GL_VERTEX_PROGRAM_ARB) {
840 prog->MaxParameters = MAX_NV_VERTEX_PROGRAM_PARAMS;
841 prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
842 prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
843 }
844 else {
845 prog->MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS;
846 prog->MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS;
847 prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
848 }
849
850 /* copy the above limits to init native limits */
851 prog->MaxNativeInstructions = prog->MaxInstructions;
852 prog->MaxNativeAluInstructions = prog->MaxAluInstructions;
853 prog->MaxNativeTexInstructions = prog->MaxTexInstructions;
854 prog->MaxNativeTexIndirections = prog->MaxTexIndirections;
855 prog->MaxNativeAttribs = prog->MaxAttribs;
856 prog->MaxNativeTemps = prog->MaxTemps;
857 prog->MaxNativeAddressRegs = prog->MaxAddressRegs;
858 prog->MaxNativeParameters = prog->MaxParameters;
859 }
860
861
862 /**
863 * Initialize fields of gl_constants (aka ctx->Const.*).
864 * Use defaults from config.h. The device drivers will often override
865 * some of these values (such as number of texture units).
866 */
867 static void
868 _mesa_init_constants(GLcontext *ctx)
869 {
870 assert(ctx);
871
872 assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
873 assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
874
875 /* Max texture size should be <= max viewport size (render to texture) */
876 assert((1 << (MAX_TEXTURE_LEVELS - 1)) <= MAX_WIDTH);
877
878 /* Constants, may be overriden (usually only reduced) by device drivers */
879 ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS;
880 ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS;
881 ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS;
882 ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
883 ctx->Const.MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
884 ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
885 ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
886 ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits,
887 ctx->Const.MaxTextureImageUnits);
888 ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
889 ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
890 ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
891 ctx->Const.SubPixelBits = SUB_PIXEL_BITS;
892 ctx->Const.MinPointSize = MIN_POINT_SIZE;
893 ctx->Const.MaxPointSize = MAX_POINT_SIZE;
894 ctx->Const.MinPointSizeAA = MIN_POINT_SIZE;
895 ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE;
896 ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
897 ctx->Const.MinLineWidth = MIN_LINE_WIDTH;
898 ctx->Const.MaxLineWidth = MAX_LINE_WIDTH;
899 ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH;
900 ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH;
901 ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
902 ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE;
903 ctx->Const.MaxConvolutionWidth = MAX_CONVOLUTION_WIDTH;
904 ctx->Const.MaxConvolutionHeight = MAX_CONVOLUTION_HEIGHT;
905 ctx->Const.MaxClipPlanes = MAX_CLIP_PLANES;
906 ctx->Const.MaxLights = MAX_LIGHTS;
907 ctx->Const.MaxShininess = 128.0;
908 ctx->Const.MaxSpotExponent = 128.0;
909 ctx->Const.MaxViewportWidth = MAX_WIDTH;
910 ctx->Const.MaxViewportHeight = MAX_HEIGHT;
911 #if FEATURE_ARB_vertex_program
912 init_program_limits(GL_VERTEX_PROGRAM_ARB, &ctx->Const.VertexProgram);
913 #endif
914 #if FEATURE_ARB_fragment_program
915 init_program_limits(GL_FRAGMENT_PROGRAM_ARB, &ctx->Const.FragmentProgram);
916 #endif
917 ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES;
918 ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
919
920 /* CheckArrayBounds is overriden by drivers/x11 for X server */
921 ctx->Const.CheckArrayBounds = GL_FALSE;
922
923 /* GL_ARB_draw_buffers */
924 ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS;
925
926 /* GL_OES_read_format */
927 ctx->Const.ColorReadFormat = GL_RGBA;
928 ctx->Const.ColorReadType = GL_UNSIGNED_BYTE;
929
930 #if FEATURE_EXT_framebuffer_object
931 ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
932 ctx->Const.MaxRenderbufferSize = MAX_WIDTH;
933 #endif
934
935 #if FEATURE_ARB_vertex_shader
936 ctx->Const.MaxVertexTextureImageUnits = MAX_VERTEX_TEXTURE_IMAGE_UNITS;
937 ctx->Const.MaxVarying = MAX_VARYING;
938 #endif
939
940 /* GL_ARB_framebuffer_object */
941 ctx->Const.MaxSamples = 0;
942
943 /* sanity checks */
944 ASSERT(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
945 ctx->Const.MaxTextureCoordUnits));
946 ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
947 ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
948
949 ASSERT(MAX_NV_FRAGMENT_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
950 ASSERT(MAX_NV_VERTEX_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
951 ASSERT(MAX_NV_VERTEX_PROGRAM_INPUTS <= VERT_ATTRIB_MAX);
952 ASSERT(MAX_NV_VERTEX_PROGRAM_OUTPUTS <= VERT_RESULT_MAX);
953 }
954
955
956 /**
957 * Do some sanity checks on the limits/constants for the given context.
958 * Only called the first time a context is bound.
959 */
960 static void
961 check_context_limits(GLcontext *ctx)
962 {
963 /* Many context limits/constants are limited by the size of
964 * internal arrays.
965 */
966 assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
967 assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
968 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
969 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
970
971 /* number of coord units cannot be greater than number of image units */
972 assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
973
974 assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
975 assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
976 assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
977 assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
978
979 /* make sure largest texture image is <= MAX_WIDTH in size */
980 assert((1 << (ctx->Const.MaxTextureLevels - 1)) <= MAX_WIDTH);
981 assert((1 << (ctx->Const.MaxCubeTextureLevels - 1)) <= MAX_WIDTH);
982 assert((1 << (ctx->Const.Max3DTextureLevels - 1)) <= MAX_WIDTH);
983
984 assert(ctx->Const.MaxViewportWidth <= MAX_WIDTH);
985 assert(ctx->Const.MaxViewportHeight <= MAX_WIDTH);
986
987 assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
988
989 /* XXX probably add more tests */
990 }
991
992
993 /**
994 * Initialize the attribute groups in a GL context.
995 *
996 * \param ctx GL context.
997 *
998 * Initializes all the attributes, calling the respective <tt>init*</tt>
999 * functions for the more complex data structures.
1000 */
1001 static GLboolean
1002 init_attrib_groups(GLcontext *ctx)
1003 {
1004 assert(ctx);
1005
1006 /* Constants */
1007 _mesa_init_constants( ctx );
1008
1009 /* Extensions */
1010 _mesa_init_extensions( ctx );
1011
1012 /* Attribute Groups */
1013 #if FEATURE_accum
1014 _mesa_init_accum( ctx );
1015 #endif
1016 #if FEATURE_attrib_stack
1017 _mesa_init_attrib( ctx );
1018 #endif
1019 _mesa_init_buffer_objects( ctx );
1020 _mesa_init_color( ctx );
1021 #if FEATURE_colortable
1022 _mesa_init_colortables( ctx );
1023 #endif
1024 _mesa_init_current( ctx );
1025 _mesa_init_depth( ctx );
1026 _mesa_init_debug( ctx );
1027 #if FEATURE_dlist
1028 _mesa_init_display_list( ctx );
1029 #endif
1030 #if FEATURE_evaluators
1031 _mesa_init_eval( ctx );
1032 #endif
1033 _mesa_init_fbobjects( ctx );
1034 #if FEATURE_feedback
1035 _mesa_init_feedback( ctx );
1036 #else
1037 ctx->RenderMode = GL_RENDER;
1038 #endif
1039 _mesa_init_fog( ctx );
1040 #if FEATURE_histogram
1041 _mesa_init_histogram( ctx );
1042 #endif
1043 _mesa_init_hint( ctx );
1044 _mesa_init_line( ctx );
1045 _mesa_init_lighting( ctx );
1046 _mesa_init_matrix( ctx );
1047 _mesa_init_multisample( ctx );
1048 _mesa_init_pixel( ctx );
1049 _mesa_init_pixelstore( ctx );
1050 _mesa_init_point( ctx );
1051 _mesa_init_polygon( ctx );
1052 _mesa_init_program( ctx );
1053 #if FEATURE_ARB_occlusion_query
1054 _mesa_init_query( ctx );
1055 #endif
1056 #if FEATURE_drawpix
1057 _mesa_init_rastpos( ctx );
1058 #endif
1059 _mesa_init_scissor( ctx );
1060 _mesa_init_shader_state( ctx );
1061 _mesa_init_stencil( ctx );
1062 _mesa_init_transform( ctx );
1063 _mesa_init_varray( ctx );
1064 _mesa_init_viewport( ctx );
1065
1066 if (!_mesa_init_texture( ctx ))
1067 return GL_FALSE;
1068
1069 #if FEATURE_texture_s3tc
1070 _mesa_init_texture_s3tc( ctx );
1071 #endif
1072 #if FEATURE_texture_fxt1
1073 _mesa_init_texture_fxt1( ctx );
1074 #endif
1075
1076 /* Miscellaneous */
1077 ctx->NewState = _NEW_ALL;
1078 ctx->ErrorValue = (GLenum) GL_NO_ERROR;
1079 ctx->varying_vp_inputs = ~0;
1080
1081 return GL_TRUE;
1082 }
1083
1084
1085 /**
1086 * Update default objects in a GL context with respect to shared state.
1087 *
1088 * \param ctx GL context.
1089 *
1090 * Removes references to old default objects, (texture objects, program
1091 * objects, etc.) and changes to reference those from the current shared
1092 * state.
1093 */
1094 static GLboolean
1095 update_default_objects(GLcontext *ctx)
1096 {
1097 assert(ctx);
1098
1099 _mesa_update_default_objects_program(ctx);
1100 _mesa_update_default_objects_texture(ctx);
1101 _mesa_update_default_objects_buffer_objects(ctx);
1102
1103 return GL_TRUE;
1104 }
1105
1106
1107 /**
1108 * This is the default function we plug into all dispatch table slots
1109 * This helps prevents a segfault when someone calls a GL function without
1110 * first checking if the extension's supported.
1111 */
1112 static int
1113 generic_nop(void)
1114 {
1115 _mesa_warning(NULL, "User called no-op dispatch function (an unsupported extension function?)");
1116 return 0;
1117 }
1118
1119
1120 /**
1121 * Allocate and initialize a new dispatch table.
1122 */
1123 static struct _glapi_table *
1124 alloc_dispatch_table(void)
1125 {
1126 /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
1127 * In practice, this'll be the same for stand-alone Mesa. But for DRI
1128 * Mesa we do this to accomodate different versions of libGL and various
1129 * DRI drivers.
1130 */
1131 GLint numEntries = MAX2(_glapi_get_dispatch_table_size(),
1132 sizeof(struct _glapi_table) / sizeof(_glapi_proc));
1133 struct _glapi_table *table =
1134 (struct _glapi_table *) _mesa_malloc(numEntries * sizeof(_glapi_proc));
1135 if (table) {
1136 _glapi_proc *entry = (_glapi_proc *) table;
1137 GLint i;
1138 for (i = 0; i < numEntries; i++) {
1139 entry[i] = (_glapi_proc) generic_nop;
1140 }
1141 }
1142 return table;
1143 }
1144
1145
1146 /**
1147 * Initialize a GLcontext struct (rendering context).
1148 *
1149 * This includes allocating all the other structs and arrays which hang off of
1150 * the context by pointers.
1151 * Note that the driver needs to pass in its dd_function_table here since
1152 * we need to at least call driverFunctions->NewTextureObject to create the
1153 * default texture objects.
1154 *
1155 * Called by _mesa_create_context().
1156 *
1157 * Performs the imports and exports callback tables initialization, and
1158 * miscellaneous one-time initializations. If no shared context is supplied one
1159 * is allocated, and increase its reference count. Setups the GL API dispatch
1160 * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
1161 * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
1162 * for debug flags.
1163 *
1164 * \param ctx the context to initialize
1165 * \param visual describes the visual attributes for this context
1166 * \param share_list points to context to share textures, display lists,
1167 * etc with, or NULL
1168 * \param driverFunctions table of device driver functions for this context
1169 * to use
1170 * \param driverContext pointer to driver-specific context data
1171 */
1172 GLboolean
1173 _mesa_initialize_context(GLcontext *ctx,
1174 const GLvisual *visual,
1175 GLcontext *share_list,
1176 const struct dd_function_table *driverFunctions,
1177 void *driverContext)
1178 {
1179 /*ASSERT(driverContext);*/
1180 assert(driverFunctions->NewTextureObject);
1181 assert(driverFunctions->FreeTexImageData);
1182
1183 /* misc one-time initializations */
1184 one_time_init(ctx);
1185
1186 ctx->Visual = *visual;
1187 ctx->DrawBuffer = NULL;
1188 ctx->ReadBuffer = NULL;
1189 ctx->WinSysDrawBuffer = NULL;
1190 ctx->WinSysReadBuffer = NULL;
1191
1192 /* Plug in driver functions and context pointer here.
1193 * This is important because when we call alloc_shared_state() below
1194 * we'll call ctx->Driver.NewTextureObject() to create the default
1195 * textures.
1196 */
1197 ctx->Driver = *driverFunctions;
1198 ctx->DriverCtx = driverContext;
1199
1200 if (share_list) {
1201 /* share state with another context */
1202 ctx->Shared = share_list->Shared;
1203 }
1204 else {
1205 /* allocate new, unshared state */
1206 if (!alloc_shared_state( ctx )) {
1207 return GL_FALSE;
1208 }
1209 }
1210 _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
1211 ctx->Shared->RefCount++;
1212 _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
1213
1214 if (!init_attrib_groups( ctx )) {
1215 free_shared_state(ctx, ctx->Shared);
1216 return GL_FALSE;
1217 }
1218
1219 /* setup the API dispatch tables */
1220 ctx->Exec = alloc_dispatch_table();
1221 ctx->Save = alloc_dispatch_table();
1222 if (!ctx->Exec || !ctx->Save) {
1223 free_shared_state(ctx, ctx->Shared);
1224 if (ctx->Exec)
1225 _mesa_free(ctx->Exec);
1226 }
1227 #if FEATURE_dispatch
1228 _mesa_init_exec_table(ctx->Exec);
1229 #endif
1230 ctx->CurrentDispatch = ctx->Exec;
1231 #if FEATURE_dlist
1232 _mesa_init_dlist_table(ctx->Save);
1233 _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt );
1234 #endif
1235 /* Neutral tnl module stuff */
1236 _mesa_init_exec_vtxfmt( ctx );
1237 ctx->TnlModule.Current = NULL;
1238 ctx->TnlModule.SwapCount = 0;
1239
1240 ctx->FragmentProgram._MaintainTexEnvProgram
1241 = (_mesa_getenv("MESA_TEX_PROG") != NULL);
1242
1243 ctx->VertexProgram._MaintainTnlProgram
1244 = (_mesa_getenv("MESA_TNL_PROG") != NULL);
1245 if (ctx->VertexProgram._MaintainTnlProgram) {
1246 /* this is required... */
1247 ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
1248 }
1249
1250 #ifdef FEATURE_extra_context_init
1251 _mesa_initialize_context_extra(ctx);
1252 #endif
1253
1254 ctx->FirstTimeCurrent = GL_TRUE;
1255
1256 return GL_TRUE;
1257 }
1258
1259
1260 /**
1261 * Allocate and initialize a GLcontext structure.
1262 * Note that the driver needs to pass in its dd_function_table here since
1263 * we need to at least call driverFunctions->NewTextureObject to initialize
1264 * the rendering context.
1265 *
1266 * \param visual a GLvisual pointer (we copy the struct contents)
1267 * \param share_list another context to share display lists with or NULL
1268 * \param driverFunctions points to the dd_function_table into which the
1269 * driver has plugged in all its special functions.
1270 * \param driverCtx points to the device driver's private context state
1271 *
1272 * \return pointer to a new __GLcontextRec or NULL if error.
1273 */
1274 GLcontext *
1275 _mesa_create_context(const GLvisual *visual,
1276 GLcontext *share_list,
1277 const struct dd_function_table *driverFunctions,
1278 void *driverContext)
1279 {
1280 GLcontext *ctx;
1281
1282 ASSERT(visual);
1283 /*ASSERT(driverContext);*/
1284
1285 ctx = (GLcontext *) _mesa_calloc(sizeof(GLcontext));
1286 if (!ctx)
1287 return NULL;
1288
1289 if (_mesa_initialize_context(ctx, visual, share_list,
1290 driverFunctions, driverContext)) {
1291 return ctx;
1292 }
1293 else {
1294 _mesa_free(ctx);
1295 return NULL;
1296 }
1297 }
1298
1299
1300 /**
1301 * Free the data associated with the given context.
1302 *
1303 * But doesn't free the GLcontext struct itself.
1304 *
1305 * \sa _mesa_initialize_context() and init_attrib_groups().
1306 */
1307 void
1308 _mesa_free_context_data( GLcontext *ctx )
1309 {
1310 if (!_mesa_get_current_context()){
1311 /* No current context, but we may need one in order to delete
1312 * texture objs, etc. So temporarily bind the context now.
1313 */
1314 _mesa_make_current(ctx, NULL, NULL);
1315 }
1316
1317 /* unreference WinSysDraw/Read buffers */
1318 _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
1319 _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
1320 _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
1321 _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
1322
1323 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
1324 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
1325 _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
1326
1327 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
1328 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
1329 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
1330
1331 #if FEATURE_attrib_stack
1332 _mesa_free_attrib_data(ctx);
1333 #endif
1334 _mesa_free_lighting_data( ctx );
1335 #if FEATURE_evaluators
1336 _mesa_free_eval_data( ctx );
1337 #endif
1338 _mesa_free_texture_data( ctx );
1339 _mesa_free_matrix_data( ctx );
1340 _mesa_free_viewport_data( ctx );
1341 #if FEATURE_colortable
1342 _mesa_free_colortables_data( ctx );
1343 #endif
1344 _mesa_free_program_data(ctx);
1345 _mesa_free_shader_state(ctx);
1346 #if FEATURE_ARB_occlusion_query
1347 _mesa_free_query_data(ctx);
1348 #endif
1349
1350 #if FEATURE_ARB_vertex_buffer_object
1351 _mesa_delete_buffer_object(ctx, ctx->Array.NullBufferObj);
1352 #endif
1353 _mesa_delete_array_object(ctx, ctx->Array.DefaultArrayObj);
1354
1355 /* free dispatch tables */
1356 _mesa_free(ctx->Exec);
1357 _mesa_free(ctx->Save);
1358
1359 /* Shared context state (display lists, textures, etc) */
1360 _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
1361 ctx->Shared->RefCount--;
1362 assert(ctx->Shared->RefCount >= 0);
1363 _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
1364 if (ctx->Shared->RefCount == 0) {
1365 /* free shared state */
1366 free_shared_state( ctx, ctx->Shared );
1367 }
1368
1369 if (ctx->Extensions.String)
1370 _mesa_free((void *) ctx->Extensions.String);
1371
1372 /* unbind the context if it's currently bound */
1373 if (ctx == _mesa_get_current_context()) {
1374 _mesa_make_current(NULL, NULL, NULL);
1375 }
1376 }
1377
1378
1379 /**
1380 * Destroy a GLcontext structure.
1381 *
1382 * \param ctx GL context.
1383 *
1384 * Calls _mesa_free_context_data() and frees the GLcontext structure itself.
1385 */
1386 void
1387 _mesa_destroy_context( GLcontext *ctx )
1388 {
1389 if (ctx) {
1390 _mesa_free_context_data(ctx);
1391 _mesa_free( (void *) ctx );
1392 }
1393 }
1394
1395
1396 #if _HAVE_FULL_GL
1397 /**
1398 * Copy attribute groups from one context to another.
1399 *
1400 * \param src source context
1401 * \param dst destination context
1402 * \param mask bitwise OR of GL_*_BIT flags
1403 *
1404 * According to the bits specified in \p mask, copies the corresponding
1405 * attributes from \p src into \p dst. For many of the attributes a simple \c
1406 * memcpy is not enough due to the existence of internal pointers in their data
1407 * structures.
1408 */
1409 void
1410 _mesa_copy_context( const GLcontext *src, GLcontext *dst, GLuint mask )
1411 {
1412 if (mask & GL_ACCUM_BUFFER_BIT) {
1413 /* OK to memcpy */
1414 dst->Accum = src->Accum;
1415 }
1416 if (mask & GL_COLOR_BUFFER_BIT) {
1417 /* OK to memcpy */
1418 dst->Color = src->Color;
1419 }
1420 if (mask & GL_CURRENT_BIT) {
1421 /* OK to memcpy */
1422 dst->Current = src->Current;
1423 }
1424 if (mask & GL_DEPTH_BUFFER_BIT) {
1425 /* OK to memcpy */
1426 dst->Depth = src->Depth;
1427 }
1428 if (mask & GL_ENABLE_BIT) {
1429 /* no op */
1430 }
1431 if (mask & GL_EVAL_BIT) {
1432 /* OK to memcpy */
1433 dst->Eval = src->Eval;
1434 }
1435 if (mask & GL_FOG_BIT) {
1436 /* OK to memcpy */
1437 dst->Fog = src->Fog;
1438 }
1439 if (mask & GL_HINT_BIT) {
1440 /* OK to memcpy */
1441 dst->Hint = src->Hint;
1442 }
1443 if (mask & GL_LIGHTING_BIT) {
1444 GLuint i;
1445 /* begin with memcpy */
1446 dst->Light = src->Light;
1447 /* fixup linked lists to prevent pointer insanity */
1448 make_empty_list( &(dst->Light.EnabledList) );
1449 for (i = 0; i < MAX_LIGHTS; i++) {
1450 if (dst->Light.Light[i].Enabled) {
1451 insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
1452 }
1453 }
1454 }
1455 if (mask & GL_LINE_BIT) {
1456 /* OK to memcpy */
1457 dst->Line = src->Line;
1458 }
1459 if (mask & GL_LIST_BIT) {
1460 /* OK to memcpy */
1461 dst->List = src->List;
1462 }
1463 if (mask & GL_PIXEL_MODE_BIT) {
1464 /* OK to memcpy */
1465 dst->Pixel = src->Pixel;
1466 }
1467 if (mask & GL_POINT_BIT) {
1468 /* OK to memcpy */
1469 dst->Point = src->Point;
1470 }
1471 if (mask & GL_POLYGON_BIT) {
1472 /* OK to memcpy */
1473 dst->Polygon = src->Polygon;
1474 }
1475 if (mask & GL_POLYGON_STIPPLE_BIT) {
1476 /* Use loop instead of MEMCPY due to problem with Portland Group's
1477 * C compiler. Reported by John Stone.
1478 */
1479 GLuint i;
1480 for (i = 0; i < 32; i++) {
1481 dst->PolygonStipple[i] = src->PolygonStipple[i];
1482 }
1483 }
1484 if (mask & GL_SCISSOR_BIT) {
1485 /* OK to memcpy */
1486 dst->Scissor = src->Scissor;
1487 }
1488 if (mask & GL_STENCIL_BUFFER_BIT) {
1489 /* OK to memcpy */
1490 dst->Stencil = src->Stencil;
1491 }
1492 if (mask & GL_TEXTURE_BIT) {
1493 /* Cannot memcpy because of pointers */
1494 _mesa_copy_texture_state(src, dst);
1495 }
1496 if (mask & GL_TRANSFORM_BIT) {
1497 /* OK to memcpy */
1498 dst->Transform = src->Transform;
1499 }
1500 if (mask & GL_VIEWPORT_BIT) {
1501 /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
1502 dst->Viewport.X = src->Viewport.X;
1503 dst->Viewport.Y = src->Viewport.Y;
1504 dst->Viewport.Width = src->Viewport.Width;
1505 dst->Viewport.Height = src->Viewport.Height;
1506 dst->Viewport.Near = src->Viewport.Near;
1507 dst->Viewport.Far = src->Viewport.Far;
1508 _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
1509 }
1510
1511 /* XXX FIXME: Call callbacks?
1512 */
1513 dst->NewState = _NEW_ALL;
1514 }
1515 #endif
1516
1517
1518 /**
1519 * Check if the given context can render into the given framebuffer
1520 * by checking visual attributes.
1521 *
1522 * Most of these tests could go away because Mesa is now pretty flexible
1523 * in terms of mixing rendering contexts with framebuffers. As long
1524 * as RGB vs. CI mode agree, we're probably good.
1525 *
1526 * \return GL_TRUE if compatible, GL_FALSE otherwise.
1527 */
1528 static GLboolean
1529 check_compatible(const GLcontext *ctx, const GLframebuffer *buffer)
1530 {
1531 const GLvisual *ctxvis = &ctx->Visual;
1532 const GLvisual *bufvis = &buffer->Visual;
1533
1534 if (ctxvis == bufvis)
1535 return GL_TRUE;
1536
1537 if (ctxvis->rgbMode != bufvis->rgbMode)
1538 return GL_FALSE;
1539 #if 0
1540 /* disabling this fixes the fgl_glxgears pbuffer demo */
1541 if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
1542 return GL_FALSE;
1543 #endif
1544 if (ctxvis->stereoMode && !bufvis->stereoMode)
1545 return GL_FALSE;
1546 if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
1547 return GL_FALSE;
1548 if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
1549 return GL_FALSE;
1550 if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
1551 return GL_FALSE;
1552 if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
1553 return GL_FALSE;
1554 if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
1555 return GL_FALSE;
1556 if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
1557 return GL_FALSE;
1558 #if 0
1559 /* disabled (see bug 11161) */
1560 if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
1561 return GL_FALSE;
1562 #endif
1563 if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
1564 return GL_FALSE;
1565
1566 return GL_TRUE;
1567 }
1568
1569
1570 /**
1571 * Do one-time initialization for the given framebuffer. Specifically,
1572 * ask the driver for the window's current size and update the framebuffer
1573 * object to match.
1574 * Really, the device driver should totally take care of this.
1575 */
1576 static void
1577 initialize_framebuffer_size(GLcontext *ctx, GLframebuffer *fb)
1578 {
1579 GLuint width, height;
1580 if (ctx->Driver.GetBufferSize) {
1581 ctx->Driver.GetBufferSize(fb, &width, &height);
1582 if (ctx->Driver.ResizeBuffers)
1583 ctx->Driver.ResizeBuffers(ctx, fb, width, height);
1584 fb->Initialized = GL_TRUE;
1585 }
1586 }
1587
1588
1589 /**
1590 * Bind the given context to the given drawBuffer and readBuffer and
1591 * make it the current context for the calling thread.
1592 * We'll render into the drawBuffer and read pixels from the
1593 * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1594 *
1595 * We check that the context's and framebuffer's visuals are compatible
1596 * and return immediately if they're not.
1597 *
1598 * \param newCtx the new GL context. If NULL then there will be no current GL
1599 * context.
1600 * \param drawBuffer the drawing framebuffer
1601 * \param readBuffer the reading framebuffer
1602 */
1603 void
1604 _mesa_make_current( GLcontext *newCtx, GLframebuffer *drawBuffer,
1605 GLframebuffer *readBuffer )
1606 {
1607 if (MESA_VERBOSE & VERBOSE_API)
1608 _mesa_debug(newCtx, "_mesa_make_current()\n");
1609
1610 /* Check that the context's and framebuffer's visuals are compatible.
1611 */
1612 if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1613 if (!check_compatible(newCtx, drawBuffer)) {
1614 _mesa_warning(newCtx,
1615 "MakeCurrent: incompatible visuals for context and drawbuffer");
1616 return;
1617 }
1618 }
1619 if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1620 if (!check_compatible(newCtx, readBuffer)) {
1621 _mesa_warning(newCtx,
1622 "MakeCurrent: incompatible visuals for context and readbuffer");
1623 return;
1624 }
1625 }
1626
1627 /* We used to call _glapi_check_multithread() here. Now do it in drivers */
1628 _glapi_set_context((void *) newCtx);
1629 ASSERT(_mesa_get_current_context() == newCtx);
1630
1631 if (!newCtx) {
1632 _glapi_set_dispatch(NULL); /* none current */
1633 }
1634 else {
1635 _glapi_set_dispatch(newCtx->CurrentDispatch);
1636
1637 if (drawBuffer && readBuffer) {
1638 /* TODO: check if newCtx and buffer's visual match??? */
1639
1640 ASSERT(drawBuffer->Name == 0);
1641 ASSERT(readBuffer->Name == 0);
1642 _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1643 _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1644
1645 /*
1646 * Only set the context's Draw/ReadBuffer fields if they're NULL
1647 * or not bound to a user-created FBO.
1648 */
1649 if (!newCtx->DrawBuffer || newCtx->DrawBuffer->Name == 0) {
1650 /* KW: merge conflict here, revisit.
1651 */
1652 /* fix up the fb fields - these will end up wrong otherwise
1653 * if the DRIdrawable changes, and everything relies on them.
1654 * This is a bit messy (same as needed in _mesa_BindFramebufferEXT)
1655 */
1656 unsigned int i;
1657 GLenum buffers[MAX_DRAW_BUFFERS];
1658
1659 _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1660
1661 for(i = 0; i < newCtx->Const.MaxDrawBuffers; i++) {
1662 buffers[i] = newCtx->Color.DrawBuffer[i];
1663 }
1664
1665 _mesa_drawbuffers(newCtx, newCtx->Const.MaxDrawBuffers, buffers, NULL);
1666 }
1667 if (!newCtx->ReadBuffer || newCtx->ReadBuffer->Name == 0) {
1668 _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1669 }
1670
1671 /* XXX only set this flag if we're really changing the draw/read
1672 * framebuffer bindings.
1673 */
1674 newCtx->NewState |= _NEW_BUFFERS;
1675
1676 #if 1
1677 /* We want to get rid of these lines: */
1678
1679 #if _HAVE_FULL_GL
1680 if (!drawBuffer->Initialized) {
1681 initialize_framebuffer_size(newCtx, drawBuffer);
1682 }
1683 if (readBuffer != drawBuffer && !readBuffer->Initialized) {
1684 initialize_framebuffer_size(newCtx, readBuffer);
1685 }
1686
1687 _mesa_resizebuffers(newCtx);
1688 #endif
1689
1690 #else
1691 /* We want the drawBuffer and readBuffer to be initialized by
1692 * the driver.
1693 * This generally means the Width and Height match the actual
1694 * window size and the renderbuffers (both hardware and software
1695 * based) are allocated to match. The later can generally be
1696 * done with a call to _mesa_resize_framebuffer().
1697 *
1698 * It's theoretically possible for a buffer to have zero width
1699 * or height, but for now, assert check that the driver did what's
1700 * expected of it.
1701 */
1702 ASSERT(drawBuffer->Width > 0);
1703 ASSERT(drawBuffer->Height > 0);
1704 #endif
1705
1706 if (newCtx->FirstTimeCurrent) {
1707 /* set initial viewport and scissor size now */
1708 _mesa_set_viewport(newCtx, 0, 0,
1709 drawBuffer->Width, drawBuffer->Height);
1710 _mesa_set_scissor(newCtx, 0, 0,
1711 drawBuffer->Width, drawBuffer->Height );
1712 check_context_limits(newCtx);
1713 }
1714 }
1715
1716 /* We can use this to help debug user's problems. Tell them to set
1717 * the MESA_INFO env variable before running their app. Then the
1718 * first time each context is made current we'll print some useful
1719 * information.
1720 */
1721 if (newCtx->FirstTimeCurrent) {
1722 if (_mesa_getenv("MESA_INFO")) {
1723 _mesa_print_info();
1724 }
1725 newCtx->FirstTimeCurrent = GL_FALSE;
1726 }
1727 }
1728 }
1729
1730
1731 /**
1732 * Make context 'ctx' share the display lists, textures and programs
1733 * that are associated with 'ctxToShare'.
1734 * Any display lists, textures or programs associated with 'ctx' will
1735 * be deleted if nobody else is sharing them.
1736 */
1737 GLboolean
1738 _mesa_share_state(GLcontext *ctx, GLcontext *ctxToShare)
1739 {
1740 if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1741 struct gl_shared_state *oldSharedState = ctx->Shared;
1742
1743 ctx->Shared = ctxToShare->Shared;
1744 ctx->Shared->RefCount++;
1745
1746 update_default_objects(ctx);
1747
1748 oldSharedState->RefCount--;
1749 if (oldSharedState->RefCount == 0) {
1750 free_shared_state(ctx, oldSharedState);
1751 }
1752
1753 return GL_TRUE;
1754 }
1755 else {
1756 return GL_FALSE;
1757 }
1758 }
1759
1760
1761
1762 /**
1763 * \return pointer to the current GL context for this thread.
1764 *
1765 * Calls _glapi_get_context(). This isn't the fastest way to get the current
1766 * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
1767 * context.h.
1768 */
1769 GLcontext *
1770 _mesa_get_current_context( void )
1771 {
1772 return (GLcontext *) _glapi_get_context();
1773 }
1774
1775
1776 /**
1777 * Get context's current API dispatch table.
1778 *
1779 * It'll either be the immediate-mode execute dispatcher or the display list
1780 * compile dispatcher.
1781 *
1782 * \param ctx GL context.
1783 *
1784 * \return pointer to dispatch_table.
1785 *
1786 * Simply returns __GLcontextRec::CurrentDispatch.
1787 */
1788 struct _glapi_table *
1789 _mesa_get_dispatch(GLcontext *ctx)
1790 {
1791 return ctx->CurrentDispatch;
1792 }
1793
1794 /*@}*/
1795
1796
1797 /**********************************************************************/
1798 /** \name Miscellaneous functions */
1799 /**********************************************************************/
1800 /*@{*/
1801
1802 /**
1803 * Record an error.
1804 *
1805 * \param ctx GL context.
1806 * \param error error code.
1807 *
1808 * Records the given error code and call the driver's dd_function_table::Error
1809 * function if defined.
1810 *
1811 * \sa
1812 * This is called via _mesa_error().
1813 */
1814 void
1815 _mesa_record_error(GLcontext *ctx, GLenum error)
1816 {
1817 if (!ctx)
1818 return;
1819
1820 if (ctx->ErrorValue == GL_NO_ERROR) {
1821 ctx->ErrorValue = error;
1822 }
1823
1824 /* Call device driver's error handler, if any. This is used on the Mac. */
1825 if (ctx->Driver.Error) {
1826 ctx->Driver.Error(ctx);
1827 }
1828 }
1829
1830
1831 /**
1832 * Execute glFinish().
1833 *
1834 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1835 * dd_function_table::Finish driver callback, if not NULL.
1836 */
1837 void GLAPIENTRY
1838 _mesa_Finish(void)
1839 {
1840 GET_CURRENT_CONTEXT(ctx);
1841 ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
1842 if (ctx->Driver.Finish) {
1843 ctx->Driver.Finish(ctx);
1844 }
1845 }
1846
1847
1848 /**
1849 * Execute glFlush().
1850 *
1851 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1852 * dd_function_table::Flush driver callback, if not NULL.
1853 */
1854 void GLAPIENTRY
1855 _mesa_Flush(void)
1856 {
1857 GET_CURRENT_CONTEXT(ctx);
1858 ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
1859 if (ctx->Driver.Flush) {
1860 ctx->Driver.Flush(ctx);
1861 }
1862 }
1863
1864
1865 /*@}*/