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