1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
5 * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a
8 * copy of this software and associated documentation files (the "Software"),
9 * to deal in the Software without restriction, including without limitation
10 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 * and/or sell copies of the Software, and to permit persons to whom the
12 * Software is furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 * 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
81 #include "accum.h"
82 #include "arrayobj.h"
83 #include "attrib.h"
84 #include "bbox.h"
85 #include "blend.h"
86 #include "buffers.h"
87 #include "bufferobj.h"
88 #include "conservativeraster.h"
89 #include "context.h"
90 #include "cpuinfo.h"
91 #include "debug.h"
92 #include "debug_output.h"
93 #include "depth.h"
94 #include "dlist.h"
95 #include "draw_validate.h"
96 #include "eval.h"
97 #include "extensions.h"
98 #include "fbobject.h"
99 #include "feedback.h"
100 #include "fog.h"
101 #include "formats.h"
102 #include "framebuffer.h"
103 #include "glthread.h"
104 #include "hint.h"
105 #include "hash.h"
106 #include "light.h"
107 #include "lines.h"
108 #include "macros.h"
109 #include "matrix.h"
110 #include "multisample.h"
111 #include "performance_monitor.h"
112 #include "performance_query.h"
113 #include "pipelineobj.h"
114 #include "pixel.h"
115 #include "pixelstore.h"
116 #include "points.h"
117 #include "polygon.h"
118 #include "queryobj.h"
119 #include "syncobj.h"
120 #include "rastpos.h"
121 #include "remap.h"
122 #include "scissor.h"
123 #include "shared.h"
124 #include "shaderobj.h"
125 #include "shaderimage.h"
126 #include "state.h"
127 #include "util/debug.h"
128 #include "util/disk_cache.h"
129 #include "util/strtod.h"
130 #include "stencil.h"
131 #include "shaderimage.h"
132 #include "texcompress_s3tc.h"
133 #include "texstate.h"
134 #include "transformfeedback.h"
135 #include "mtypes.h"
136 #include "varray.h"
137 #include "version.h"
138 #include "viewport.h"
139 #include "texturebindless.h"
140 #include "program/program.h"
141 #include "math/m_matrix.h"
142 #include "main/dispatch.h" /* for _gloffset_COUNT */
143 #include "macros.h"
144 #include "git_sha1.h"
145
146 #include "compiler/glsl_types.h"
147 #include "compiler/glsl/builtin_functions.h"
148 #include "compiler/glsl/glsl_parser_extras.h"
149 #include <stdbool.h>
150 #include "util/u_memory.h"
151 #include "api_exec_decl.h"
152
153 #include "state_tracker/st_cb_texture.h"
154 #include "state_tracker/st_cb_flush.h"
155
156 #ifndef MESA_VERBOSE
157 int MESA_VERBOSE = 0;
158 #endif
159
160 #ifndef MESA_DEBUG_FLAGS
161 int MESA_DEBUG_FLAGS = 0;
162 #endif
163
164
165 /* ubyte -> float conversion */
166 GLfloat _mesa_ubyte_to_float_color_tab[256];
167
168
169 /**********************************************************************/
170 /** \name Context allocation, initialization, destroying
171 *
172 * The purpose of the most initialization functions here is to provide the
173 * default state values according to the OpenGL specification.
174 */
175 /**********************************************************************/
176 /*@{*/
177
178
179 /**
180 * Calls all the various one-time-fini functions in Mesa
181 */
182
183 static void
one_time_fini(void)184 one_time_fini(void)
185 {
186 glsl_type_singleton_decref();
187 _mesa_locale_fini();
188 }
189
190 /**
191 * Calls all the various one-time-init functions in Mesa
192 */
193
194 static void
one_time_init(const char * extensions_override)195 one_time_init(const char *extensions_override)
196 {
197 GLuint i;
198
199 STATIC_ASSERT(sizeof(GLbyte) == 1);
200 STATIC_ASSERT(sizeof(GLubyte) == 1);
201 STATIC_ASSERT(sizeof(GLshort) == 2);
202 STATIC_ASSERT(sizeof(GLushort) == 2);
203 STATIC_ASSERT(sizeof(GLint) == 4);
204 STATIC_ASSERT(sizeof(GLuint) == 4);
205
206 _mesa_locale_init();
207
208 const char *env_const = os_get_option("MESA_EXTENSION_OVERRIDE");
209 if (env_const) {
210 if (extensions_override &&
211 strcmp(extensions_override, env_const)) {
212 printf("Warning: MESA_EXTENSION_OVERRIDE used instead of driconf setting\n");
213 }
214 extensions_override = env_const;
215 }
216
217 _mesa_one_time_init_extension_overrides(extensions_override);
218
219 _mesa_get_cpu_features();
220
221 for (i = 0; i < 256; i++) {
222 _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
223 }
224
225 atexit(one_time_fini);
226
227 #if defined(DEBUG)
228 if (MESA_VERBOSE != 0) {
229 _mesa_debug(NULL, "Mesa " PACKAGE_VERSION " DEBUG build" MESA_GIT_SHA1 "\n");
230 }
231 #endif
232
233 /* Take a glsl type reference for the duration of libGL's life to avoid
234 * unecessary creation/destruction of glsl types.
235 */
236 glsl_type_singleton_init_or_ref();
237
238 _mesa_init_remap_table();
239 }
240
241 /**
242 * One-time initialization flag
243 *
244 * \sa Used by _mesa_initialize().
245 */
246 static bool init_done = false;
247 static mtx_t init_once_lock;
248 static once_flag init_once = ONCE_FLAG_INIT;
249
init_lock(void)250 static void init_lock(void) {
251 mtx_init(&init_once_lock, mtx_plain);
252 }
253
254
255 /**
256 * Calls all the various one-time-init functions in Mesa.
257 *
258 * While holding a global mutex lock, calls several initialization functions,
259 * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
260 * defined.
261 */
262 void
_mesa_initialize(const char * extensions_override)263 _mesa_initialize(const char *extensions_override)
264 {
265 call_once(&init_once, init_lock);
266
267 mtx_lock(&init_once_lock);
268 if (!init_done) {
269 one_time_init(extensions_override);
270 init_done = true;
271 }
272 mtx_unlock(&init_once_lock);
273 }
274
275
276 /**
277 * Initialize fields of gl_current_attrib (aka ctx->Current.*)
278 */
279 static void
_mesa_init_current(struct gl_context * ctx)280 _mesa_init_current(struct gl_context *ctx)
281 {
282 GLuint i;
283
284 /* Init all to (0,0,0,1) */
285 for (i = 0; i < ARRAY_SIZE(ctx->Current.Attrib); i++) {
286 ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
287 }
288
289 /* redo special cases: */
290 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
291 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
292 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
293 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
294 ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
295 }
296
297
298 /**
299 * Init vertex/fragment/geometry program limits.
300 * Important: drivers should override these with actual limits.
301 */
302 static void
init_program_limits(struct gl_constants * consts,gl_shader_stage stage,struct gl_program_constants * prog)303 init_program_limits(struct gl_constants *consts, gl_shader_stage stage,
304 struct gl_program_constants *prog)
305 {
306 prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
307 prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
308 prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
309 prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
310 prog->MaxTemps = MAX_PROGRAM_TEMPS;
311 prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
312 prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
313 prog->MaxAddressOffset = MAX_PROGRAM_LOCAL_PARAMS;
314
315 switch (stage) {
316 case MESA_SHADER_VERTEX:
317 prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
318 prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
319 prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
320 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
321 prog->MaxInputComponents = 0; /* value not used */
322 prog->MaxOutputComponents = 16 * 4; /* old limit not to break tnl and swrast */
323 break;
324 case MESA_SHADER_FRAGMENT:
325 prog->MaxParameters = MAX_FRAGMENT_PROGRAM_PARAMS;
326 prog->MaxAttribs = MAX_FRAGMENT_PROGRAM_INPUTS;
327 prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
328 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
329 prog->MaxInputComponents = 16 * 4; /* old limit not to break tnl and swrast */
330 prog->MaxOutputComponents = 0; /* value not used */
331 break;
332 case MESA_SHADER_TESS_CTRL:
333 case MESA_SHADER_TESS_EVAL:
334 case MESA_SHADER_GEOMETRY:
335 prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
336 prog->MaxAttribs = MAX_VERTEX_GENERIC_ATTRIBS;
337 prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
338 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
339 prog->MaxInputComponents = 16 * 4; /* old limit not to break tnl and swrast */
340 prog->MaxOutputComponents = 16 * 4; /* old limit not to break tnl and swrast */
341 break;
342 case MESA_SHADER_COMPUTE:
343 prog->MaxParameters = 0; /* not meaningful for compute shaders */
344 prog->MaxAttribs = 0; /* not meaningful for compute shaders */
345 prog->MaxAddressRegs = 0; /* not meaningful for compute shaders */
346 prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
347 prog->MaxInputComponents = 0; /* not meaningful for compute shaders */
348 prog->MaxOutputComponents = 0; /* not meaningful for compute shaders */
349 break;
350 default:
351 assert(0 && "Bad shader stage in init_program_limits()");
352 }
353
354 /* Set the native limits to zero. This implies that there is no native
355 * support for shaders. Let the drivers fill in the actual values.
356 */
357 prog->MaxNativeInstructions = 0;
358 prog->MaxNativeAluInstructions = 0;
359 prog->MaxNativeTexInstructions = 0;
360 prog->MaxNativeTexIndirections = 0;
361 prog->MaxNativeAttribs = 0;
362 prog->MaxNativeTemps = 0;
363 prog->MaxNativeAddressRegs = 0;
364 prog->MaxNativeParameters = 0;
365
366 /* Set GLSL datatype range/precision info assuming IEEE float values.
367 * Drivers should override these defaults as needed.
368 */
369 prog->MediumFloat.RangeMin = 127;
370 prog->MediumFloat.RangeMax = 127;
371 prog->MediumFloat.Precision = 23;
372 prog->LowFloat = prog->HighFloat = prog->MediumFloat;
373
374 /* Assume ints are stored as floats for now, since this is the least-common
375 * denominator. The OpenGL ES spec implies (page 132) that the precision
376 * of integer types should be 0. Practically speaking, IEEE
377 * single-precision floating point values can only store integers in the
378 * range [-0x01000000, 0x01000000] without loss of precision.
379 */
380 prog->MediumInt.RangeMin = 24;
381 prog->MediumInt.RangeMax = 24;
382 prog->MediumInt.Precision = 0;
383 prog->LowInt = prog->HighInt = prog->MediumInt;
384
385 prog->MaxUniformBlocks = 12;
386 prog->MaxCombinedUniformComponents = (prog->MaxUniformComponents +
387 consts->MaxUniformBlockSize / 4 *
388 prog->MaxUniformBlocks);
389
390 prog->MaxAtomicBuffers = 0;
391 prog->MaxAtomicCounters = 0;
392
393 prog->MaxShaderStorageBlocks = 8;
394 }
395
396
397 /**
398 * Initialize fields of gl_constants (aka ctx->Const.*).
399 * Use defaults from config.h. The device drivers will often override
400 * some of these values (such as number of texture units).
401 */
402 void
_mesa_init_constants(struct gl_constants * consts,gl_api api)403 _mesa_init_constants(struct gl_constants *consts, gl_api api)
404 {
405 int i;
406 assert(consts);
407
408 /* Constants, may be overriden (usually only reduced) by device drivers */
409 consts->MaxTextureMbytes = MAX_TEXTURE_MBYTES;
410 consts->MaxTextureSize = 1 << (MAX_TEXTURE_LEVELS - 1);
411 consts->Max3DTextureLevels = MAX_TEXTURE_LEVELS;
412 consts->MaxCubeTextureLevels = MAX_TEXTURE_LEVELS;
413 consts->MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
414 consts->MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
415 consts->MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
416 consts->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
417 consts->MaxTextureUnits = MIN2(consts->MaxTextureCoordUnits,
418 consts->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
419 consts->MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
420 consts->MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
421 consts->MaxTextureBufferSize = 65536;
422 consts->TextureBufferOffsetAlignment = 1;
423 consts->MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
424 consts->SubPixelBits = SUB_PIXEL_BITS;
425 consts->MinPointSize = MIN_POINT_SIZE;
426 consts->MaxPointSize = MAX_POINT_SIZE;
427 consts->MinPointSizeAA = MIN_POINT_SIZE;
428 consts->MaxPointSizeAA = MAX_POINT_SIZE;
429 consts->PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
430 consts->MinLineWidth = MIN_LINE_WIDTH;
431 consts->MaxLineWidth = MAX_LINE_WIDTH;
432 consts->MinLineWidthAA = MIN_LINE_WIDTH;
433 consts->MaxLineWidthAA = MAX_LINE_WIDTH;
434 consts->LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
435 consts->MaxClipPlanes = 6;
436 consts->MaxLights = MAX_LIGHTS;
437 consts->MaxShininess = 128.0;
438 consts->MaxSpotExponent = 128.0;
439 consts->MaxViewportWidth = 16384;
440 consts->MaxViewportHeight = 16384;
441 consts->MinMapBufferAlignment = 64;
442
443 /* Driver must override these values if ARB_viewport_array is supported. */
444 consts->MaxViewports = 1;
445 consts->ViewportSubpixelBits = 0;
446 consts->ViewportBounds.Min = 0;
447 consts->ViewportBounds.Max = 0;
448
449 /** GL_ARB_uniform_buffer_object */
450 consts->MaxCombinedUniformBlocks = 36;
451 consts->MaxUniformBufferBindings = 36;
452 consts->MaxUniformBlockSize = 16384;
453 consts->UniformBufferOffsetAlignment = 1;
454
455 /** GL_ARB_shader_storage_buffer_object */
456 consts->MaxCombinedShaderStorageBlocks = 8;
457 consts->MaxShaderStorageBufferBindings = 8;
458 consts->MaxShaderStorageBlockSize = 128 * 1024 * 1024; /* 2^27 */
459 consts->ShaderStorageBufferOffsetAlignment = 256;
460
461 /* GL_ARB_explicit_uniform_location, GL_MAX_UNIFORM_LOCATIONS */
462 consts->MaxUserAssignableUniformLocations =
463 4 * MESA_SHADER_STAGES * MAX_UNIFORMS;
464
465 for (i = 0; i < MESA_SHADER_STAGES; i++)
466 init_program_limits(consts, i, &consts->Program[i]);
467
468 consts->MaxProgramMatrices = MAX_PROGRAM_MATRICES;
469 consts->MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
470
471 /* Set the absolute minimum possible GLSL version. API_OPENGL_CORE can
472 * mean an OpenGL 3.0 forward-compatible context, so that implies a minimum
473 * possible version of 1.30. Otherwise, the minimum possible version 1.20.
474 * Since Mesa unconditionally advertises GL_ARB_shading_language_100 and
475 * GL_ARB_shader_objects, every driver has GLSL 1.20... even if they don't
476 * advertise any extensions to enable any shader stages (e.g.,
477 * GL_ARB_vertex_shader).
478 */
479 consts->GLSLVersion = api == API_OPENGL_CORE ? 130 : 120;
480 consts->GLSLVersionCompat = consts->GLSLVersion;
481
482 consts->GLSLLowerConstArrays = true;
483
484 /* Assume that if GLSL 1.30+ (or GLSL ES 3.00+) is supported that
485 * gl_VertexID is implemented using a native hardware register with OpenGL
486 * semantics.
487 */
488 consts->VertexID_is_zero_based = false;
489
490 /* GL_ARB_draw_buffers */
491 consts->MaxDrawBuffers = MAX_DRAW_BUFFERS;
492
493 consts->MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
494 consts->MaxRenderbufferSize = MAX_RENDERBUFFER_SIZE;
495
496 consts->Program[MESA_SHADER_VERTEX].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
497 consts->MaxCombinedTextureImageUnits = MAX_COMBINED_TEXTURE_IMAGE_UNITS;
498 consts->MaxVarying = 16; /* old limit not to break tnl and swrast */
499 consts->Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
500 consts->MaxGeometryOutputVertices = MAX_GEOMETRY_OUTPUT_VERTICES;
501 consts->MaxGeometryTotalOutputComponents = MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS;
502 consts->MaxGeometryShaderInvocations = MAX_GEOMETRY_SHADER_INVOCATIONS;
503
504 #ifdef DEBUG
505 consts->GenerateTemporaryNames = true;
506 #else
507 consts->GenerateTemporaryNames = false;
508 #endif
509
510 /* GL_ARB_framebuffer_object */
511 consts->MaxSamples = 0;
512
513 /* GLSL default if NativeIntegers == FALSE */
514 consts->UniformBooleanTrue = FLOAT_AS_UNION(1.0f).u;
515
516 /* GL_ARB_sync */
517 consts->MaxServerWaitTimeout = 0x7fffffff7fffffffULL;
518
519 /* GL_EXT_provoking_vertex */
520 consts->QuadsFollowProvokingVertexConvention = GL_TRUE;
521
522 /** GL_ARB_viewport_array */
523 consts->LayerAndVPIndexProvokingVertex = GL_UNDEFINED_VERTEX;
524
525 /* GL_EXT_transform_feedback */
526 consts->MaxTransformFeedbackBuffers = MAX_FEEDBACK_BUFFERS;
527 consts->MaxTransformFeedbackSeparateComponents = 4 * MAX_FEEDBACK_ATTRIBS;
528 consts->MaxTransformFeedbackInterleavedComponents = 4 * MAX_FEEDBACK_ATTRIBS;
529 consts->MaxVertexStreams = 1;
530
531 /* GL 3.2 */
532 consts->ProfileMask = api == API_OPENGL_CORE
533 ? GL_CONTEXT_CORE_PROFILE_BIT
534 : GL_CONTEXT_COMPATIBILITY_PROFILE_BIT;
535
536 /* GL 4.4 */
537 consts->MaxVertexAttribStride = 2048;
538
539 /** GL_EXT_gpu_shader4 */
540 consts->MinProgramTexelOffset = -8;
541 consts->MaxProgramTexelOffset = 7;
542
543 /* GL_ARB_texture_gather */
544 consts->MinProgramTextureGatherOffset = -8;
545 consts->MaxProgramTextureGatherOffset = 7;
546
547 /* GL_ARB_robustness */
548 consts->ResetStrategy = GL_NO_RESET_NOTIFICATION_ARB;
549
550 /* GL_KHR_robustness */
551 consts->RobustAccess = GL_FALSE;
552
553 /* ES 3.0 or ARB_ES3_compatibility */
554 consts->MaxElementIndex = 0xffffffffu;
555
556 /* GL_ARB_texture_multisample */
557 consts->MaxColorTextureSamples = 1;
558 consts->MaxDepthTextureSamples = 1;
559 consts->MaxIntegerSamples = 1;
560
561 /* GL_ARB_shader_atomic_counters */
562 consts->MaxAtomicBufferBindings = MAX_COMBINED_ATOMIC_BUFFERS;
563 consts->MaxAtomicBufferSize = MAX_ATOMIC_COUNTERS * ATOMIC_COUNTER_SIZE;
564 consts->MaxCombinedAtomicBuffers = MAX_COMBINED_ATOMIC_BUFFERS;
565 consts->MaxCombinedAtomicCounters = MAX_ATOMIC_COUNTERS;
566
567 /* GL_ARB_vertex_attrib_binding */
568 consts->MaxVertexAttribRelativeOffset = 2047;
569 consts->MaxVertexAttribBindings = MAX_VERTEX_GENERIC_ATTRIBS;
570
571 /* GL_ARB_compute_shader */
572 consts->MaxComputeWorkGroupCount[0] = 65535;
573 consts->MaxComputeWorkGroupCount[1] = 65535;
574 consts->MaxComputeWorkGroupCount[2] = 65535;
575 consts->MaxComputeWorkGroupSize[0] = 1024;
576 consts->MaxComputeWorkGroupSize[1] = 1024;
577 consts->MaxComputeWorkGroupSize[2] = 64;
578 /* Enables compute support for GLES 3.1 if >= 128 */
579 consts->MaxComputeWorkGroupInvocations = 0;
580
581 /** GL_ARB_gpu_shader5 */
582 consts->MinFragmentInterpolationOffset = MIN_FRAGMENT_INTERPOLATION_OFFSET;
583 consts->MaxFragmentInterpolationOffset = MAX_FRAGMENT_INTERPOLATION_OFFSET;
584
585 /** GL_KHR_context_flush_control */
586 consts->ContextReleaseBehavior = GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH;
587
588 /** GL_ARB_tessellation_shader */
589 consts->MaxTessGenLevel = MAX_TESS_GEN_LEVEL;
590 consts->MaxPatchVertices = MAX_PATCH_VERTICES;
591 consts->Program[MESA_SHADER_TESS_CTRL].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
592 consts->Program[MESA_SHADER_TESS_EVAL].MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
593 consts->MaxTessPatchComponents = MAX_TESS_PATCH_COMPONENTS;
594 consts->MaxTessControlTotalOutputComponents = MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS;
595 consts->PrimitiveRestartForPatches = false;
596
597 /** GL_ARB_compute_variable_group_size */
598 consts->MaxComputeVariableGroupSize[0] = 512;
599 consts->MaxComputeVariableGroupSize[1] = 512;
600 consts->MaxComputeVariableGroupSize[2] = 64;
601 consts->MaxComputeVariableGroupInvocations = 512;
602
603 /** GL_NV_conservative_raster */
604 consts->MaxSubpixelPrecisionBiasBits = 0;
605
606 /** GL_NV_conservative_raster_dilate */
607 consts->ConservativeRasterDilateRange[0] = 0.0;
608 consts->ConservativeRasterDilateRange[1] = 0.0;
609 consts->ConservativeRasterDilateGranularity = 0.0;
610
611 consts->glBeginEndBufferSize = 512 * 1024;
612 }
613
614
615 /**
616 * Do some sanity checks on the limits/constants for the given context.
617 * Only called the first time a context is bound.
618 */
619 static void
check_context_limits(struct gl_context * ctx)620 check_context_limits(struct gl_context *ctx)
621 {
622 (void) ctx;
623
624 /* check that we don't exceed the size of various bitfields */
625 assert(VARYING_SLOT_MAX <=
626 (8 * sizeof(ctx->VertexProgram._Current->info.outputs_written)));
627 assert(VARYING_SLOT_MAX <=
628 (8 * sizeof(ctx->FragmentProgram._Current->info.inputs_read)));
629
630 /* shader-related checks */
631 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
632 assert(ctx->Const.Program[MESA_SHADER_VERTEX].MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
633
634 /* Texture unit checks */
635 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits > 0);
636 assert(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
637 assert(ctx->Const.MaxTextureCoordUnits > 0);
638 assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
639 assert(ctx->Const.MaxTextureUnits > 0);
640 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
641 assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
642 assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits,
643 ctx->Const.MaxTextureCoordUnits));
644 assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
645 assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
646 assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
647 /* number of coord units cannot be greater than number of image units */
648 assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
649
650
651 /* Texture size checks */
652 assert(ctx->Const.MaxTextureSize <= (1 << (MAX_TEXTURE_LEVELS - 1)));
653 assert(ctx->Const.Max3DTextureLevels <= MAX_TEXTURE_LEVELS);
654 assert(ctx->Const.MaxCubeTextureLevels <= MAX_TEXTURE_LEVELS);
655 assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
656
657 /* Max texture size should be <= max viewport size (render to texture) */
658 assert(ctx->Const.MaxTextureSize <= ctx->Const.MaxViewportWidth);
659 assert(ctx->Const.MaxTextureSize <= ctx->Const.MaxViewportHeight);
660
661 assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
662
663 /* if this fails, add more enum values to gl_buffer_index */
664 assert(BUFFER_COLOR0 + MAX_DRAW_BUFFERS <= BUFFER_COUNT);
665
666 /* XXX probably add more tests */
667 }
668
669
670 /**
671 * Initialize the attribute groups in a GL context.
672 *
673 * \param ctx GL context.
674 *
675 * Initializes all the attributes, calling the respective <tt>init*</tt>
676 * functions for the more complex data structures.
677 */
678 static GLboolean
init_attrib_groups(struct gl_context * ctx)679 init_attrib_groups(struct gl_context *ctx)
680 {
681 assert(ctx);
682
683 /* Constants */
684 _mesa_init_constants(&ctx->Const, ctx->API);
685
686 /* Extensions */
687 _mesa_init_extensions(&ctx->Extensions);
688
689 /* Attribute Groups */
690 _mesa_init_accum( ctx );
691 _mesa_init_attrib( ctx );
692 _mesa_init_bbox( ctx );
693 _mesa_init_buffer_objects( ctx );
694 _mesa_init_color( ctx );
695 _mesa_init_conservative_raster( ctx );
696 _mesa_init_current( ctx );
697 _mesa_init_depth( ctx );
698 _mesa_init_debug( ctx );
699 _mesa_init_debug_output( ctx );
700 _mesa_init_display_list( ctx );
701 _mesa_init_eval( ctx );
702 _mesa_init_feedback( ctx );
703 _mesa_init_fog( ctx );
704 _mesa_init_hint( ctx );
705 _mesa_init_image_units( ctx );
706 _mesa_init_line( ctx );
707 _mesa_init_lighting( ctx );
708 _mesa_init_matrix( ctx );
709 _mesa_init_multisample( ctx );
710 _mesa_init_performance_monitors( ctx );
711 _mesa_init_performance_queries( ctx );
712 _mesa_init_pipeline( ctx );
713 _mesa_init_pixel( ctx );
714 _mesa_init_pixelstore( ctx );
715 _mesa_init_point( ctx );
716 _mesa_init_polygon( ctx );
717 _mesa_init_program( ctx );
718 _mesa_init_queryobj( ctx );
719 _mesa_init_sync( ctx );
720 _mesa_init_rastpos( ctx );
721 _mesa_init_scissor( ctx );
722 _mesa_init_shader_state( ctx );
723 _mesa_init_stencil( ctx );
724 _mesa_init_transform( ctx );
725 _mesa_init_transform_feedback( ctx );
726 _mesa_init_varray( ctx );
727 _mesa_init_viewport( ctx );
728 _mesa_init_resident_handles( ctx );
729
730 if (!_mesa_init_texture( ctx ))
731 return GL_FALSE;
732
733 /* Miscellaneous */
734 ctx->TileRasterOrderIncreasingX = GL_TRUE;
735 ctx->TileRasterOrderIncreasingY = GL_TRUE;
736 ctx->NewState = _NEW_ALL;
737 ctx->NewDriverState = ~0;
738 ctx->ErrorValue = GL_NO_ERROR;
739 ctx->ShareGroupReset = false;
740 ctx->VertexProgram._VaryingInputs = VERT_BIT_ALL;
741 ctx->IntelBlackholeRender = env_var_as_boolean("INTEL_BLACKHOLE_DEFAULT", false);
742
743 return GL_TRUE;
744 }
745
746
747 /**
748 * Update default objects in a GL context with respect to shared state.
749 *
750 * \param ctx GL context.
751 *
752 * Removes references to old default objects, (texture objects, program
753 * objects, etc.) and changes to reference those from the current shared
754 * state.
755 */
756 static GLboolean
update_default_objects(struct gl_context * ctx)757 update_default_objects(struct gl_context *ctx)
758 {
759 assert(ctx);
760
761 _mesa_update_default_objects_program(ctx);
762 _mesa_update_default_objects_texture(ctx);
763 _mesa_update_default_objects_buffer_objects(ctx);
764
765 return GL_TRUE;
766 }
767
768
769 /* XXX this is temporary and should be removed at some point in the
770 * future when there's a reasonable expectation that the libGL library
771 * contains the _glapi_new_nop_table() and _glapi_set_nop_handler()
772 * functions which were added in Mesa 10.6.
773 */
774 #if !defined(_WIN32)
775 /* Avoid libGL / driver ABI break */
776 #define USE_GLAPI_NOP_FEATURES 0
777 #else
778 #define USE_GLAPI_NOP_FEATURES 1
779 #endif
780
781
782 /**
783 * This function is called by the glapi no-op functions. For each OpenGL
784 * function/entrypoint there's a simple no-op function. These "no-op"
785 * functions call this function.
786 *
787 * If there's a current OpenGL context for the calling thread, we record a
788 * GL_INVALID_OPERATION error. This can happen either because the app's
789 * calling an unsupported extension function, or calling an illegal function
790 * (such as glClear between glBegin/glEnd).
791 *
792 * If there's no current OpenGL context for the calling thread, we can
793 * print a message to stderr.
794 *
795 * \param name the name of the OpenGL function
796 */
797 #if USE_GLAPI_NOP_FEATURES
798 static void
nop_handler(const char * name)799 nop_handler(const char *name)
800 {
801 GET_CURRENT_CONTEXT(ctx);
802 if (ctx) {
803 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(invalid call)", name);
804 }
805 #ifndef NDEBUG
806 else if (getenv("MESA_DEBUG") || getenv("LIBGL_DEBUG")) {
807 fprintf(stderr,
808 "GL User Error: gl%s called without a rendering context\n",
809 name);
810 fflush(stderr);
811 }
812 #endif
813 }
814 #endif
815
816
817 /**
818 * Special no-op glFlush, see below.
819 */
820 #if defined(_WIN32)
821 static void GLAPIENTRY
nop_glFlush(void)822 nop_glFlush(void)
823 {
824 /* don't record an error like we do in nop_handler() */
825 }
826 #endif
827
828
829 #if !USE_GLAPI_NOP_FEATURES
830 static int
generic_nop(void)831 generic_nop(void)
832 {
833 GET_CURRENT_CONTEXT(ctx);
834 _mesa_error(ctx, GL_INVALID_OPERATION,
835 "unsupported function called "
836 "(unsupported extension or deprecated function?)");
837 return 0;
838 }
839 #endif
840
841
842 static int
glthread_nop(void)843 glthread_nop(void)
844 {
845 /* This writes the error into the glthread command buffer if glthread is
846 * enabled.
847 */
848 CALL_InternalSetError(GET_DISPATCH(), (GL_INVALID_OPERATION));
849 return 0;
850 }
851
852
853 /**
854 * Create a new API dispatch table in which all entries point to the
855 * generic_nop() function. This will not work on Windows because of
856 * the __stdcall convention which requires the callee to clean up the
857 * call stack. That's impossible with one generic no-op function.
858 */
859 struct _glapi_table *
_mesa_new_nop_table(unsigned numEntries,bool glthread)860 _mesa_new_nop_table(unsigned numEntries, bool glthread)
861 {
862 struct _glapi_table *table;
863
864 #if !USE_GLAPI_NOP_FEATURES
865 table = malloc(numEntries * sizeof(_glapi_proc));
866 if (table) {
867 _glapi_proc *entry = (_glapi_proc *) table;
868 unsigned i;
869 for (i = 0; i < numEntries; i++) {
870 entry[i] = (_glapi_proc) generic_nop;
871 }
872 }
873 #else
874 table = _glapi_new_nop_table(numEntries);
875 #endif
876
877 if (glthread) {
878 _glapi_proc *entry = (_glapi_proc *) table;
879 for (unsigned i = 0; i < numEntries; i++)
880 entry[i] = (_glapi_proc)glthread_nop;
881 }
882
883 return table;
884 }
885
886
887 /**
888 * Allocate and initialize a new dispatch table. The table will be
889 * populated with pointers to "no-op" functions. In turn, the no-op
890 * functions will call nop_handler() above.
891 */
892 struct _glapi_table *
_mesa_alloc_dispatch_table(bool glthread)893 _mesa_alloc_dispatch_table(bool glthread)
894 {
895 /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
896 * In practice, this'll be the same for stand-alone Mesa. But for DRI
897 * Mesa we do this to accommodate different versions of libGL and various
898 * DRI drivers.
899 */
900 int numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
901
902 struct _glapi_table *table = _mesa_new_nop_table(numEntries, glthread);
903
904 #if defined(_WIN32)
905 if (table) {
906 /* This is a special case for Windows in the event that
907 * wglGetProcAddress is called between glBegin/End().
908 *
909 * The MS opengl32.dll library apparently calls glFlush from
910 * wglGetProcAddress(). If we're inside glBegin/End(), glFlush
911 * will dispatch to _mesa_generic_nop() and we'll generate a
912 * GL_INVALID_OPERATION error.
913 *
914 * The specific case which hits this is piglit's primitive-restart
915 * test which calls glPrimitiveRestartNV() inside glBegin/End. The
916 * first time we call glPrimitiveRestartNV() Piglit's API dispatch
917 * code will try to resolve the function by calling wglGetProcAddress.
918 * This raises GL_INVALID_OPERATION and an assert(glGetError()==0)
919 * will fail causing the test to fail. By suppressing the error, the
920 * assertion passes and the test continues.
921 */
922 SET_Flush(table, nop_glFlush);
923 }
924 #endif
925
926 #if USE_GLAPI_NOP_FEATURES
927 _glapi_set_nop_handler(nop_handler);
928 #endif
929
930 return table;
931 }
932
933 void
_mesa_initialize_dispatch_tables(struct gl_context * ctx)934 _mesa_initialize_dispatch_tables(struct gl_context *ctx)
935 {
936 /* Do the code-generated setup of the exec table in api_exec_init.c. */
937 _mesa_initialize_exec_table(ctx);
938
939 if (ctx->Save)
940 _mesa_initialize_save_table(ctx);
941
942 vbo_install_exec_vtxfmt(ctx);
943 if (ctx->API == API_OPENGL_COMPAT)
944 _mesa_install_save_vtxfmt(ctx);
945 }
946
947 /**
948 * Initialize a struct gl_context struct (rendering context).
949 *
950 * This includes allocating all the other structs and arrays which hang off of
951 * the context by pointers.
952 * Note that the driver needs to pass in its dd_function_table here since
953 * we need to at least call st_NewTextureObject to create the
954 * default texture objects.
955 *
956 * Called by _mesa_create_context().
957 *
958 * Performs the imports and exports callback tables initialization, and
959 * miscellaneous one-time initializations. If no shared context is supplied one
960 * is allocated, and increase its reference count. Setups the GL API dispatch
961 * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
962 * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
963 * for debug flags.
964 *
965 * \param ctx the context to initialize
966 * \param api the GL API type to create the context for
967 * \param visual describes the visual attributes for this context or NULL to
968 * create a configless context
969 * \param share_list points to context to share textures, display lists,
970 * etc with, or NULL
971 * \param driverFunctions table of device driver functions for this context
972 * to use
973 */
974 GLboolean
_mesa_initialize_context(struct gl_context * ctx,gl_api api,bool no_error,const struct gl_config * visual,struct gl_context * share_list,const struct dd_function_table * driverFunctions)975 _mesa_initialize_context(struct gl_context *ctx,
976 gl_api api,
977 bool no_error,
978 const struct gl_config *visual,
979 struct gl_context *share_list,
980 const struct dd_function_table *driverFunctions)
981 {
982 struct gl_shared_state *shared;
983 int i;
984
985 ctx->API = api;
986 ctx->DrawBuffer = NULL;
987 ctx->ReadBuffer = NULL;
988 ctx->WinSysDrawBuffer = NULL;
989 ctx->WinSysReadBuffer = NULL;
990
991 if (visual) {
992 ctx->Visual = *visual;
993 ctx->HasConfig = GL_TRUE;
994 }
995 else {
996 memset(&ctx->Visual, 0, sizeof ctx->Visual);
997 ctx->HasConfig = GL_FALSE;
998 }
999
1000 _mesa_override_gl_version(ctx);
1001
1002 /* misc one-time initializations */
1003 _mesa_initialize(NULL);
1004
1005 /* Plug in driver functions and context pointer here.
1006 * This is important because when we call alloc_shared_state() below
1007 * we'll call ctx->Driver.NewTextureObject() to create the default
1008 * textures.
1009 */
1010 ctx->Driver = *driverFunctions;
1011
1012 if (share_list) {
1013 /* share state with another context */
1014 shared = share_list->Shared;
1015 }
1016 else {
1017 /* allocate new, unshared state */
1018 shared = _mesa_alloc_shared_state(ctx);
1019 if (!shared)
1020 return GL_FALSE;
1021 }
1022
1023 /* all supported by default */
1024 ctx->Const.DriverSupportedPrimMask = 0xffffffff;
1025
1026 _mesa_reference_shared_state(ctx, &ctx->Shared, shared);
1027
1028 if (!init_attrib_groups( ctx ))
1029 goto fail;
1030
1031 if (no_error)
1032 ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR;
1033
1034 /* setup the API dispatch tables with all nop functions */
1035 ctx->OutsideBeginEnd = _mesa_alloc_dispatch_table(false);
1036 if (!ctx->OutsideBeginEnd)
1037 goto fail;
1038 ctx->Exec = ctx->OutsideBeginEnd;
1039 ctx->CurrentClientDispatch = ctx->CurrentServerDispatch = ctx->OutsideBeginEnd;
1040
1041 _mesa_reset_vertex_processing_mode(ctx);
1042
1043 /* Mesa core handles all the formats that mesa core knows about.
1044 * Drivers will want to override this list with just the formats
1045 * they can handle.
1046 */
1047 memset(&ctx->TextureFormatSupported, GL_TRUE,
1048 sizeof(ctx->TextureFormatSupported));
1049
1050 switch (ctx->API) {
1051 case API_OPENGL_COMPAT:
1052 ctx->BeginEnd = _mesa_alloc_dispatch_table(false);
1053 ctx->Save = _mesa_alloc_dispatch_table(false);
1054 if (!ctx->BeginEnd || !ctx->Save)
1055 goto fail;
1056
1057 FALLTHROUGH;
1058 case API_OPENGL_CORE:
1059 case API_OPENGLES2:
1060 break;
1061 case API_OPENGLES:
1062 /**
1063 * GL_OES_texture_cube_map says
1064 * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
1065 */
1066 for (i = 0; i < ARRAY_SIZE(ctx->Texture.FixedFuncUnit); i++) {
1067 struct gl_fixedfunc_texture_unit *texUnit =
1068 &ctx->Texture.FixedFuncUnit[i];
1069
1070 texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
1071 texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
1072 texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
1073 texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1074 texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1075 texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
1076 }
1077 break;
1078 }
1079 ctx->VertexProgram.PointSizeEnabled = ctx->API == API_OPENGLES2;
1080 ctx->PointSizeIsSet = GL_TRUE;
1081
1082 ctx->FirstTimeCurrent = GL_TRUE;
1083
1084 return GL_TRUE;
1085
1086 fail:
1087 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1088 free(ctx->BeginEnd);
1089 free(ctx->OutsideBeginEnd);
1090 free(ctx->Save);
1091 return GL_FALSE;
1092 }
1093
1094
1095 /**
1096 * Free the data associated with the given context.
1097 *
1098 * But doesn't free the struct gl_context struct itself.
1099 *
1100 * \sa _mesa_initialize_context() and init_attrib_groups().
1101 */
1102 void
_mesa_free_context_data(struct gl_context * ctx,bool destroy_debug_output)1103 _mesa_free_context_data(struct gl_context *ctx, bool destroy_debug_output)
1104 {
1105 if (!_mesa_get_current_context()){
1106 /* No current context, but we may need one in order to delete
1107 * texture objs, etc. So temporarily bind the context now.
1108 */
1109 _mesa_make_current(ctx, NULL, NULL);
1110 }
1111
1112 /* unreference WinSysDraw/Read buffers */
1113 _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
1114 _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
1115 _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
1116 _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
1117
1118 _mesa_reference_program(ctx, &ctx->VertexProgram.Current, NULL);
1119 _mesa_reference_program(ctx, &ctx->VertexProgram._Current, NULL);
1120 _mesa_reference_program(ctx, &ctx->VertexProgram._TnlProgram, NULL);
1121
1122 _mesa_reference_program(ctx, &ctx->TessCtrlProgram._Current, NULL);
1123 _mesa_reference_program(ctx, &ctx->TessEvalProgram._Current, NULL);
1124 _mesa_reference_program(ctx, &ctx->GeometryProgram._Current, NULL);
1125
1126 _mesa_reference_program(ctx, &ctx->FragmentProgram.Current, NULL);
1127 _mesa_reference_program(ctx, &ctx->FragmentProgram._Current, NULL);
1128 _mesa_reference_program(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
1129
1130 _mesa_reference_program(ctx, &ctx->ComputeProgram._Current, NULL);
1131
1132 _mesa_reference_vao(ctx, &ctx->Array.VAO, NULL);
1133 _mesa_reference_vao(ctx, &ctx->Array.DefaultVAO, NULL);
1134 _mesa_reference_vao(ctx, &ctx->Array._EmptyVAO, NULL);
1135 _mesa_reference_vao(ctx, &ctx->Array._DrawVAO, NULL);
1136
1137 _mesa_free_attrib_data(ctx);
1138 _mesa_free_eval_data( ctx );
1139 _mesa_free_feedback(ctx);
1140 _mesa_free_texture_data( ctx );
1141 _mesa_free_image_textures(ctx);
1142 _mesa_free_matrix_data( ctx );
1143 _mesa_free_pipeline_data(ctx);
1144 _mesa_free_program_data(ctx);
1145 _mesa_free_shader_state(ctx);
1146 _mesa_free_queryobj_data(ctx);
1147 _mesa_free_sync_data(ctx);
1148 _mesa_free_varray_data(ctx);
1149 _mesa_free_transform_feedback(ctx);
1150 _mesa_free_performance_monitors(ctx);
1151 _mesa_free_performance_queries(ctx);
1152 _mesa_free_perfomance_monitor_groups(ctx);
1153 _mesa_free_resident_handles(ctx);
1154
1155 _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
1156 _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
1157 _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
1158 _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
1159
1160 /* This must be called after all buffers are unbound because global buffer
1161 * references that this context holds will be removed.
1162 */
1163 _mesa_free_buffer_objects(ctx);
1164
1165 /* free dispatch tables */
1166 free(ctx->BeginEnd);
1167 free(ctx->OutsideBeginEnd);
1168 free(ctx->Save);
1169 free(ctx->ContextLost);
1170 free(ctx->MarshalExec);
1171 free(ctx->HWSelectModeBeginEnd);
1172
1173 /* Shared context state (display lists, textures, etc) */
1174 _mesa_reference_shared_state(ctx, &ctx->Shared, NULL);
1175
1176 if (destroy_debug_output)
1177 _mesa_destroy_debug_output(ctx);
1178
1179 free((void *)ctx->Extensions.String);
1180
1181 free(ctx->VersionString);
1182
1183 ralloc_free(ctx->SoftFP64);
1184
1185 /* unbind the context if it's currently bound */
1186 if (ctx == _mesa_get_current_context()) {
1187 _mesa_make_current(NULL, NULL, NULL);
1188 }
1189
1190 /* Do this after unbinding context to ensure any thread is finished. */
1191 if (ctx->shader_builtin_ref) {
1192 _mesa_glsl_builtin_functions_decref();
1193 ctx->shader_builtin_ref = false;
1194 }
1195
1196 free(ctx->Const.SpirVExtensions);
1197 }
1198
1199
1200 /**
1201 * Copy attribute groups from one context to another.
1202 *
1203 * \param src source context
1204 * \param dst destination context
1205 * \param mask bitwise OR of GL_*_BIT flags
1206 *
1207 * According to the bits specified in \p mask, copies the corresponding
1208 * attributes from \p src into \p dst. For many of the attributes a simple \c
1209 * memcpy is not enough due to the existence of internal pointers in their data
1210 * structures.
1211 */
1212 void
_mesa_copy_context(const struct gl_context * src,struct gl_context * dst,GLuint mask)1213 _mesa_copy_context( const struct gl_context *src, struct gl_context *dst,
1214 GLuint mask )
1215 {
1216 if (mask & GL_ACCUM_BUFFER_BIT) {
1217 /* OK to memcpy */
1218 dst->Accum = src->Accum;
1219 }
1220 if (mask & GL_COLOR_BUFFER_BIT) {
1221 /* OK to memcpy */
1222 dst->Color = src->Color;
1223 }
1224 if (mask & GL_CURRENT_BIT) {
1225 /* OK to memcpy */
1226 dst->Current = src->Current;
1227 }
1228 if (mask & GL_DEPTH_BUFFER_BIT) {
1229 /* OK to memcpy */
1230 dst->Depth = src->Depth;
1231 }
1232 if (mask & GL_ENABLE_BIT) {
1233 /* no op */
1234 }
1235 if (mask & GL_EVAL_BIT) {
1236 /* OK to memcpy */
1237 dst->Eval = src->Eval;
1238 }
1239 if (mask & GL_FOG_BIT) {
1240 /* OK to memcpy */
1241 dst->Fog = src->Fog;
1242 }
1243 if (mask & GL_HINT_BIT) {
1244 /* OK to memcpy */
1245 dst->Hint = src->Hint;
1246 }
1247 if (mask & GL_LIGHTING_BIT) {
1248 /* OK to memcpy */
1249 dst->Light = src->Light;
1250 }
1251 if (mask & GL_LINE_BIT) {
1252 /* OK to memcpy */
1253 dst->Line = src->Line;
1254 }
1255 if (mask & GL_LIST_BIT) {
1256 /* OK to memcpy */
1257 dst->List = src->List;
1258 }
1259 if (mask & GL_PIXEL_MODE_BIT) {
1260 /* OK to memcpy */
1261 dst->Pixel = src->Pixel;
1262 }
1263 if (mask & GL_POINT_BIT) {
1264 /* OK to memcpy */
1265 dst->Point = src->Point;
1266 }
1267 if (mask & GL_POLYGON_BIT) {
1268 /* OK to memcpy */
1269 dst->Polygon = src->Polygon;
1270 }
1271 if (mask & GL_POLYGON_STIPPLE_BIT) {
1272 /* Use loop instead of memcpy due to problem with Portland Group's
1273 * C compiler. Reported by John Stone.
1274 */
1275 GLuint i;
1276 for (i = 0; i < 32; i++) {
1277 dst->PolygonStipple[i] = src->PolygonStipple[i];
1278 }
1279 }
1280 if (mask & GL_SCISSOR_BIT) {
1281 /* OK to memcpy */
1282 dst->Scissor = src->Scissor;
1283 }
1284 if (mask & GL_STENCIL_BUFFER_BIT) {
1285 /* OK to memcpy */
1286 dst->Stencil = src->Stencil;
1287 }
1288 if (mask & GL_TEXTURE_BIT) {
1289 /* Cannot memcpy because of pointers */
1290 _mesa_copy_texture_state(src, dst);
1291 }
1292 if (mask & GL_TRANSFORM_BIT) {
1293 /* OK to memcpy */
1294 dst->Transform = src->Transform;
1295 }
1296 if (mask & GL_VIEWPORT_BIT) {
1297 unsigned i;
1298 for (i = 0; i < src->Const.MaxViewports; i++) {
1299 /* OK to memcpy */
1300 dst->ViewportArray[i] = src->ViewportArray[i];
1301 }
1302 }
1303
1304 /* XXX FIXME: Call callbacks?
1305 */
1306 dst->NewState = _NEW_ALL;
1307 dst->NewDriverState = ~0;
1308 }
1309
1310
1311 /**
1312 * Check if the given context can render into the given framebuffer
1313 * by checking visual attributes.
1314 *
1315 * \return GL_TRUE if compatible, GL_FALSE otherwise.
1316 */
1317 static GLboolean
check_compatible(const struct gl_context * ctx,const struct gl_framebuffer * buffer)1318 check_compatible(const struct gl_context *ctx,
1319 const struct gl_framebuffer *buffer)
1320 {
1321 const struct gl_config *ctxvis = &ctx->Visual;
1322 const struct gl_config *bufvis = &buffer->Visual;
1323
1324 if (buffer == _mesa_get_incomplete_framebuffer())
1325 return GL_TRUE;
1326
1327 #define check_component(foo) \
1328 if (ctxvis->foo && bufvis->foo && \
1329 ctxvis->foo != bufvis->foo) \
1330 return GL_FALSE
1331
1332 check_component(redShift);
1333 check_component(greenShift);
1334 check_component(blueShift);
1335 check_component(redBits);
1336 check_component(greenBits);
1337 check_component(blueBits);
1338 check_component(depthBits);
1339 check_component(stencilBits);
1340
1341 #undef check_component
1342
1343 return GL_TRUE;
1344 }
1345
1346
1347 /**
1348 * Check if the viewport/scissor size has not yet been initialized.
1349 * Initialize the size if the given width and height are non-zero.
1350 */
1351 static void
check_init_viewport(struct gl_context * ctx,GLuint width,GLuint height)1352 check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
1353 {
1354 if (!ctx->ViewportInitialized && width > 0 && height > 0) {
1355 unsigned i;
1356
1357 /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
1358 * potential infinite recursion.
1359 */
1360 ctx->ViewportInitialized = GL_TRUE;
1361
1362 /* Note: ctx->Const.MaxViewports may not have been set by the driver
1363 * yet, so just initialize all of them.
1364 */
1365 for (i = 0; i < MAX_VIEWPORTS; i++) {
1366 _mesa_set_viewport(ctx, i, 0, 0, width, height);
1367 _mesa_set_scissor(ctx, i, 0, 0, width, height);
1368 }
1369 }
1370 }
1371
1372
1373 static void
handle_first_current(struct gl_context * ctx)1374 handle_first_current(struct gl_context *ctx)
1375 {
1376 if (ctx->Version == 0 || !ctx->DrawBuffer) {
1377 /* probably in the process of tearing down the context */
1378 return;
1379 }
1380
1381 check_context_limits(ctx);
1382
1383 _mesa_update_vertex_processing_mode(ctx);
1384
1385 /* According to GL_MESA_configless_context the default value of
1386 * glDrawBuffers depends on the config of the first surface it is bound to.
1387 * For GLES it is always GL_BACK which has a magic interpretation.
1388 */
1389 if (!ctx->HasConfig && _mesa_is_desktop_gl(ctx)) {
1390 if (ctx->DrawBuffer != _mesa_get_incomplete_framebuffer()) {
1391 GLenum16 buffer;
1392
1393 if (ctx->DrawBuffer->Visual.doubleBufferMode)
1394 buffer = GL_BACK;
1395 else
1396 buffer = GL_FRONT;
1397
1398 _mesa_drawbuffers(ctx, ctx->DrawBuffer, 1, &buffer,
1399 NULL /* destMask */);
1400 }
1401
1402 if (ctx->ReadBuffer != _mesa_get_incomplete_framebuffer()) {
1403 gl_buffer_index bufferIndex;
1404 GLenum buffer;
1405
1406 if (ctx->ReadBuffer->Visual.doubleBufferMode) {
1407 buffer = GL_BACK;
1408 bufferIndex = BUFFER_BACK_LEFT;
1409 }
1410 else {
1411 buffer = GL_FRONT;
1412 bufferIndex = BUFFER_FRONT_LEFT;
1413 }
1414
1415 _mesa_readbuffer(ctx, ctx->ReadBuffer, buffer, bufferIndex);
1416 }
1417 }
1418
1419 /* Determine if generic vertex attribute 0 aliases the conventional
1420 * glVertex position.
1421 */
1422 {
1423 const bool is_forward_compatible_context =
1424 ctx->Const.ContextFlags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT;
1425
1426 /* In OpenGL 3.1 attribute 0 becomes non-magic, just like in OpenGL ES
1427 * 2.0. Note that we cannot just check for API_OPENGL_COMPAT here because
1428 * that will erroneously allow this usage in a 3.0 forward-compatible
1429 * context too.
1430 */
1431 ctx->_AttribZeroAliasesVertex = (ctx->API == API_OPENGLES
1432 || (ctx->API == API_OPENGL_COMPAT
1433 && !is_forward_compatible_context));
1434 }
1435
1436 /* We can use this to help debug user's problems. Tell them to set
1437 * the MESA_INFO env variable before running their app. Then the
1438 * first time each context is made current we'll print some useful
1439 * information.
1440 */
1441 if (getenv("MESA_INFO")) {
1442 _mesa_print_info(ctx);
1443 }
1444 }
1445
1446 /**
1447 * Bind the given context to the given drawBuffer and readBuffer and
1448 * make it the current context for the calling thread.
1449 * We'll render into the drawBuffer and read pixels from the
1450 * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
1451 *
1452 * We check that the context's and framebuffer's visuals are compatible
1453 * and return immediately if they're not.
1454 *
1455 * \param newCtx the new GL context. If NULL then there will be no current GL
1456 * context.
1457 * \param drawBuffer the drawing framebuffer
1458 * \param readBuffer the reading framebuffer
1459 */
1460 GLboolean
_mesa_make_current(struct gl_context * newCtx,struct gl_framebuffer * drawBuffer,struct gl_framebuffer * readBuffer)1461 _mesa_make_current( struct gl_context *newCtx,
1462 struct gl_framebuffer *drawBuffer,
1463 struct gl_framebuffer *readBuffer )
1464 {
1465 GET_CURRENT_CONTEXT(curCtx);
1466
1467 if (MESA_VERBOSE & VERBOSE_API)
1468 _mesa_debug(newCtx, "_mesa_make_current()\n");
1469
1470 /* Check that the context's and framebuffer's visuals are compatible.
1471 */
1472 if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
1473 if (!check_compatible(newCtx, drawBuffer)) {
1474 _mesa_warning(newCtx,
1475 "MakeCurrent: incompatible visuals for context and drawbuffer");
1476 return GL_FALSE;
1477 }
1478 }
1479 if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
1480 if (!check_compatible(newCtx, readBuffer)) {
1481 _mesa_warning(newCtx,
1482 "MakeCurrent: incompatible visuals for context and readbuffer");
1483 return GL_FALSE;
1484 }
1485 }
1486
1487 if (curCtx &&
1488 /* make sure this context is valid for flushing */
1489 curCtx != newCtx &&
1490 curCtx->Const.ContextReleaseBehavior ==
1491 GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH) {
1492 FLUSH_VERTICES(curCtx, 0, 0);
1493 st_glFlush(curCtx, 0);
1494 }
1495
1496 /* Call this periodically to detect when the user has begun using
1497 * GL rendering from multiple threads.
1498 */
1499 _glapi_check_multithread();
1500
1501 if (!newCtx) {
1502 _glapi_set_dispatch(NULL); /* none current */
1503 /* We need old ctx to correctly release Draw/ReadBuffer
1504 * and avoid a surface leak in st_renderbuffer_delete.
1505 * Therefore, first drop buffers then set new ctx to NULL.
1506 */
1507 if (curCtx) {
1508 _mesa_reference_framebuffer(&curCtx->WinSysDrawBuffer, NULL);
1509 _mesa_reference_framebuffer(&curCtx->WinSysReadBuffer, NULL);
1510 }
1511 _glapi_set_context(NULL);
1512 assert(_mesa_get_current_context() == NULL);
1513 }
1514 else {
1515 _glapi_set_context((void *) newCtx);
1516 assert(_mesa_get_current_context() == newCtx);
1517 _glapi_set_dispatch(newCtx->CurrentClientDispatch);
1518
1519 if (drawBuffer && readBuffer) {
1520 assert(_mesa_is_winsys_fbo(drawBuffer));
1521 assert(_mesa_is_winsys_fbo(readBuffer));
1522 _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
1523 _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
1524
1525 /*
1526 * Only set the context's Draw/ReadBuffer fields if they're NULL
1527 * or not bound to a user-created FBO.
1528 */
1529 if (!newCtx->DrawBuffer || _mesa_is_winsys_fbo(newCtx->DrawBuffer)) {
1530 _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
1531 /* Update the FBO's list of drawbuffers/renderbuffers.
1532 * For winsys FBOs this comes from the GL state (which may have
1533 * changed since the last time this FBO was bound).
1534 */
1535 _mesa_update_draw_buffers(newCtx);
1536 _mesa_update_allow_draw_out_of_order(newCtx);
1537 _mesa_update_valid_to_render_state(newCtx);
1538 }
1539 if (!newCtx->ReadBuffer || _mesa_is_winsys_fbo(newCtx->ReadBuffer)) {
1540 _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
1541 /* In _mesa_initialize_window_framebuffer, for single-buffered
1542 * visuals, the ColorReadBuffer is set to be GL_FRONT, even with
1543 * GLES contexts. When calling read_buffer, we verify we are reading
1544 * from GL_BACK in is_legal_es3_readbuffer_enum. But the default is
1545 * incorrect, and certain dEQP tests check this. So fix it here.
1546 */
1547 if (_mesa_is_gles(newCtx) &&
1548 !newCtx->ReadBuffer->Visual.doubleBufferMode)
1549 if (newCtx->ReadBuffer->ColorReadBuffer == GL_FRONT)
1550 newCtx->ReadBuffer->ColorReadBuffer = GL_BACK;
1551 }
1552
1553 /* XXX only set this flag if we're really changing the draw/read
1554 * framebuffer bindings.
1555 */
1556 newCtx->NewState |= _NEW_BUFFERS;
1557
1558 check_init_viewport(newCtx, drawBuffer->Width, drawBuffer->Height);
1559 }
1560
1561 if (newCtx->FirstTimeCurrent) {
1562 handle_first_current(newCtx);
1563 newCtx->FirstTimeCurrent = GL_FALSE;
1564 }
1565 }
1566
1567 return GL_TRUE;
1568 }
1569
1570
1571 /**
1572 * Make context 'ctx' share the display lists, textures and programs
1573 * that are associated with 'ctxToShare'.
1574 * Any display lists, textures or programs associated with 'ctx' will
1575 * be deleted if nobody else is sharing them.
1576 */
1577 GLboolean
_mesa_share_state(struct gl_context * ctx,struct gl_context * ctxToShare)1578 _mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
1579 {
1580 if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
1581 struct gl_shared_state *oldShared = NULL;
1582
1583 /* save ref to old state to prevent it from being deleted immediately */
1584 _mesa_reference_shared_state(ctx, &oldShared, ctx->Shared);
1585
1586 /* update ctx's Shared pointer */
1587 _mesa_reference_shared_state(ctx, &ctx->Shared, ctxToShare->Shared);
1588
1589 update_default_objects(ctx);
1590
1591 /* release the old shared state */
1592 _mesa_reference_shared_state(ctx, &oldShared, NULL);
1593
1594 return GL_TRUE;
1595 }
1596 else {
1597 return GL_FALSE;
1598 }
1599 }
1600
1601
1602
1603 /**
1604 * \return pointer to the current GL context for this thread.
1605 *
1606 * Calls _glapi_get_context(). This isn't the fastest way to get the current
1607 * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
1608 * context.h.
1609 */
1610 struct gl_context *
_mesa_get_current_context(void)1611 _mesa_get_current_context( void )
1612 {
1613 return (struct gl_context *) _glapi_get_context();
1614 }
1615
1616
1617 /**
1618 * Get context's current API dispatch table.
1619 *
1620 * It'll either be the immediate-mode execute dispatcher, the display list
1621 * compile dispatcher, or the thread marshalling dispatcher.
1622 *
1623 * \param ctx GL context.
1624 *
1625 * \return pointer to dispatch_table.
1626 *
1627 * Simply returns __struct gl_contextRec::CurrentClientDispatch.
1628 */
1629 struct _glapi_table *
_mesa_get_dispatch(struct gl_context * ctx)1630 _mesa_get_dispatch(struct gl_context *ctx)
1631 {
1632 return ctx->CurrentClientDispatch;
1633 }
1634
1635 /*@}*/
1636
1637
1638 /**********************************************************************/
1639 /** \name Miscellaneous functions */
1640 /**********************************************************************/
1641 /*@{*/
1642 /**
1643 * Flush commands.
1644 */
1645 void
_mesa_flush(struct gl_context * ctx)1646 _mesa_flush(struct gl_context *ctx)
1647 {
1648 bool async = !ctx->Shared->HasExternallySharedImages;
1649 FLUSH_VERTICES(ctx, 0, 0);
1650
1651 st_glFlush(ctx, async ? PIPE_FLUSH_ASYNC : 0);
1652 }
1653
1654
1655
1656 /**
1657 * Flush commands and wait for completion.
1658 *
1659 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1660 * dd_function_table::Finish driver callback, if not NULL.
1661 */
1662 void GLAPIENTRY
_mesa_Finish(void)1663 _mesa_Finish(void)
1664 {
1665 GET_CURRENT_CONTEXT(ctx);
1666 ASSERT_OUTSIDE_BEGIN_END(ctx);
1667
1668 FLUSH_VERTICES(ctx, 0, 0);
1669
1670 st_glFinish(ctx);
1671 }
1672
1673
1674 /**
1675 * Execute glFlush().
1676 *
1677 * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
1678 * dd_function_table::Flush driver callback, if not NULL.
1679 */
1680 void GLAPIENTRY
_mesa_Flush(void)1681 _mesa_Flush(void)
1682 {
1683 GET_CURRENT_CONTEXT(ctx);
1684 ASSERT_OUTSIDE_BEGIN_END(ctx);
1685 _mesa_flush(ctx);
1686 }
1687
1688
1689 /*@}*/
1690