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