mesa: Drop _mesa_getenv() wrapper.
[mesa.git] / src / mesa / main / shaderapi.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
5 * Copyright (C) 2009-2010 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 shaderapi.c
28 * \author Brian Paul
29 *
30 * Implementation of GLSL-related API functions.
31 * The glUniform* functions are in uniforms.c
32 *
33 *
34 * XXX things to do:
35 * 1. Check that the right error code is generated for all _mesa_error() calls.
36 * 2. Insert FLUSH_VERTICES calls in various places
37 */
38
39
40 #include "main/glheader.h"
41 #include "main/context.h"
42 #include "main/dispatch.h"
43 #include "main/enums.h"
44 #include "main/hash.h"
45 #include "main/mtypes.h"
46 #include "main/pipelineobj.h"
47 #include "main/shaderapi.h"
48 #include "main/shaderobj.h"
49 #include "main/transformfeedback.h"
50 #include "main/uniforms.h"
51 #include "program/program.h"
52 #include "program/prog_print.h"
53 #include "program/prog_parameter.h"
54 #include "util/ralloc.h"
55 #include "util/hash_table.h"
56 #include <stdbool.h>
57 #include "../glsl/glsl_parser_extras.h"
58 #include "../glsl/ir.h"
59 #include "../glsl/ir_uniform.h"
60 #include "../glsl/program.h"
61
62 /** Define this to enable shader substitution (see below) */
63 #define SHADER_SUBST 0
64
65
66 /**
67 * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
68 */
69 GLbitfield
70 _mesa_get_shader_flags(void)
71 {
72 GLbitfield flags = 0x0;
73 const char *env = getenv("MESA_GLSL");
74
75 if (env) {
76 if (strstr(env, "dump_on_error"))
77 flags |= GLSL_DUMP_ON_ERROR;
78 else if (strstr(env, "dump"))
79 flags |= GLSL_DUMP;
80 if (strstr(env, "log"))
81 flags |= GLSL_LOG;
82 if (strstr(env, "nopvert"))
83 flags |= GLSL_NOP_VERT;
84 if (strstr(env, "nopfrag"))
85 flags |= GLSL_NOP_FRAG;
86 if (strstr(env, "nopt"))
87 flags |= GLSL_NO_OPT;
88 else if (strstr(env, "opt"))
89 flags |= GLSL_OPT;
90 if (strstr(env, "uniform"))
91 flags |= GLSL_UNIFORMS;
92 if (strstr(env, "useprog"))
93 flags |= GLSL_USE_PROG;
94 if (strstr(env, "errors"))
95 flags |= GLSL_REPORT_ERRORS;
96 }
97
98 return flags;
99 }
100
101
102 /**
103 * Initialize context's shader state.
104 */
105 void
106 _mesa_init_shader_state(struct gl_context *ctx)
107 {
108 /* Device drivers may override these to control what kind of instructions
109 * are generated by the GLSL compiler.
110 */
111 struct gl_shader_compiler_options options;
112 gl_shader_stage sh;
113
114 memset(&options, 0, sizeof(options));
115 options.MaxUnrollIterations = 32;
116 options.MaxIfDepth = UINT_MAX;
117
118 /* Default pragma settings */
119 options.DefaultPragmas.Optimize = GL_TRUE;
120
121 for (sh = 0; sh < MESA_SHADER_STAGES; ++sh)
122 memcpy(&ctx->Const.ShaderCompilerOptions[sh], &options, sizeof(options));
123
124 ctx->Shader.Flags = _mesa_get_shader_flags();
125
126 /* Extended for ARB_separate_shader_objects */
127 ctx->Shader.RefCount = 1;
128 mtx_init(&ctx->Shader.Mutex, mtx_plain);
129 }
130
131
132 /**
133 * Free the per-context shader-related state.
134 */
135 void
136 _mesa_free_shader_state(struct gl_context *ctx)
137 {
138 int i;
139 for (i = 0; i < MESA_SHADER_STAGES; i++) {
140 _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentProgram[i],
141 NULL);
142 }
143 _mesa_reference_shader_program(ctx, &ctx->Shader._CurrentFragmentProgram,
144 NULL);
145 _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
146
147 /* Extended for ARB_separate_shader_objects */
148 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, NULL);
149
150 assert(ctx->Shader.RefCount == 1);
151 mtx_destroy(&ctx->Shader.Mutex);
152 }
153
154
155 /**
156 * Copy string from <src> to <dst>, up to maxLength characters, returning
157 * length of <dst> in <length>.
158 * \param src the strings source
159 * \param maxLength max chars to copy
160 * \param length returns number of chars copied
161 * \param dst the string destination
162 */
163 void
164 _mesa_copy_string(GLchar *dst, GLsizei maxLength,
165 GLsizei *length, const GLchar *src)
166 {
167 GLsizei len;
168 for (len = 0; len < maxLength - 1 && src && src[len]; len++)
169 dst[len] = src[len];
170 if (maxLength > 0)
171 dst[len] = 0;
172 if (length)
173 *length = len;
174 }
175
176
177
178 /**
179 * Confirm that the a shader type is valid and supported by the implementation
180 *
181 * \param ctx Current GL context
182 * \param type Shader target
183 *
184 */
185 bool
186 _mesa_validate_shader_target(const struct gl_context *ctx, GLenum type)
187 {
188 /* Note: when building built-in GLSL functions, this function may be
189 * invoked with ctx == NULL. In that case, we can only validate that it's
190 * a shader target we recognize, not that it's supported in the current
191 * context. But that's fine--we don't need any further validation than
192 * that when building built-in GLSL functions.
193 */
194
195 switch (type) {
196 case GL_FRAGMENT_SHADER:
197 return ctx == NULL || ctx->Extensions.ARB_fragment_shader;
198 case GL_VERTEX_SHADER:
199 return ctx == NULL || ctx->Extensions.ARB_vertex_shader;
200 case GL_GEOMETRY_SHADER_ARB:
201 return ctx == NULL || _mesa_has_geometry_shaders(ctx);
202 case GL_COMPUTE_SHADER:
203 return ctx == NULL || ctx->Extensions.ARB_compute_shader;
204 default:
205 return false;
206 }
207 }
208
209
210 static GLboolean
211 is_program(struct gl_context *ctx, GLuint name)
212 {
213 struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
214 return shProg ? GL_TRUE : GL_FALSE;
215 }
216
217
218 static GLboolean
219 is_shader(struct gl_context *ctx, GLuint name)
220 {
221 struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
222 return shader ? GL_TRUE : GL_FALSE;
223 }
224
225
226 /**
227 * Attach shader to a shader program.
228 */
229 static void
230 attach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
231 {
232 struct gl_shader_program *shProg;
233 struct gl_shader *sh;
234 GLuint i, n;
235
236 const bool same_type_disallowed = _mesa_is_gles(ctx);
237
238 shProg = _mesa_lookup_shader_program_err(ctx, program, "glAttachShader");
239 if (!shProg)
240 return;
241
242 sh = _mesa_lookup_shader_err(ctx, shader, "glAttachShader");
243 if (!sh) {
244 return;
245 }
246
247 n = shProg->NumShaders;
248 for (i = 0; i < n; i++) {
249 if (shProg->Shaders[i] == sh) {
250 /* The shader is already attched to this program. The
251 * GL_ARB_shader_objects spec says:
252 *
253 * "The error INVALID_OPERATION is generated by AttachObjectARB
254 * if <obj> is already attached to <containerObj>."
255 */
256 _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
257 return;
258 } else if (same_type_disallowed &&
259 shProg->Shaders[i]->Type == sh->Type) {
260 /* Shader with the same type is already attached to this program,
261 * OpenGL ES 2.0 and 3.0 specs say:
262 *
263 * "Multiple shader objects of the same type may not be attached
264 * to a single program object. [...] The error INVALID_OPERATION
265 * is generated if [...] another shader object of the same type
266 * as shader is already attached to program."
267 */
268 _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
269 return;
270 }
271 }
272
273 /* grow list */
274 shProg->Shaders = (struct gl_shader **)
275 realloc(shProg->Shaders,
276 (n + 1) * sizeof(struct gl_shader *));
277 if (!shProg->Shaders) {
278 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
279 return;
280 }
281
282 /* append */
283 shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
284 _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
285 shProg->NumShaders++;
286 }
287
288
289 static GLuint
290 create_shader(struct gl_context *ctx, GLenum type)
291 {
292 struct gl_shader *sh;
293 GLuint name;
294
295 if (!_mesa_validate_shader_target(ctx, type)) {
296 _mesa_error(ctx, GL_INVALID_ENUM, "CreateShader(type)");
297 return 0;
298 }
299
300 name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
301 sh = ctx->Driver.NewShader(ctx, name, type);
302 _mesa_HashInsert(ctx->Shared->ShaderObjects, name, sh);
303
304 return name;
305 }
306
307
308 static GLuint
309 create_shader_program(struct gl_context *ctx)
310 {
311 GLuint name;
312 struct gl_shader_program *shProg;
313
314 name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
315
316 shProg = ctx->Driver.NewShaderProgram(ctx, name);
317
318 _mesa_HashInsert(ctx->Shared->ShaderObjects, name, shProg);
319
320 assert(shProg->RefCount == 1);
321
322 return name;
323 }
324
325
326 /**
327 * Named w/ "2" to indicate OpenGL 2.x vs GL_ARB_fragment_programs's
328 * DeleteProgramARB.
329 */
330 static void
331 delete_shader_program(struct gl_context *ctx, GLuint name)
332 {
333 /*
334 * NOTE: deleting shaders/programs works a bit differently than
335 * texture objects (and buffer objects, etc). Shader/program
336 * handles/IDs exist in the hash table until the object is really
337 * deleted (refcount==0). With texture objects, the handle/ID is
338 * removed from the hash table in glDeleteTextures() while the tex
339 * object itself might linger until its refcount goes to zero.
340 */
341 struct gl_shader_program *shProg;
342
343 shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
344 if (!shProg)
345 return;
346
347 if (!shProg->DeletePending) {
348 shProg->DeletePending = GL_TRUE;
349
350 /* effectively, decr shProg's refcount */
351 _mesa_reference_shader_program(ctx, &shProg, NULL);
352 }
353 }
354
355
356 static void
357 delete_shader(struct gl_context *ctx, GLuint shader)
358 {
359 struct gl_shader *sh;
360
361 sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
362 if (!sh)
363 return;
364
365 if (!sh->DeletePending) {
366 sh->DeletePending = GL_TRUE;
367
368 /* effectively, decr sh's refcount */
369 _mesa_reference_shader(ctx, &sh, NULL);
370 }
371 }
372
373
374 static void
375 detach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
376 {
377 struct gl_shader_program *shProg;
378 GLuint n;
379 GLuint i, j;
380
381 shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
382 if (!shProg)
383 return;
384
385 n = shProg->NumShaders;
386
387 for (i = 0; i < n; i++) {
388 if (shProg->Shaders[i]->Name == shader) {
389 /* found it */
390 struct gl_shader **newList;
391
392 /* release */
393 _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
394
395 /* alloc new, smaller array */
396 newList = malloc((n - 1) * sizeof(struct gl_shader *));
397 if (!newList) {
398 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
399 return;
400 }
401 /* Copy old list entries to new list, skipping removed entry at [i] */
402 for (j = 0; j < i; j++) {
403 newList[j] = shProg->Shaders[j];
404 }
405 while (++i < n) {
406 newList[j++] = shProg->Shaders[i];
407 }
408
409 /* Free old list and install new one */
410 free(shProg->Shaders);
411 shProg->Shaders = newList;
412 shProg->NumShaders = n - 1;
413
414 #ifdef DEBUG
415 /* sanity check - make sure the new list's entries are sensible */
416 for (j = 0; j < shProg->NumShaders; j++) {
417 assert(shProg->Shaders[j]->Type == GL_VERTEX_SHADER ||
418 shProg->Shaders[j]->Type == GL_GEOMETRY_SHADER ||
419 shProg->Shaders[j]->Type == GL_FRAGMENT_SHADER);
420 assert(shProg->Shaders[j]->RefCount > 0);
421 }
422 #endif
423
424 return;
425 }
426 }
427
428 /* not found */
429 {
430 GLenum err;
431 if (is_shader(ctx, shader))
432 err = GL_INVALID_OPERATION;
433 else if (is_program(ctx, shader))
434 err = GL_INVALID_OPERATION;
435 else
436 err = GL_INVALID_VALUE;
437 _mesa_error(ctx, err, "glDetachShader(shader)");
438 return;
439 }
440 }
441
442
443 /**
444 * Return list of shaders attached to shader program.
445 */
446 static void
447 get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
448 GLsizei *count, GLuint *obj)
449 {
450 struct gl_shader_program *shProg =
451 _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
452 if (shProg) {
453 GLuint i;
454 for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
455 obj[i] = shProg->Shaders[i]->Name;
456 }
457 if (count)
458 *count = i;
459 }
460 }
461
462
463 /**
464 * glGetHandleARB() - return ID/name of currently bound shader program.
465 */
466 static GLuint
467 get_handle(struct gl_context *ctx, GLenum pname)
468 {
469 if (pname == GL_PROGRAM_OBJECT_ARB) {
470 if (ctx->_Shader->ActiveProgram)
471 return ctx->_Shader->ActiveProgram->Name;
472 else
473 return 0;
474 }
475 else {
476 _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
477 return 0;
478 }
479 }
480
481
482 /**
483 * Check if a geometry shader query is valid at this time. If not, report an
484 * error and return false.
485 *
486 * From GL 3.2 section 6.1.16 (Shader and Program Queries):
487 *
488 * "If GEOMETRY_VERTICES_OUT, GEOMETRY_INPUT_TYPE, or GEOMETRY_OUTPUT_TYPE
489 * are queried for a program which has not been linked successfully, or
490 * which does not contain objects to form a geometry shader, then an
491 * INVALID_OPERATION error is generated."
492 */
493 static bool
494 check_gs_query(struct gl_context *ctx, const struct gl_shader_program *shProg)
495 {
496 if (shProg->LinkStatus &&
497 shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
498 return true;
499 }
500
501 _mesa_error(ctx, GL_INVALID_OPERATION,
502 "glGetProgramv(linked geometry shader required)");
503 return false;
504 }
505
506
507 /**
508 * glGetProgramiv() - get shader program state.
509 * Note that this is for GLSL shader programs, not ARB vertex/fragment
510 * programs (see glGetProgramivARB).
511 */
512 static void
513 get_programiv(struct gl_context *ctx, GLuint program, GLenum pname, GLint *params)
514 {
515 struct gl_shader_program *shProg
516 = _mesa_lookup_shader_program(ctx, program);
517
518 /* Is transform feedback available in this context?
519 */
520 const bool has_xfb =
521 (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.EXT_transform_feedback)
522 || ctx->API == API_OPENGL_CORE
523 || _mesa_is_gles3(ctx);
524
525 /* True if geometry shaders (of the form that was adopted into GLSL 1.50
526 * and GL 3.2) are available in this context
527 */
528 const bool has_core_gs = _mesa_is_desktop_gl(ctx) && ctx->Version >= 32;
529
530 /* Are uniform buffer objects available in this context?
531 */
532 const bool has_ubo =
533 (ctx->API == API_OPENGL_COMPAT && ctx->Extensions.ARB_uniform_buffer_object)
534 || ctx->API == API_OPENGL_CORE
535 || _mesa_is_gles3(ctx);
536
537 if (!shProg) {
538 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramiv(program)");
539 return;
540 }
541
542 switch (pname) {
543 case GL_DELETE_STATUS:
544 *params = shProg->DeletePending;
545 return;
546 case GL_LINK_STATUS:
547 *params = shProg->LinkStatus;
548 return;
549 case GL_VALIDATE_STATUS:
550 *params = shProg->Validated;
551 return;
552 case GL_INFO_LOG_LENGTH:
553 *params = shProg->InfoLog ? strlen(shProg->InfoLog) + 1 : 0;
554 return;
555 case GL_ATTACHED_SHADERS:
556 *params = shProg->NumShaders;
557 return;
558 case GL_ACTIVE_ATTRIBUTES:
559 *params = _mesa_count_active_attribs(shProg);
560 return;
561 case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
562 *params = _mesa_longest_attribute_name_length(shProg);
563 return;
564 case GL_ACTIVE_UNIFORMS:
565 *params = shProg->NumUserUniformStorage;
566 return;
567 case GL_ACTIVE_UNIFORM_MAX_LENGTH: {
568 unsigned i;
569 GLint max_len = 0;
570
571 for (i = 0; i < shProg->NumUserUniformStorage; i++) {
572 /* Add one for the terminating NUL character for a non-array, and
573 * 4 for the "[0]" and the NUL for an array.
574 */
575 const GLint len = strlen(shProg->UniformStorage[i].name) + 1 +
576 ((shProg->UniformStorage[i].array_elements != 0) ? 3 : 0);
577
578 if (len > max_len)
579 max_len = len;
580 }
581
582 *params = max_len;
583 return;
584 }
585 case GL_TRANSFORM_FEEDBACK_VARYINGS:
586 if (!has_xfb)
587 break;
588 *params = shProg->TransformFeedback.NumVarying;
589 return;
590 case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH: {
591 unsigned i;
592 GLint max_len = 0;
593 if (!has_xfb)
594 break;
595
596 for (i = 0; i < shProg->TransformFeedback.NumVarying; i++) {
597 /* Add one for the terminating NUL character.
598 */
599 const GLint len = strlen(shProg->TransformFeedback.VaryingNames[i]) + 1;
600
601 if (len > max_len)
602 max_len = len;
603 }
604
605 *params = max_len;
606 return;
607 }
608 case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
609 if (!has_xfb)
610 break;
611 *params = shProg->TransformFeedback.BufferMode;
612 return;
613 case GL_GEOMETRY_VERTICES_OUT:
614 if (!has_core_gs)
615 break;
616 if (check_gs_query(ctx, shProg))
617 *params = shProg->Geom.VerticesOut;
618 return;
619 case GL_GEOMETRY_SHADER_INVOCATIONS:
620 if (!has_core_gs || !ctx->Extensions.ARB_gpu_shader5)
621 break;
622 if (check_gs_query(ctx, shProg))
623 *params = shProg->Geom.Invocations;
624 return;
625 case GL_GEOMETRY_INPUT_TYPE:
626 if (!has_core_gs)
627 break;
628 if (check_gs_query(ctx, shProg))
629 *params = shProg->Geom.InputType;
630 return;
631 case GL_GEOMETRY_OUTPUT_TYPE:
632 if (!has_core_gs)
633 break;
634 if (check_gs_query(ctx, shProg))
635 *params = shProg->Geom.OutputType;
636 return;
637 case GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH: {
638 unsigned i;
639 GLint max_len = 0;
640
641 if (!has_ubo)
642 break;
643
644 for (i = 0; i < shProg->NumUniformBlocks; i++) {
645 /* Add one for the terminating NUL character.
646 */
647 const GLint len = strlen(shProg->UniformBlocks[i].Name) + 1;
648
649 if (len > max_len)
650 max_len = len;
651 }
652
653 *params = max_len;
654 return;
655 }
656 case GL_ACTIVE_UNIFORM_BLOCKS:
657 if (!has_ubo)
658 break;
659
660 *params = shProg->NumUniformBlocks;
661 return;
662 case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
663 /* This enum isn't part of the OES extension for OpenGL ES 2.0. It is
664 * only available with desktop OpenGL 3.0+ with the
665 * GL_ARB_get_program_binary extension or OpenGL ES 3.0.
666 *
667 * On desktop, we ignore the 3.0+ requirement because it is silly.
668 */
669 if (!_mesa_is_desktop_gl(ctx) && !_mesa_is_gles3(ctx))
670 break;
671
672 *params = shProg->BinaryRetreivableHint;
673 return;
674 case GL_PROGRAM_BINARY_LENGTH:
675 *params = 0;
676 return;
677 case GL_ACTIVE_ATOMIC_COUNTER_BUFFERS:
678 if (!ctx->Extensions.ARB_shader_atomic_counters)
679 break;
680
681 *params = shProg->NumAtomicBuffers;
682 return;
683 case GL_COMPUTE_WORK_GROUP_SIZE: {
684 int i;
685 if (!_mesa_is_desktop_gl(ctx) || !ctx->Extensions.ARB_compute_shader)
686 break;
687 if (!shProg->LinkStatus) {
688 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(program not "
689 "linked)");
690 return;
691 }
692 if (shProg->_LinkedShaders[MESA_SHADER_COMPUTE] == NULL) {
693 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramiv(no compute "
694 "shaders)");
695 return;
696 }
697 for (i = 0; i < 3; i++)
698 params[i] = shProg->Comp.LocalSize[i];
699 return;
700 }
701 case GL_PROGRAM_SEPARABLE:
702 *params = shProg->SeparateShader;
703 return;
704 default:
705 break;
706 }
707
708 _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname=%s)",
709 _mesa_lookup_enum_by_nr(pname));
710 }
711
712
713 /**
714 * glGetShaderiv() - get GLSL shader state
715 */
716 static void
717 get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
718 {
719 struct gl_shader *shader =
720 _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
721
722 if (!shader) {
723 return;
724 }
725
726 switch (pname) {
727 case GL_SHADER_TYPE:
728 *params = shader->Type;
729 break;
730 case GL_DELETE_STATUS:
731 *params = shader->DeletePending;
732 break;
733 case GL_COMPILE_STATUS:
734 *params = shader->CompileStatus;
735 break;
736 case GL_INFO_LOG_LENGTH:
737 *params = shader->InfoLog ? strlen(shader->InfoLog) + 1 : 0;
738 break;
739 case GL_SHADER_SOURCE_LENGTH:
740 *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
741 break;
742 default:
743 _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
744 return;
745 }
746 }
747
748
749 static void
750 get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
751 GLsizei *length, GLchar *infoLog)
752 {
753 struct gl_shader_program *shProg
754 = _mesa_lookup_shader_program(ctx, program);
755 if (!shProg) {
756 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(program)");
757 return;
758 }
759 _mesa_copy_string(infoLog, bufSize, length, shProg->InfoLog);
760 }
761
762
763 static void
764 get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
765 GLsizei *length, GLchar *infoLog)
766 {
767 struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
768 if (!sh) {
769 _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(shader)");
770 return;
771 }
772 _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
773 }
774
775
776 /**
777 * Return shader source code.
778 */
779 static void
780 get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
781 GLsizei *length, GLchar *sourceOut)
782 {
783 struct gl_shader *sh;
784 sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
785 if (!sh) {
786 return;
787 }
788 _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
789 }
790
791
792 /**
793 * Set/replace shader source code. A helper function used by
794 * glShaderSource[ARB].
795 */
796 static void
797 shader_source(struct gl_context *ctx, GLuint shader, const GLchar *source)
798 {
799 struct gl_shader *sh;
800
801 sh = _mesa_lookup_shader_err(ctx, shader, "glShaderSource");
802 if (!sh)
803 return;
804
805 /* free old shader source string and install new one */
806 free((void *)sh->Source);
807 sh->Source = source;
808 sh->CompileStatus = GL_FALSE;
809 #ifdef DEBUG
810 sh->SourceChecksum = _mesa_str_checksum(sh->Source);
811 #endif
812 }
813
814
815 /**
816 * Compile a shader.
817 */
818 static void
819 compile_shader(struct gl_context *ctx, GLuint shaderObj)
820 {
821 struct gl_shader *sh;
822 struct gl_shader_compiler_options *options;
823
824 sh = _mesa_lookup_shader_err(ctx, shaderObj, "glCompileShader");
825 if (!sh)
826 return;
827
828 options = &ctx->Const.ShaderCompilerOptions[sh->Stage];
829
830 /* set default pragma state for shader */
831 sh->Pragmas = options->DefaultPragmas;
832
833 if (!sh->Source) {
834 /* If the user called glCompileShader without first calling
835 * glShaderSource, we should fail to compile, but not raise a GL_ERROR.
836 */
837 sh->CompileStatus = GL_FALSE;
838 } else {
839 if (ctx->_Shader->Flags & GLSL_DUMP) {
840 fprintf(stderr, "GLSL source for %s shader %d:\n",
841 _mesa_shader_stage_to_string(sh->Stage), sh->Name);
842 fprintf(stderr, "%s\n", sh->Source);
843 fflush(stderr);
844 }
845
846 /* this call will set the shader->CompileStatus field to indicate if
847 * compilation was successful.
848 */
849 _mesa_glsl_compile_shader(ctx, sh, false, false);
850
851 if (ctx->_Shader->Flags & GLSL_LOG) {
852 _mesa_write_shader_to_file(sh);
853 }
854
855 if (ctx->_Shader->Flags & GLSL_DUMP) {
856 if (sh->CompileStatus) {
857 fprintf(stderr, "GLSL IR for shader %d:\n", sh->Name);
858 _mesa_print_ir(stderr, sh->ir, NULL);
859 fprintf(stderr, "\n\n");
860 } else {
861 fprintf(stderr, "GLSL shader %d failed to compile.\n", sh->Name);
862 }
863 if (sh->InfoLog && sh->InfoLog[0] != 0) {
864 fprintf(stderr, "GLSL shader %d info log:\n", sh->Name);
865 fprintf(stderr, "%s\n", sh->InfoLog);
866 }
867 fflush(stderr);
868 }
869
870 }
871
872 if (!sh->CompileStatus) {
873 if (ctx->_Shader->Flags & GLSL_DUMP_ON_ERROR) {
874 fprintf(stderr, "GLSL source for %s shader %d:\n",
875 _mesa_shader_stage_to_string(sh->Stage), sh->Name);
876 fprintf(stderr, "%s\n", sh->Source);
877 fprintf(stderr, "Info Log:\n%s\n", sh->InfoLog);
878 fflush(stderr);
879 }
880
881 if (ctx->_Shader->Flags & GLSL_REPORT_ERRORS) {
882 _mesa_debug(ctx, "Error compiling shader %u:\n%s\n",
883 sh->Name, sh->InfoLog);
884 }
885 }
886 }
887
888
889 /**
890 * Link a program's shaders.
891 */
892 static void
893 link_program(struct gl_context *ctx, GLuint program)
894 {
895 struct gl_shader_program *shProg;
896
897 shProg = _mesa_lookup_shader_program_err(ctx, program, "glLinkProgram");
898 if (!shProg)
899 return;
900
901 /* From the ARB_transform_feedback2 specification:
902 * "The error INVALID_OPERATION is generated by LinkProgram if <program> is
903 * the name of a program being used by one or more transform feedback
904 * objects, even if the objects are not currently bound or are paused."
905 */
906 if (_mesa_transform_feedback_is_using_program(ctx, shProg)) {
907 _mesa_error(ctx, GL_INVALID_OPERATION,
908 "glLinkProgram(transform feedback is using the program)");
909 return;
910 }
911
912 FLUSH_VERTICES(ctx, _NEW_PROGRAM);
913
914 _mesa_glsl_link_shader(ctx, shProg);
915
916 if (shProg->LinkStatus == GL_FALSE &&
917 (ctx->_Shader->Flags & GLSL_REPORT_ERRORS)) {
918 _mesa_debug(ctx, "Error linking program %u:\n%s\n",
919 shProg->Name, shProg->InfoLog);
920 }
921
922 /* debug code */
923 if (0) {
924 GLuint i;
925
926 printf("Link %u shaders in program %u: %s\n",
927 shProg->NumShaders, shProg->Name,
928 shProg->LinkStatus ? "Success" : "Failed");
929
930 for (i = 0; i < shProg->NumShaders; i++) {
931 printf(" shader %u, type 0x%x\n",
932 shProg->Shaders[i]->Name,
933 shProg->Shaders[i]->Type);
934 }
935 }
936 }
937
938
939 /**
940 * Print basic shader info (for debug).
941 */
942 static void
943 print_shader_info(const struct gl_shader_program *shProg)
944 {
945 GLuint i;
946
947 printf("Mesa: glUseProgram(%u)\n", shProg->Name);
948 for (i = 0; i < shProg->NumShaders; i++) {
949 printf(" %s shader %u, checksum %u\n",
950 _mesa_shader_stage_to_string(shProg->Shaders[i]->Stage),
951 shProg->Shaders[i]->Name,
952 shProg->Shaders[i]->SourceChecksum);
953 }
954 if (shProg->_LinkedShaders[MESA_SHADER_VERTEX])
955 printf(" vert prog %u\n",
956 shProg->_LinkedShaders[MESA_SHADER_VERTEX]->Program->Id);
957 if (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT])
958 printf(" frag prog %u\n",
959 shProg->_LinkedShaders[MESA_SHADER_FRAGMENT]->Program->Id);
960 if (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY])
961 printf(" geom prog %u\n",
962 shProg->_LinkedShaders[MESA_SHADER_GEOMETRY]->Program->Id);
963 }
964
965
966 /**
967 * Use the named shader program for subsequent glUniform calls
968 */
969 void
970 _mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
971 const char *caller)
972 {
973 if ((shProg != NULL) && !shProg->LinkStatus) {
974 _mesa_error(ctx, GL_INVALID_OPERATION,
975 "%s(program %u not linked)", caller, shProg->Name);
976 return;
977 }
978
979 if (ctx->Shader.ActiveProgram != shProg) {
980 _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
981 }
982 }
983
984 /**
985 */
986 static void
987 use_shader_program(struct gl_context *ctx, GLenum type,
988 struct gl_shader_program *shProg,
989 struct gl_pipeline_object *shTarget)
990 {
991 struct gl_shader_program **target;
992 gl_shader_stage stage = _mesa_shader_enum_to_shader_stage(type);
993
994 target = &shTarget->CurrentProgram[stage];
995 if ((shProg == NULL) || (shProg->_LinkedShaders[stage] == NULL))
996 shProg = NULL;
997
998 if (*target != shProg) {
999 /* Program is current, flush it */
1000 if (shTarget == ctx->_Shader) {
1001 FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS);
1002 }
1003
1004 /* If the shader is also bound as the current rendering shader, unbind
1005 * it from that binding point as well. This ensures that the correct
1006 * semantics of glDeleteProgram are maintained.
1007 */
1008 switch (type) {
1009 case GL_VERTEX_SHADER:
1010 /* Empty for now. */
1011 break;
1012 case GL_GEOMETRY_SHADER_ARB:
1013 /* Empty for now. */
1014 break;
1015 case GL_COMPUTE_SHADER:
1016 /* Empty for now. */
1017 break;
1018 case GL_FRAGMENT_SHADER:
1019 if (*target == ctx->_Shader->_CurrentFragmentProgram) {
1020 _mesa_reference_shader_program(ctx,
1021 &ctx->_Shader->_CurrentFragmentProgram,
1022 NULL);
1023 }
1024 break;
1025 }
1026
1027 _mesa_reference_shader_program(ctx, target, shProg);
1028 return;
1029 }
1030 }
1031
1032 /**
1033 * Use the named shader program for subsequent rendering.
1034 */
1035 void
1036 _mesa_use_program(struct gl_context *ctx, struct gl_shader_program *shProg)
1037 {
1038 use_shader_program(ctx, GL_VERTEX_SHADER, shProg, &ctx->Shader);
1039 use_shader_program(ctx, GL_GEOMETRY_SHADER_ARB, shProg, &ctx->Shader);
1040 use_shader_program(ctx, GL_FRAGMENT_SHADER, shProg, &ctx->Shader);
1041 use_shader_program(ctx, GL_COMPUTE_SHADER, shProg, &ctx->Shader);
1042 _mesa_active_program(ctx, shProg, "glUseProgram");
1043
1044 if (ctx->Driver.UseProgram)
1045 ctx->Driver.UseProgram(ctx, shProg);
1046 }
1047
1048
1049 /**
1050 * Do validation of the given shader program.
1051 * \param errMsg returns error message if validation fails.
1052 * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
1053 */
1054 static GLboolean
1055 validate_shader_program(const struct gl_shader_program *shProg,
1056 char *errMsg)
1057 {
1058 if (!shProg->LinkStatus) {
1059 return GL_FALSE;
1060 }
1061
1062 /* From the GL spec, a program is invalid if any of these are true:
1063
1064 any two active samplers in the current program object are of
1065 different types, but refer to the same texture image unit,
1066
1067 any active sampler in the current program object refers to a texture
1068 image unit where fixed-function fragment processing accesses a
1069 texture target that does not match the sampler type, or
1070
1071 the sum of the number of active samplers in the program and the
1072 number of texture image units enabled for fixed-function fragment
1073 processing exceeds the combined limit on the total number of texture
1074 image units allowed.
1075 */
1076
1077
1078 /*
1079 * Check: any two active samplers in the current program object are of
1080 * different types, but refer to the same texture image unit,
1081 */
1082 if (!_mesa_sampler_uniforms_are_valid(shProg, errMsg, 100))
1083 return GL_FALSE;
1084
1085 return GL_TRUE;
1086 }
1087
1088
1089 /**
1090 * Called via glValidateProgram()
1091 */
1092 static void
1093 validate_program(struct gl_context *ctx, GLuint program)
1094 {
1095 struct gl_shader_program *shProg;
1096 char errMsg[100] = "";
1097
1098 shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
1099 if (!shProg) {
1100 return;
1101 }
1102
1103 shProg->Validated = validate_shader_program(shProg, errMsg);
1104 if (!shProg->Validated) {
1105 /* update info log */
1106 if (shProg->InfoLog) {
1107 ralloc_free(shProg->InfoLog);
1108 }
1109 shProg->InfoLog = ralloc_strdup(shProg, errMsg);
1110 }
1111 }
1112
1113
1114
1115 void GLAPIENTRY
1116 _mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
1117 {
1118 GET_CURRENT_CONTEXT(ctx);
1119 attach_shader(ctx, program, shader);
1120 }
1121
1122
1123 void GLAPIENTRY
1124 _mesa_AttachShader(GLuint program, GLuint shader)
1125 {
1126 GET_CURRENT_CONTEXT(ctx);
1127 attach_shader(ctx, program, shader);
1128 }
1129
1130
1131 void GLAPIENTRY
1132 _mesa_CompileShader(GLhandleARB shaderObj)
1133 {
1134 GET_CURRENT_CONTEXT(ctx);
1135 if (MESA_VERBOSE & VERBOSE_API)
1136 _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
1137 compile_shader(ctx, shaderObj);
1138 }
1139
1140
1141 GLuint GLAPIENTRY
1142 _mesa_CreateShader(GLenum type)
1143 {
1144 GET_CURRENT_CONTEXT(ctx);
1145 if (MESA_VERBOSE & VERBOSE_API)
1146 _mesa_debug(ctx, "glCreateShader %s\n", _mesa_lookup_enum_by_nr(type));
1147 return create_shader(ctx, type);
1148 }
1149
1150
1151 GLhandleARB GLAPIENTRY
1152 _mesa_CreateShaderObjectARB(GLenum type)
1153 {
1154 GET_CURRENT_CONTEXT(ctx);
1155 return create_shader(ctx, type);
1156 }
1157
1158
1159 GLuint GLAPIENTRY
1160 _mesa_CreateProgram(void)
1161 {
1162 GET_CURRENT_CONTEXT(ctx);
1163 if (MESA_VERBOSE & VERBOSE_API)
1164 _mesa_debug(ctx, "glCreateProgram\n");
1165 return create_shader_program(ctx);
1166 }
1167
1168
1169 GLhandleARB GLAPIENTRY
1170 _mesa_CreateProgramObjectARB(void)
1171 {
1172 GET_CURRENT_CONTEXT(ctx);
1173 return create_shader_program(ctx);
1174 }
1175
1176
1177 void GLAPIENTRY
1178 _mesa_DeleteObjectARB(GLhandleARB obj)
1179 {
1180 if (MESA_VERBOSE & VERBOSE_API) {
1181 GET_CURRENT_CONTEXT(ctx);
1182 _mesa_debug(ctx, "glDeleteObjectARB(%u)\n", obj);
1183 }
1184
1185 if (obj) {
1186 GET_CURRENT_CONTEXT(ctx);
1187 FLUSH_VERTICES(ctx, 0);
1188 if (is_program(ctx, obj)) {
1189 delete_shader_program(ctx, obj);
1190 }
1191 else if (is_shader(ctx, obj)) {
1192 delete_shader(ctx, obj);
1193 }
1194 else {
1195 /* error? */
1196 }
1197 }
1198 }
1199
1200
1201 void GLAPIENTRY
1202 _mesa_DeleteProgram(GLuint name)
1203 {
1204 if (name) {
1205 GET_CURRENT_CONTEXT(ctx);
1206 FLUSH_VERTICES(ctx, 0);
1207 delete_shader_program(ctx, name);
1208 }
1209 }
1210
1211
1212 void GLAPIENTRY
1213 _mesa_DeleteShader(GLuint name)
1214 {
1215 if (name) {
1216 GET_CURRENT_CONTEXT(ctx);
1217 FLUSH_VERTICES(ctx, 0);
1218 delete_shader(ctx, name);
1219 }
1220 }
1221
1222
1223 void GLAPIENTRY
1224 _mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
1225 {
1226 GET_CURRENT_CONTEXT(ctx);
1227 detach_shader(ctx, program, shader);
1228 }
1229
1230
1231 void GLAPIENTRY
1232 _mesa_DetachShader(GLuint program, GLuint shader)
1233 {
1234 GET_CURRENT_CONTEXT(ctx);
1235 detach_shader(ctx, program, shader);
1236 }
1237
1238
1239 void GLAPIENTRY
1240 _mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
1241 GLsizei * count, GLhandleARB * obj)
1242 {
1243 GET_CURRENT_CONTEXT(ctx);
1244 get_attached_shaders(ctx, container, maxCount, count, obj);
1245 }
1246
1247
1248 void GLAPIENTRY
1249 _mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
1250 GLsizei *count, GLuint *obj)
1251 {
1252 GET_CURRENT_CONTEXT(ctx);
1253 get_attached_shaders(ctx, program, maxCount, count, obj);
1254 }
1255
1256
1257 void GLAPIENTRY
1258 _mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
1259 GLcharARB * infoLog)
1260 {
1261 GET_CURRENT_CONTEXT(ctx);
1262 if (is_program(ctx, object)) {
1263 get_program_info_log(ctx, object, maxLength, length, infoLog);
1264 }
1265 else if (is_shader(ctx, object)) {
1266 get_shader_info_log(ctx, object, maxLength, length, infoLog);
1267 }
1268 else {
1269 _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
1270 }
1271 }
1272
1273
1274 void GLAPIENTRY
1275 _mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
1276 {
1277 GET_CURRENT_CONTEXT(ctx);
1278 /* Implement in terms of GetProgramiv, GetShaderiv */
1279 if (is_program(ctx, object)) {
1280 if (pname == GL_OBJECT_TYPE_ARB) {
1281 *params = GL_PROGRAM_OBJECT_ARB;
1282 }
1283 else {
1284 get_programiv(ctx, object, pname, params);
1285 }
1286 }
1287 else if (is_shader(ctx, object)) {
1288 if (pname == GL_OBJECT_TYPE_ARB) {
1289 *params = GL_SHADER_OBJECT_ARB;
1290 }
1291 else {
1292 get_shaderiv(ctx, object, pname, params);
1293 }
1294 }
1295 else {
1296 _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
1297 }
1298 }
1299
1300
1301 void GLAPIENTRY
1302 _mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
1303 GLfloat *params)
1304 {
1305 GLint iparams[1]; /* XXX is one element enough? */
1306 _mesa_GetObjectParameterivARB(object, pname, iparams);
1307 params[0] = (GLfloat) iparams[0];
1308 }
1309
1310
1311 void GLAPIENTRY
1312 _mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
1313 {
1314 GET_CURRENT_CONTEXT(ctx);
1315 get_programiv(ctx, program, pname, params);
1316 }
1317
1318
1319 void GLAPIENTRY
1320 _mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
1321 {
1322 GET_CURRENT_CONTEXT(ctx);
1323 get_shaderiv(ctx, shader, pname, params);
1324 }
1325
1326
1327 void GLAPIENTRY
1328 _mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
1329 GLsizei *length, GLchar *infoLog)
1330 {
1331 GET_CURRENT_CONTEXT(ctx);
1332 get_program_info_log(ctx, program, bufSize, length, infoLog);
1333 }
1334
1335
1336 void GLAPIENTRY
1337 _mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
1338 GLsizei *length, GLchar *infoLog)
1339 {
1340 GET_CURRENT_CONTEXT(ctx);
1341 get_shader_info_log(ctx, shader, bufSize, length, infoLog);
1342 }
1343
1344
1345 void GLAPIENTRY
1346 _mesa_GetShaderSource(GLhandleARB shader, GLsizei maxLength,
1347 GLsizei *length, GLcharARB *sourceOut)
1348 {
1349 GET_CURRENT_CONTEXT(ctx);
1350 get_shader_source(ctx, shader, maxLength, length, sourceOut);
1351 }
1352
1353
1354 GLhandleARB GLAPIENTRY
1355 _mesa_GetHandleARB(GLenum pname)
1356 {
1357 GET_CURRENT_CONTEXT(ctx);
1358 return get_handle(ctx, pname);
1359 }
1360
1361
1362 GLboolean GLAPIENTRY
1363 _mesa_IsProgram(GLuint name)
1364 {
1365 GET_CURRENT_CONTEXT(ctx);
1366 return is_program(ctx, name);
1367 }
1368
1369
1370 GLboolean GLAPIENTRY
1371 _mesa_IsShader(GLuint name)
1372 {
1373 GET_CURRENT_CONTEXT(ctx);
1374 return is_shader(ctx, name);
1375 }
1376
1377
1378 void GLAPIENTRY
1379 _mesa_LinkProgram(GLhandleARB programObj)
1380 {
1381 GET_CURRENT_CONTEXT(ctx);
1382 link_program(ctx, programObj);
1383 }
1384
1385
1386
1387 /**
1388 * Read shader source code from a file.
1389 * Useful for debugging to override an app's shader.
1390 */
1391 static GLcharARB *
1392 read_shader(const char *fname)
1393 {
1394 int shader_size = 0;
1395 FILE *f = fopen(fname, "r");
1396 GLcharARB *buffer, *shader;
1397 int len;
1398
1399 if (!f) {
1400 return NULL;
1401 }
1402
1403 /* allocate enough room for the entire shader */
1404 fseek(f, 0, SEEK_END);
1405 shader_size = ftell(f);
1406 rewind(f);
1407 assert(shader_size);
1408
1409 /* add one for terminating zero */
1410 shader_size++;
1411
1412 buffer = malloc(shader_size);
1413 assert(buffer);
1414
1415 len = fread(buffer, 1, shader_size, f);
1416 buffer[len] = 0;
1417
1418 fclose(f);
1419
1420 shader = _mesa_strdup(buffer);
1421 free(buffer);
1422
1423 return shader;
1424 }
1425
1426
1427 /**
1428 * Called via glShaderSource() and glShaderSourceARB() API functions.
1429 * Basically, concatenate the source code strings into one long string
1430 * and pass it to _mesa_shader_source().
1431 */
1432 void GLAPIENTRY
1433 _mesa_ShaderSource(GLhandleARB shaderObj, GLsizei count,
1434 const GLcharARB * const * string, const GLint * length)
1435 {
1436 GET_CURRENT_CONTEXT(ctx);
1437 GLint *offsets;
1438 GLsizei i, totalLength;
1439 GLcharARB *source;
1440 GLuint checksum;
1441
1442 if (!shaderObj || string == NULL) {
1443 _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
1444 return;
1445 }
1446
1447 /*
1448 * This array holds offsets of where the appropriate string ends, thus the
1449 * last element will be set to the total length of the source code.
1450 */
1451 offsets = malloc(count * sizeof(GLint));
1452 if (offsets == NULL) {
1453 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1454 return;
1455 }
1456
1457 for (i = 0; i < count; i++) {
1458 if (string[i] == NULL) {
1459 free((GLvoid *) offsets);
1460 _mesa_error(ctx, GL_INVALID_OPERATION,
1461 "glShaderSourceARB(null string)");
1462 return;
1463 }
1464 if (length == NULL || length[i] < 0)
1465 offsets[i] = strlen(string[i]);
1466 else
1467 offsets[i] = length[i];
1468 /* accumulate string lengths */
1469 if (i > 0)
1470 offsets[i] += offsets[i - 1];
1471 }
1472
1473 /* Total length of source string is sum off all strings plus two.
1474 * One extra byte for terminating zero, another extra byte to silence
1475 * valgrind warnings in the parser/grammer code.
1476 */
1477 totalLength = offsets[count - 1] + 2;
1478 source = malloc(totalLength * sizeof(GLcharARB));
1479 if (source == NULL) {
1480 free((GLvoid *) offsets);
1481 _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
1482 return;
1483 }
1484
1485 for (i = 0; i < count; i++) {
1486 GLint start = (i > 0) ? offsets[i - 1] : 0;
1487 memcpy(source + start, string[i],
1488 (offsets[i] - start) * sizeof(GLcharARB));
1489 }
1490 source[totalLength - 1] = '\0';
1491 source[totalLength - 2] = '\0';
1492
1493 if (SHADER_SUBST) {
1494 /* Compute the shader's source code checksum then try to open a file
1495 * named newshader_<CHECKSUM>. If it exists, use it in place of the
1496 * original shader source code. For debugging.
1497 */
1498 char filename[100];
1499 GLcharARB *newSource;
1500
1501 checksum = _mesa_str_checksum(source);
1502
1503 _mesa_snprintf(filename, sizeof(filename), "newshader_%d", checksum);
1504
1505 newSource = read_shader(filename);
1506 if (newSource) {
1507 fprintf(stderr, "Mesa: Replacing shader %u chksum=%d with %s\n",
1508 shaderObj, checksum, filename);
1509 free(source);
1510 source = newSource;
1511 }
1512 }
1513
1514 shader_source(ctx, shaderObj, source);
1515
1516 if (SHADER_SUBST) {
1517 struct gl_shader *sh = _mesa_lookup_shader(ctx, shaderObj);
1518 if (sh)
1519 sh->SourceChecksum = checksum; /* save original checksum */
1520 }
1521
1522 free(offsets);
1523 }
1524
1525
1526 void GLAPIENTRY
1527 _mesa_UseProgram(GLhandleARB program)
1528 {
1529 GET_CURRENT_CONTEXT(ctx);
1530 struct gl_shader_program *shProg;
1531
1532 if (_mesa_is_xfb_active_and_unpaused(ctx)) {
1533 _mesa_error(ctx, GL_INVALID_OPERATION,
1534 "glUseProgram(transform feedback active)");
1535 return;
1536 }
1537
1538 if (program) {
1539 shProg = _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
1540 if (!shProg) {
1541 return;
1542 }
1543 if (!shProg->LinkStatus) {
1544 _mesa_error(ctx, GL_INVALID_OPERATION,
1545 "glUseProgram(program %u not linked)", program);
1546 return;
1547 }
1548
1549 /* debug code */
1550 if (ctx->_Shader->Flags & GLSL_USE_PROG) {
1551 print_shader_info(shProg);
1552 }
1553 }
1554 else {
1555 shProg = NULL;
1556 }
1557
1558 /* The ARB_separate_shader_object spec says:
1559 *
1560 * "The executable code for an individual shader stage is taken from
1561 * the current program for that stage. If there is a current program
1562 * object established by UseProgram, that program is considered current
1563 * for all stages. Otherwise, if there is a bound program pipeline
1564 * object (section 2.14.PPO), the program bound to the appropriate
1565 * stage of the pipeline object is considered current."
1566 */
1567 if (program) {
1568 /* Attach shader state to the binding point */
1569 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, &ctx->Shader);
1570 /* Update the program */
1571 _mesa_use_program(ctx, shProg);
1572 } else {
1573 /* Must be done first: detach the progam */
1574 _mesa_use_program(ctx, shProg);
1575 /* Unattach shader_state binding point */
1576 _mesa_reference_pipeline_object(ctx, &ctx->_Shader, ctx->Pipeline.Default);
1577 /* If a pipeline was bound, rebind it */
1578 if (ctx->Pipeline.Current) {
1579 _mesa_BindProgramPipeline(ctx->Pipeline.Current->Name);
1580 }
1581 }
1582 }
1583
1584
1585 void GLAPIENTRY
1586 _mesa_ValidateProgram(GLhandleARB program)
1587 {
1588 GET_CURRENT_CONTEXT(ctx);
1589 validate_program(ctx, program);
1590 }
1591
1592
1593 /**
1594 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1595 */
1596 void GLAPIENTRY
1597 _mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
1598 GLint* range, GLint* precision)
1599 {
1600 const struct gl_program_constants *limits;
1601 const struct gl_precision *p;
1602 GET_CURRENT_CONTEXT(ctx);
1603
1604 switch (shadertype) {
1605 case GL_VERTEX_SHADER:
1606 limits = &ctx->Const.Program[MESA_SHADER_VERTEX];
1607 break;
1608 case GL_FRAGMENT_SHADER:
1609 limits = &ctx->Const.Program[MESA_SHADER_FRAGMENT];
1610 break;
1611 default:
1612 _mesa_error(ctx, GL_INVALID_ENUM,
1613 "glGetShaderPrecisionFormat(shadertype)");
1614 return;
1615 }
1616
1617 switch (precisiontype) {
1618 case GL_LOW_FLOAT:
1619 p = &limits->LowFloat;
1620 break;
1621 case GL_MEDIUM_FLOAT:
1622 p = &limits->MediumFloat;
1623 break;
1624 case GL_HIGH_FLOAT:
1625 p = &limits->HighFloat;
1626 break;
1627 case GL_LOW_INT:
1628 p = &limits->LowInt;
1629 break;
1630 case GL_MEDIUM_INT:
1631 p = &limits->MediumInt;
1632 break;
1633 case GL_HIGH_INT:
1634 p = &limits->HighInt;
1635 break;
1636 default:
1637 _mesa_error(ctx, GL_INVALID_ENUM,
1638 "glGetShaderPrecisionFormat(precisiontype)");
1639 return;
1640 }
1641
1642 range[0] = p->RangeMin;
1643 range[1] = p->RangeMax;
1644 precision[0] = p->Precision;
1645 }
1646
1647
1648 /**
1649 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1650 */
1651 void GLAPIENTRY
1652 _mesa_ReleaseShaderCompiler(void)
1653 {
1654 _mesa_destroy_shader_compiler_caches();
1655 }
1656
1657
1658 /**
1659 * For OpenGL ES 2.0, GL_ARB_ES2_compatibility
1660 */
1661 void GLAPIENTRY
1662 _mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
1663 const void* binary, GLint length)
1664 {
1665 GET_CURRENT_CONTEXT(ctx);
1666 (void) n;
1667 (void) shaders;
1668 (void) binaryformat;
1669 (void) binary;
1670 (void) length;
1671 _mesa_error(ctx, GL_INVALID_OPERATION, __FUNCTION__);
1672 }
1673
1674
1675 void GLAPIENTRY
1676 _mesa_GetProgramBinary(GLuint program, GLsizei bufSize, GLsizei *length,
1677 GLenum *binaryFormat, GLvoid *binary)
1678 {
1679 struct gl_shader_program *shProg;
1680 GET_CURRENT_CONTEXT(ctx);
1681
1682 shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetProgramBinary");
1683 if (!shProg)
1684 return;
1685
1686 if (!shProg->LinkStatus) {
1687 _mesa_error(ctx, GL_INVALID_OPERATION,
1688 "glGetProgramBinary(program %u not linked)",
1689 shProg->Name);
1690 return;
1691 }
1692
1693 if (bufSize < 0){
1694 _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramBinary(bufSize < 0)");
1695 return;
1696 }
1697
1698 /* The ARB_get_program_binary spec says:
1699 *
1700 * "If <length> is NULL, then no length is returned."
1701 */
1702 if (length != NULL)
1703 *length = 0;
1704
1705 (void) binaryFormat;
1706 (void) binary;
1707 }
1708
1709 void GLAPIENTRY
1710 _mesa_ProgramBinary(GLuint program, GLenum binaryFormat,
1711 const GLvoid *binary, GLsizei length)
1712 {
1713 struct gl_shader_program *shProg;
1714 GET_CURRENT_CONTEXT(ctx);
1715
1716 shProg = _mesa_lookup_shader_program_err(ctx, program, "glProgramBinary");
1717 if (!shProg)
1718 return;
1719
1720 (void) binaryFormat;
1721 (void) binary;
1722 (void) length;
1723 _mesa_error(ctx, GL_INVALID_OPERATION, __FUNCTION__);
1724 }
1725
1726
1727 void GLAPIENTRY
1728 _mesa_ProgramParameteri(GLuint program, GLenum pname, GLint value)
1729 {
1730 struct gl_shader_program *shProg;
1731 GET_CURRENT_CONTEXT(ctx);
1732
1733 shProg = _mesa_lookup_shader_program_err(ctx, program,
1734 "glProgramParameteri");
1735 if (!shProg)
1736 return;
1737
1738 switch (pname) {
1739 case GL_PROGRAM_BINARY_RETRIEVABLE_HINT:
1740 /* This enum isn't part of the OES extension for OpenGL ES 2.0, but it
1741 * is part of OpenGL ES 3.0. For the ES2 case, this function shouldn't
1742 * even be in the dispatch table, so we shouldn't need to expclicitly
1743 * check here.
1744 *
1745 * On desktop, we ignore the 3.0+ requirement because it is silly.
1746 */
1747
1748 /* The ARB_get_program_binary extension spec says:
1749 *
1750 * "An INVALID_VALUE error is generated if the <value> argument to
1751 * ProgramParameteri is not TRUE or FALSE."
1752 */
1753 if (value != GL_TRUE && value != GL_FALSE) {
1754 _mesa_error(ctx, GL_INVALID_VALUE,
1755 "glProgramParameteri(pname=%s, value=%d): "
1756 "value must be 0 or 1.",
1757 _mesa_lookup_enum_by_nr(pname),
1758 value);
1759 return;
1760 }
1761
1762 /* No need to notify the driver. Any changes will actually take effect
1763 * the next time the shader is linked.
1764 *
1765 * The ARB_get_program_binary extension spec says:
1766 *
1767 * "To indicate that a program binary is likely to be retrieved,
1768 * ProgramParameteri should be called with <pname>
1769 * PROGRAM_BINARY_RETRIEVABLE_HINT and <value> TRUE. This setting
1770 * will not be in effect until the next time LinkProgram or
1771 * ProgramBinary has been called successfully."
1772 *
1773 * The resloution of issue 9 in the extension spec also says:
1774 *
1775 * "The application may use the PROGRAM_BINARY_RETRIEVABLE_HINT hint
1776 * to indicate to the GL implementation that this program will
1777 * likely be saved with GetProgramBinary at some point. This will
1778 * give the GL implementation the opportunity to track any state
1779 * changes made to the program before being saved such that when it
1780 * is loaded again a recompile can be avoided."
1781 */
1782 shProg->BinaryRetreivableHint = value;
1783 return;
1784
1785 case GL_PROGRAM_SEPARABLE:
1786 /* Spec imply that the behavior is the same as ARB_get_program_binary
1787 * Chapter 7.3 Program Objects
1788 */
1789 if (value != GL_TRUE && value != GL_FALSE) {
1790 _mesa_error(ctx, GL_INVALID_VALUE,
1791 "glProgramParameteri(pname=%s, value=%d): "
1792 "value must be 0 or 1.",
1793 _mesa_lookup_enum_by_nr(pname),
1794 value);
1795 return;
1796 }
1797 shProg->SeparateShader = value;
1798 return;
1799
1800 default:
1801 break;
1802 }
1803
1804 _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteri(pname=%s)",
1805 _mesa_lookup_enum_by_nr(pname));
1806 }
1807
1808 void
1809 _mesa_use_shader_program(struct gl_context *ctx, GLenum type,
1810 struct gl_shader_program *shProg,
1811 struct gl_pipeline_object *shTarget)
1812 {
1813 use_shader_program(ctx, type, shProg, shTarget);
1814
1815 if (ctx->Driver.UseProgram)
1816 ctx->Driver.UseProgram(ctx, shProg);
1817 }
1818
1819
1820 static GLuint
1821 _mesa_create_shader_program(struct gl_context* ctx, GLboolean separate,
1822 GLenum type, GLsizei count, const GLchar* const *strings)
1823 {
1824 const GLuint shader = create_shader(ctx, type);
1825 GLuint program = 0;
1826
1827 if (shader) {
1828 _mesa_ShaderSource(shader, count, strings, NULL);
1829
1830 compile_shader(ctx, shader);
1831
1832 program = create_shader_program(ctx);
1833 if (program) {
1834 struct gl_shader_program *shProg;
1835 struct gl_shader *sh;
1836 GLint compiled = GL_FALSE;
1837
1838 shProg = _mesa_lookup_shader_program(ctx, program);
1839 sh = _mesa_lookup_shader(ctx, shader);
1840
1841 shProg->SeparateShader = separate;
1842
1843 get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
1844 if (compiled) {
1845 attach_shader(ctx, program, shader);
1846 link_program(ctx, program);
1847 detach_shader(ctx, program, shader);
1848
1849 #if 0
1850 /* Possibly... */
1851 if (active-user-defined-varyings-in-linked-program) {
1852 append-error-to-info-log;
1853 shProg->LinkStatus = GL_FALSE;
1854 }
1855 #endif
1856 }
1857
1858 ralloc_strcat(&shProg->InfoLog, sh->InfoLog);
1859 }
1860
1861 delete_shader(ctx, shader);
1862 }
1863
1864 return program;
1865 }
1866
1867
1868 /**
1869 * Copy program-specific data generated by linking from the gl_shader_program
1870 * object to a specific gl_program object.
1871 */
1872 void
1873 _mesa_copy_linked_program_data(gl_shader_stage type,
1874 const struct gl_shader_program *src,
1875 struct gl_program *dst)
1876 {
1877 switch (type) {
1878 case MESA_SHADER_VERTEX:
1879 dst->UsesClipDistanceOut = src->Vert.UsesClipDistance;
1880 break;
1881 case MESA_SHADER_GEOMETRY: {
1882 struct gl_geometry_program *dst_gp = (struct gl_geometry_program *) dst;
1883 dst_gp->VerticesIn = src->Geom.VerticesIn;
1884 dst_gp->VerticesOut = src->Geom.VerticesOut;
1885 dst_gp->Invocations = src->Geom.Invocations;
1886 dst_gp->InputType = src->Geom.InputType;
1887 dst_gp->OutputType = src->Geom.OutputType;
1888 dst->UsesClipDistanceOut = src->Geom.UsesClipDistance;
1889 dst_gp->UsesEndPrimitive = src->Geom.UsesEndPrimitive;
1890 dst_gp->UsesStreams = src->Geom.UsesStreams;
1891 }
1892 break;
1893 case MESA_SHADER_FRAGMENT: {
1894 struct gl_fragment_program *dst_fp = (struct gl_fragment_program *) dst;
1895 dst_fp->FragDepthLayout = src->FragDepthLayout;
1896 }
1897 break;
1898 case MESA_SHADER_COMPUTE: {
1899 struct gl_compute_program *dst_cp = (struct gl_compute_program *) dst;
1900 int i;
1901 for (i = 0; i < 3; i++)
1902 dst_cp->LocalSize[i] = src->Comp.LocalSize[i];
1903 }
1904 break;
1905 default:
1906 break;
1907 }
1908 }
1909
1910 /**
1911 * ARB_separate_shader_objects: Compile & Link Program
1912 */
1913 GLuint GLAPIENTRY
1914 _mesa_CreateShaderProgramv(GLenum type, GLsizei count,
1915 const GLchar* const *strings)
1916 {
1917 GET_CURRENT_CONTEXT(ctx);
1918
1919 return _mesa_create_shader_program(ctx, GL_TRUE, type, count, strings);
1920 }