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