mesa: Minor clean ups in _mesa_uniform
[mesa.git] / src / mesa / main / uniform_query.cpp
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 * Copyright © 2010, 2011 Intel Corporation
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a
9 * copy of this software and associated documentation files (the "Software"),
10 * to deal in the Software without restriction, including without limitation
11 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 * and/or sell copies of the Software, and to permit persons to whom the
13 * Software is furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 * OTHER DEALINGS IN THE SOFTWARE.
25 */
26
27 #include <stdlib.h>
28
29 #include "main/core.h"
30 #include "main/context.h"
31 #include "ir.h"
32 #include "ir_uniform.h"
33 #include "program/hash_table.h"
34 #include "../glsl/program.h"
35 #include "../glsl/ir_uniform.h"
36 #include "../glsl/glsl_parser_extras.h"
37 #include "main/shaderapi.h"
38 #include "main/shaderobj.h"
39 #include "uniforms.h"
40
41
42 extern "C" void GLAPIENTRY
43 _mesa_GetActiveUniform(GLuint program, GLuint index,
44 GLsizei maxLength, GLsizei *length, GLint *size,
45 GLenum *type, GLcharARB *nameOut)
46 {
47 GET_CURRENT_CONTEXT(ctx);
48 struct gl_shader_program *shProg =
49 _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
50
51 if (!shProg)
52 return;
53
54 if (index >= shProg->NumUserUniformStorage) {
55 _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniform(index)");
56 return;
57 }
58
59 const struct gl_uniform_storage *const uni = &shProg->UniformStorage[index];
60
61 if (nameOut) {
62 _mesa_get_uniform_name(uni, maxLength, length, nameOut);
63 }
64
65 if (size) {
66 /* array_elements is zero for non-arrays, but the API requires that 1 be
67 * returned.
68 */
69 *size = MAX2(1, uni->array_elements);
70 }
71
72 if (type) {
73 *type = uni->type->gl_type;
74 }
75 }
76
77 extern "C" void GLAPIENTRY
78 _mesa_GetActiveUniformsiv(GLuint program,
79 GLsizei uniformCount,
80 const GLuint *uniformIndices,
81 GLenum pname,
82 GLint *params)
83 {
84 GET_CURRENT_CONTEXT(ctx);
85 struct gl_shader_program *shProg;
86 GLsizei i;
87
88 shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveUniform");
89 if (!shProg)
90 return;
91
92 if (uniformCount < 0) {
93 _mesa_error(ctx, GL_INVALID_VALUE,
94 "glGetActiveUniformsiv(uniformCount < 0)");
95 return;
96 }
97
98 for (i = 0; i < uniformCount; i++) {
99 GLuint index = uniformIndices[i];
100
101 if (index >= shProg->NumUserUniformStorage) {
102 _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveUniformsiv(index)");
103 return;
104 }
105 }
106
107 for (i = 0; i < uniformCount; i++) {
108 GLuint index = uniformIndices[i];
109 const struct gl_uniform_storage *uni = &shProg->UniformStorage[index];
110
111 switch (pname) {
112 case GL_UNIFORM_TYPE:
113 params[i] = uni->type->gl_type;
114 break;
115
116 case GL_UNIFORM_SIZE:
117 /* array_elements is zero for non-arrays, but the API requires that 1 be
118 * returned.
119 */
120 params[i] = MAX2(1, uni->array_elements);
121 break;
122
123 case GL_UNIFORM_NAME_LENGTH:
124 params[i] = strlen(uni->name) + 1;
125
126 /* Page 61 (page 73 of the PDF) in section 2.11 of the OpenGL ES 3.0
127 * spec says:
128 *
129 * "If the active uniform is an array, the uniform name returned
130 * in name will always be the name of the uniform array appended
131 * with "[0]"."
132 */
133 if (uni->array_elements != 0)
134 params[i] += 3;
135 break;
136
137 case GL_UNIFORM_BLOCK_INDEX:
138 params[i] = uni->block_index;
139 break;
140
141 case GL_UNIFORM_OFFSET:
142 params[i] = uni->offset;
143 break;
144
145 case GL_UNIFORM_ARRAY_STRIDE:
146 params[i] = uni->array_stride;
147 break;
148
149 case GL_UNIFORM_MATRIX_STRIDE:
150 params[i] = uni->matrix_stride;
151 break;
152
153 case GL_UNIFORM_IS_ROW_MAJOR:
154 params[i] = uni->row_major;
155 break;
156
157 case GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX:
158 if (!ctx->Extensions.ARB_shader_atomic_counters)
159 goto invalid_enum;
160 params[i] = uni->atomic_buffer_index;
161 break;
162
163 default:
164 goto invalid_enum;
165 }
166 }
167
168 return;
169
170 invalid_enum:
171 _mesa_error(ctx, GL_INVALID_ENUM, "glGetActiveUniformsiv(pname)");
172 }
173
174 static struct gl_uniform_storage *
175 validate_uniform_parameters(struct gl_context *ctx,
176 struct gl_shader_program *shProg,
177 GLint location, GLsizei count,
178 unsigned *array_index,
179 const char *caller,
180 bool negative_one_is_not_valid)
181 {
182 if (!shProg || !shProg->LinkStatus) {
183 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(program not linked)", caller);
184 return NULL;
185 }
186
187 if (location == -1) {
188 /* For glGetUniform, page 264 (page 278 of the PDF) of the OpenGL 2.1
189 * spec says:
190 *
191 * "The error INVALID_OPERATION is generated if program has not been
192 * linked successfully, or if location is not a valid location for
193 * program."
194 *
195 * For glUniform, page 82 (page 96 of the PDF) of the OpenGL 2.1 spec
196 * says:
197 *
198 * "If the value of location is -1, the Uniform* commands will
199 * silently ignore the data passed in, and the current uniform
200 * values will not be changed."
201 *
202 * Allowing -1 for the location parameter of glUniform allows
203 * applications to avoid error paths in the case that, for example, some
204 * uniform variable is removed by the compiler / linker after
205 * optimization. In this case, the new value of the uniform is dropped
206 * on the floor. For the case of glGetUniform, there is nothing
207 * sensible to do for a location of -1.
208 *
209 * The negative_one_is_not_valid flag selects between the two behaviors.
210 */
211 if (negative_one_is_not_valid) {
212 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
213 caller, location);
214 }
215
216 return NULL;
217 }
218
219 /* From page 12 (page 26 of the PDF) of the OpenGL 2.1 spec:
220 *
221 * "If a negative number is provided where an argument of type sizei or
222 * sizeiptr is specified, the error INVALID_VALUE is generated."
223 */
224 if (count < 0) {
225 _mesa_error(ctx, GL_INVALID_VALUE, "%s(count < 0)", caller);
226 return NULL;
227 }
228
229 /* Check that the given location is in bounds of uniform remap table. */
230 if (location >= (GLint) shProg->NumUniformRemapTable) {
231 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
232 caller, location);
233 return NULL;
234 }
235
236 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
237 *
238 * "If any of the following conditions occur, an INVALID_OPERATION
239 * error is generated by the Uniform* commands, and no uniform values
240 * are changed:
241 *
242 * ...
243 *
244 * - if no variable with a location of location exists in the
245 * program object currently in use and location is not -1,
246 * - if count is greater than one, and the uniform declared in the
247 * shader is not an array variable,
248 */
249 if (location < -1 || !shProg->UniformRemapTable[location]) {
250 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
251 caller, location);
252 return NULL;
253 }
254
255 /* If the driver storage pointer in remap table is -1, we ignore silently.
256 *
257 * GL_ARB_explicit_uniform_location spec says:
258 * "What happens if Uniform* is called with an explicitly defined
259 * uniform location, but that uniform is deemed inactive by the
260 * linker?
261 *
262 * RESOLVED: The call is ignored for inactive uniform variables and
263 * no error is generated."
264 *
265 */
266 if (shProg->UniformRemapTable[location] ==
267 INACTIVE_UNIFORM_EXPLICIT_LOCATION)
268 return NULL;
269
270 struct gl_uniform_storage *const uni = shProg->UniformRemapTable[location];
271
272 if (uni->array_elements == 0 && count > 1) {
273 _mesa_error(ctx, GL_INVALID_OPERATION,
274 "%s(count > 1 for non-array, location=%d)",
275 caller, location);
276 return NULL;
277 }
278
279 /* The array index specified by the uniform location is just the uniform
280 * location minus the base location of of the uniform.
281 */
282 *array_index = location - uni->remap_location;
283
284 /* If the uniform is an array, check that array_index is in bounds.
285 * If not an array, check that array_index is zero.
286 * array_index is unsigned so no need to check for less than zero.
287 */
288 const unsigned limit = MAX2(uni->array_elements, 1);
289 if (*array_index >= limit) {
290 _mesa_error(ctx, GL_INVALID_OPERATION, "%s(location=%d)",
291 caller, location);
292 return NULL;
293 }
294 return uni;
295 }
296
297 /**
298 * Called via glGetUniform[fiui]v() to get the current value of a uniform.
299 */
300 extern "C" void
301 _mesa_get_uniform(struct gl_context *ctx, GLuint program, GLint location,
302 GLsizei bufSize, enum glsl_base_type returnType,
303 GLvoid *paramsOut)
304 {
305 struct gl_shader_program *shProg =
306 _mesa_lookup_shader_program_err(ctx, program, "glGetUniformfv");
307 unsigned offset;
308
309 struct gl_uniform_storage *const uni =
310 validate_uniform_parameters(ctx, shProg, location, 1,
311 &offset, "glGetUniform", true);
312 if (uni == NULL)
313 return;
314
315 {
316 unsigned elements = (uni->type->is_sampler())
317 ? 1 : uni->type->components();
318
319 /* Calculate the source base address *BEFORE* modifying elements to
320 * account for the size of the user's buffer.
321 */
322 const union gl_constant_value *const src =
323 &uni->storage[offset * elements];
324
325 assert(returnType == GLSL_TYPE_FLOAT || returnType == GLSL_TYPE_INT ||
326 returnType == GLSL_TYPE_UINT);
327 /* The three (currently) supported types all have the same size,
328 * which is of course the same as their union. That'll change
329 * with glGetUniformdv()...
330 */
331 unsigned bytes = sizeof(src[0]) * elements;
332 if (bufSize < 0 || bytes > (unsigned) bufSize) {
333 _mesa_error( ctx, GL_INVALID_OPERATION,
334 "glGetnUniform*vARB(out of bounds: bufSize is %d,"
335 " but %u bytes are required)", bufSize, bytes );
336 return;
337 }
338
339 /* If the return type and the uniform's native type are "compatible,"
340 * just memcpy the data. If the types are not compatible, perform a
341 * slower convert-and-copy process.
342 */
343 if (returnType == uni->type->base_type
344 || ((returnType == GLSL_TYPE_INT
345 || returnType == GLSL_TYPE_UINT)
346 &&
347 (uni->type->base_type == GLSL_TYPE_INT
348 || uni->type->base_type == GLSL_TYPE_UINT
349 || uni->type->base_type == GLSL_TYPE_SAMPLER))) {
350 memcpy(paramsOut, src, bytes);
351 } else {
352 union gl_constant_value *const dst =
353 (union gl_constant_value *) paramsOut;
354
355 /* This code could be optimized by putting the loop inside the switch
356 * statements. However, this is not expected to be
357 * performance-critical code.
358 */
359 for (unsigned i = 0; i < elements; i++) {
360 switch (returnType) {
361 case GLSL_TYPE_FLOAT:
362 switch (uni->type->base_type) {
363 case GLSL_TYPE_UINT:
364 dst[i].f = (float) src[i].u;
365 break;
366 case GLSL_TYPE_INT:
367 case GLSL_TYPE_SAMPLER:
368 dst[i].f = (float) src[i].i;
369 break;
370 case GLSL_TYPE_BOOL:
371 dst[i].f = src[i].i ? 1.0f : 0.0f;
372 break;
373 default:
374 assert(!"Should not get here.");
375 break;
376 }
377 break;
378
379 case GLSL_TYPE_INT:
380 case GLSL_TYPE_UINT:
381 switch (uni->type->base_type) {
382 case GLSL_TYPE_FLOAT:
383 /* While the GL 3.2 core spec doesn't explicitly
384 * state how conversion of float uniforms to integer
385 * values works, in section 6.2 "State Tables" on
386 * page 267 it says:
387 *
388 * "Unless otherwise specified, when floating
389 * point state is returned as integer values or
390 * integer state is returned as floating-point
391 * values it is converted in the fashion
392 * described in section 6.1.2"
393 *
394 * That section, on page 248, says:
395 *
396 * "If GetIntegerv or GetInteger64v are called,
397 * a floating-point value is rounded to the
398 * nearest integer..."
399 */
400 dst[i].i = IROUND(src[i].f);
401 break;
402 case GLSL_TYPE_BOOL:
403 dst[i].i = src[i].i ? 1 : 0;
404 break;
405 default:
406 assert(!"Should not get here.");
407 break;
408 }
409 break;
410
411 default:
412 assert(!"Should not get here.");
413 break;
414 }
415 }
416 }
417 }
418 }
419
420 static void
421 log_uniform(const void *values, enum glsl_base_type basicType,
422 unsigned rows, unsigned cols, unsigned count,
423 bool transpose,
424 const struct gl_shader_program *shProg,
425 GLint location,
426 const struct gl_uniform_storage *uni)
427 {
428
429 const union gl_constant_value *v = (const union gl_constant_value *) values;
430 const unsigned elems = rows * cols * count;
431 const char *const extra = (cols == 1) ? "uniform" : "uniform matrix";
432
433 printf("Mesa: set program %u %s \"%s\" (loc %d, type \"%s\", "
434 "transpose = %s) to: ",
435 shProg->Name, extra, uni->name, location, uni->type->name,
436 transpose ? "true" : "false");
437 for (unsigned i = 0; i < elems; i++) {
438 if (i != 0 && ((i % rows) == 0))
439 printf(", ");
440
441 switch (basicType) {
442 case GLSL_TYPE_UINT:
443 printf("%u ", v[i].u);
444 break;
445 case GLSL_TYPE_INT:
446 printf("%d ", v[i].i);
447 break;
448 case GLSL_TYPE_FLOAT:
449 printf("%g ", v[i].f);
450 break;
451 default:
452 assert(!"Should not get here.");
453 break;
454 }
455 }
456 printf("\n");
457 fflush(stdout);
458 }
459
460 #if 0
461 static void
462 log_program_parameters(const struct gl_shader_program *shProg)
463 {
464 for (unsigned i = 0; i < MESA_SHADER_STAGES; i++) {
465 if (shProg->_LinkedShaders[i] == NULL)
466 continue;
467
468 const struct gl_program *const prog = shProg->_LinkedShaders[i]->Program;
469
470 printf("Program %d %s shader parameters:\n",
471 shProg->Name, _mesa_shader_stage_to_string(i));
472 for (unsigned j = 0; j < prog->Parameters->NumParameters; j++) {
473 printf("%s: %p %f %f %f %f\n",
474 prog->Parameters->Parameters[j].Name,
475 prog->Parameters->ParameterValues[j],
476 prog->Parameters->ParameterValues[j][0].f,
477 prog->Parameters->ParameterValues[j][1].f,
478 prog->Parameters->ParameterValues[j][2].f,
479 prog->Parameters->ParameterValues[j][3].f);
480 }
481 }
482 fflush(stdout);
483 }
484 #endif
485
486 /**
487 * Propagate some values from uniform backing storage to driver storage
488 *
489 * Values propagated from uniform backing storage to driver storage
490 * have all format / type conversions previously requested by the
491 * driver applied. This function is most often called by the
492 * implementations of \c glUniform1f, etc. and \c glUniformMatrix2f,
493 * etc.
494 *
495 * \param uni Uniform whose data is to be propagated to driver storage
496 * \param array_index If \c uni is an array, this is the element of
497 * the array to be propagated.
498 * \param count Number of array elements to propagate.
499 */
500 extern "C" void
501 _mesa_propagate_uniforms_to_driver_storage(struct gl_uniform_storage *uni,
502 unsigned array_index,
503 unsigned count)
504 {
505 unsigned i;
506
507 /* vector_elements and matrix_columns can be 0 for samplers.
508 */
509 const unsigned components = MAX2(1, uni->type->vector_elements);
510 const unsigned vectors = MAX2(1, uni->type->matrix_columns);
511
512 /* Store the data in the driver's requested type in the driver's storage
513 * areas.
514 */
515 unsigned src_vector_byte_stride = components * 4;
516
517 for (i = 0; i < uni->num_driver_storage; i++) {
518 struct gl_uniform_driver_storage *const store = &uni->driver_storage[i];
519 uint8_t *dst = (uint8_t *) store->data;
520 const unsigned extra_stride =
521 store->element_stride - (vectors * store->vector_stride);
522 const uint8_t *src =
523 (uint8_t *) (&uni->storage[array_index * (components * vectors)].i);
524
525 #if 0
526 printf("%s: %p[%d] components=%u vectors=%u count=%u vector_stride=%u "
527 "extra_stride=%u\n",
528 __func__, dst, array_index, components,
529 vectors, count, store->vector_stride, extra_stride);
530 #endif
531
532 dst += array_index * store->element_stride;
533
534 switch (store->format) {
535 case uniform_native: {
536 unsigned j;
537 unsigned v;
538
539 for (j = 0; j < count; j++) {
540 for (v = 0; v < vectors; v++) {
541 memcpy(dst, src, src_vector_byte_stride);
542 src += src_vector_byte_stride;
543 dst += store->vector_stride;
544 }
545
546 dst += extra_stride;
547 }
548 break;
549 }
550
551 case uniform_int_float: {
552 const int *isrc = (const int *) src;
553 unsigned j;
554 unsigned v;
555 unsigned c;
556
557 for (j = 0; j < count; j++) {
558 for (v = 0; v < vectors; v++) {
559 for (c = 0; c < components; c++) {
560 ((float *) dst)[c] = (float) *isrc;
561 isrc++;
562 }
563
564 dst += store->vector_stride;
565 }
566
567 dst += extra_stride;
568 }
569 break;
570 }
571
572 default:
573 assert(!"Should not get here.");
574 break;
575 }
576 }
577 }
578
579 /**
580 * Called via glUniform*() functions.
581 */
582 extern "C" void
583 _mesa_uniform(struct gl_context *ctx, struct gl_shader_program *shProg,
584 GLint location, GLsizei count,
585 const GLvoid *values,
586 enum glsl_base_type basicType,
587 unsigned src_components)
588 {
589 unsigned offset;
590
591 struct gl_uniform_storage *const uni =
592 validate_uniform_parameters(ctx, shProg, location, count,
593 &offset, "glUniform", false);
594 if (uni == NULL)
595 return;
596
597 /* Verify that the types are compatible.
598 */
599 const unsigned components = uni->type->is_sampler()
600 ? 1 : uni->type->vector_elements;
601
602 bool match;
603 switch (uni->type->base_type) {
604 case GLSL_TYPE_BOOL:
605 match = true;
606 break;
607 case GLSL_TYPE_SAMPLER:
608 case GLSL_TYPE_IMAGE:
609 match = (basicType == GLSL_TYPE_INT);
610 break;
611 default:
612 match = (basicType == uni->type->base_type);
613 break;
614 }
615
616 if (uni->type->is_matrix() || components != src_components || !match) {
617 _mesa_error(ctx, GL_INVALID_OPERATION, "glUniform(type mismatch)");
618 return;
619 }
620
621 if (ctx->_Shader->Flags & GLSL_UNIFORMS) {
622 log_uniform(values, basicType, components, 1, count,
623 false, shProg, location, uni);
624 }
625
626 /* Page 100 (page 116 of the PDF) of the OpenGL 3.0 spec says:
627 *
628 * "Setting a sampler's value to i selects texture image unit number
629 * i. The values of i range from zero to the implementation- dependent
630 * maximum supported number of texture image units."
631 *
632 * In addition, table 2.3, "Summary of GL errors," on page 17 (page 33 of
633 * the PDF) says:
634 *
635 * "Error Description Offending command
636 * ignored?
637 * ...
638 * INVALID_VALUE Numeric argument out of range Yes"
639 *
640 * Based on that, when an invalid sampler is specified, we generate a
641 * GL_INVALID_VALUE error and ignore the command.
642 */
643 if (uni->type->is_sampler()) {
644 for (int i = 0; i < count; i++) {
645 const unsigned texUnit = ((unsigned *) values)[i];
646
647 /* check that the sampler (tex unit index) is legal */
648 if (texUnit >= ctx->Const.MaxCombinedTextureImageUnits) {
649 _mesa_error(ctx, GL_INVALID_VALUE,
650 "glUniform1i(invalid sampler/tex unit index for "
651 "uniform %d)",
652 location);
653 return;
654 }
655 }
656 }
657
658 if (uni->type->is_image()) {
659 for (int i = 0; i < count; i++) {
660 const int unit = ((GLint *) values)[i];
661
662 /* check that the image unit is legal */
663 if (unit < 0 || unit >= (int)ctx->Const.MaxImageUnits) {
664 _mesa_error(ctx, GL_INVALID_VALUE,
665 "glUniform1i(invalid image unit index for uniform %d)",
666 location);
667 return;
668 }
669 }
670 }
671
672 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
673 *
674 * "When loading N elements starting at an arbitrary position k in a
675 * uniform declared as an array, elements k through k + N - 1 in the
676 * array will be replaced with the new values. Values for any array
677 * element that exceeds the highest array element index used, as
678 * reported by GetActiveUniform, will be ignored by the GL."
679 *
680 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
681 * will have already generated an error.
682 */
683 if (uni->array_elements != 0) {
684 count = MIN2(count, (int) (uni->array_elements - offset));
685 }
686
687 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
688
689 /* Store the data in the "actual type" backing storage for the uniform.
690 */
691 if (!uni->type->is_boolean()) {
692 memcpy(&uni->storage[components * offset], values,
693 sizeof(uni->storage[0]) * components * count);
694 } else {
695 const union gl_constant_value *src =
696 (const union gl_constant_value *) values;
697 union gl_constant_value *dst = &uni->storage[components * offset];
698 const unsigned elems = components * count;
699
700 for (unsigned i = 0; i < elems; i++) {
701 if (basicType == GLSL_TYPE_FLOAT) {
702 dst[i].i = src[i].f != 0.0f ? ctx->Const.UniformBooleanTrue : 0;
703 } else {
704 dst[i].i = src[i].i != 0 ? ctx->Const.UniformBooleanTrue : 0;
705 }
706 }
707 }
708
709 uni->initialized = true;
710
711 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
712
713 /* If the uniform is a sampler, do the extra magic necessary to propagate
714 * the changes through.
715 */
716 if (uni->type->is_sampler()) {
717 bool flushed = false;
718 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
719 struct gl_shader *const sh = shProg->_LinkedShaders[i];
720
721 /* If the shader stage doesn't use the sampler uniform, skip this.
722 */
723 if (sh == NULL || !uni->sampler[i].active)
724 continue;
725
726 for (int j = 0; j < count; j++) {
727 sh->SamplerUnits[uni->sampler[i].index + offset + j] =
728 ((unsigned *) values)[j];
729 }
730
731 struct gl_program *const prog = sh->Program;
732
733 assert(sizeof(prog->SamplerUnits) == sizeof(sh->SamplerUnits));
734
735 /* Determine if any of the samplers used by this shader stage have
736 * been modified.
737 */
738 bool changed = false;
739 for (unsigned j = 0; j < Elements(prog->SamplerUnits); j++) {
740 if ((sh->active_samplers & (1U << j)) != 0
741 && (prog->SamplerUnits[j] != sh->SamplerUnits[j])) {
742 changed = true;
743 break;
744 }
745 }
746
747 if (changed) {
748 if (!flushed) {
749 FLUSH_VERTICES(ctx, _NEW_TEXTURE | _NEW_PROGRAM);
750 flushed = true;
751 }
752
753 memcpy(prog->SamplerUnits,
754 sh->SamplerUnits,
755 sizeof(sh->SamplerUnits));
756
757 _mesa_update_shader_textures_used(shProg, prog);
758 if (ctx->Driver.SamplerUniformChange)
759 ctx->Driver.SamplerUniformChange(ctx, prog->Target, prog);
760 }
761 }
762 }
763
764 /* If the uniform is an image, update the mapping from image
765 * uniforms to image units present in the shader data structure.
766 */
767 if (uni->type->is_image()) {
768 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
769 if (uni->image[i].active) {
770 struct gl_shader *sh = shProg->_LinkedShaders[i];
771
772 for (int j = 0; j < count; j++)
773 sh->ImageUnits[uni->image[i].index + offset + j] =
774 ((GLint *) values)[j];
775 }
776 }
777
778 ctx->NewDriverState |= ctx->DriverFlags.NewImageUnits;
779 }
780 }
781
782 /**
783 * Called by glUniformMatrix*() functions.
784 * Note: cols=2, rows=4 ==> array[2] of vec4
785 */
786 extern "C" void
787 _mesa_uniform_matrix(struct gl_context *ctx, struct gl_shader_program *shProg,
788 GLuint cols, GLuint rows,
789 GLint location, GLsizei count,
790 GLboolean transpose, const GLfloat *values)
791 {
792 unsigned offset;
793 unsigned vectors;
794 unsigned components;
795 unsigned elements;
796
797 struct gl_uniform_storage *const uni =
798 validate_uniform_parameters(ctx, shProg, location, count,
799 &offset, "glUniformMatrix", false);
800 if (uni == NULL)
801 return;
802
803 if (!uni->type->is_matrix()) {
804 _mesa_error(ctx, GL_INVALID_OPERATION,
805 "glUniformMatrix(non-matrix uniform)");
806 return;
807 }
808
809 assert(!uni->type->is_sampler());
810 vectors = uni->type->matrix_columns;
811 components = uni->type->vector_elements;
812
813 /* Verify that the types are compatible. This is greatly simplified for
814 * matrices because they can only have a float base type.
815 */
816 if (vectors != cols || components != rows) {
817 _mesa_error(ctx, GL_INVALID_OPERATION,
818 "glUniformMatrix(matrix size mismatch)");
819 return;
820 }
821
822 /* GL_INVALID_VALUE is generated if `transpose' is not GL_FALSE.
823 * http://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml */
824 if (ctx->API == API_OPENGLES
825 || (ctx->API == API_OPENGLES2 && ctx->Version < 30)) {
826 if (transpose) {
827 _mesa_error(ctx, GL_INVALID_VALUE,
828 "glUniformMatrix(matrix transpose is not GL_FALSE)");
829 return;
830 }
831 }
832
833 if (ctx->_Shader->Flags & GLSL_UNIFORMS) {
834 log_uniform(values, GLSL_TYPE_FLOAT, components, vectors, count,
835 bool(transpose), shProg, location, uni);
836 }
837
838 /* Page 82 (page 96 of the PDF) of the OpenGL 2.1 spec says:
839 *
840 * "When loading N elements starting at an arbitrary position k in a
841 * uniform declared as an array, elements k through k + N - 1 in the
842 * array will be replaced with the new values. Values for any array
843 * element that exceeds the highest array element index used, as
844 * reported by GetActiveUniform, will be ignored by the GL."
845 *
846 * Clamp 'count' to a valid value. Note that for non-arrays a count > 1
847 * will have already generated an error.
848 */
849 if (uni->array_elements != 0) {
850 count = MIN2(count, (int) (uni->array_elements - offset));
851 }
852
853 FLUSH_VERTICES(ctx, _NEW_PROGRAM_CONSTANTS);
854
855 /* Store the data in the "actual type" backing storage for the uniform.
856 */
857 elements = components * vectors;
858
859 if (!transpose) {
860 memcpy(&uni->storage[elements * offset], values,
861 sizeof(uni->storage[0]) * elements * count);
862 } else {
863 /* Copy and transpose the matrix.
864 */
865 const float *src = values;
866 float *dst = &uni->storage[elements * offset].f;
867
868 for (int i = 0; i < count; i++) {
869 for (unsigned r = 0; r < rows; r++) {
870 for (unsigned c = 0; c < cols; c++) {
871 dst[(c * components) + r] = src[c + (r * vectors)];
872 }
873 }
874
875 dst += elements;
876 src += elements;
877 }
878 }
879
880 uni->initialized = true;
881
882 _mesa_propagate_uniforms_to_driver_storage(uni, offset, count);
883 }
884
885
886 /**
887 * Called via glGetUniformLocation().
888 *
889 * Returns the uniform index into UniformStorage (also the
890 * glGetActiveUniformsiv uniform index), and stores the referenced
891 * array offset in *offset, or GL_INVALID_INDEX (-1).
892 */
893 extern "C" unsigned
894 _mesa_get_uniform_location(struct gl_shader_program *shProg,
895 const GLchar *name,
896 unsigned *out_offset)
897 {
898 /* Page 80 (page 94 of the PDF) of the OpenGL 2.1 spec says:
899 *
900 * "The first element of a uniform array is identified using the
901 * name of the uniform array appended with "[0]". Except if the last
902 * part of the string name indicates a uniform array, then the
903 * location of the first element of that array can be retrieved by
904 * either using the name of the uniform array, or the name of the
905 * uniform array appended with "[0]"."
906 *
907 * Note: since uniform names are not allowed to use whitespace, and array
908 * indices within uniform names are not allowed to use "+", "-", or leading
909 * zeros, it follows that each uniform has a unique name up to the possible
910 * ambiguity with "[0]" noted above. Therefore we don't need to worry
911 * about mal-formed inputs--they will properly fail when we try to look up
912 * the uniform name in shProg->UniformHash.
913 */
914
915 const GLchar *base_name_end;
916 long offset = parse_program_resource_name(name, &base_name_end);
917 bool array_lookup = offset >= 0;
918 char *name_copy;
919
920 if (array_lookup) {
921 name_copy = (char *) malloc(base_name_end - name + 1);
922 memcpy(name_copy, name, base_name_end - name);
923 name_copy[base_name_end - name] = '\0';
924 } else {
925 name_copy = (char *) name;
926 offset = 0;
927 }
928
929 unsigned location = 0;
930 const bool found = shProg->UniformHash->get(location, name_copy);
931
932 assert(!found
933 || strcmp(name_copy, shProg->UniformStorage[location].name) == 0);
934
935 /* Free the temporary buffer *before* possibly returning an error.
936 */
937 if (name_copy != name)
938 free(name_copy);
939
940 if (!found)
941 return GL_INVALID_INDEX;
942
943 /* If the uniform is an array, fail if the index is out of bounds.
944 * (A negative index is caught above.) This also fails if the uniform
945 * is not an array, but the user is trying to index it, because
946 * array_elements is zero and offset >= 0.
947 */
948 if (array_lookup
949 && offset >= (long) shProg->UniformStorage[location].array_elements) {
950 return GL_INVALID_INDEX;
951 }
952
953 *out_offset = offset;
954 return location;
955 }
956
957 extern "C" bool
958 _mesa_sampler_uniforms_are_valid(const struct gl_shader_program *shProg,
959 char *errMsg, size_t errMsgLength)
960 {
961 /* Shader does not have samplers. */
962 if (shProg->NumUserUniformStorage == 0)
963 return true;
964
965 if (!shProg->SamplersValidated) {
966 _mesa_snprintf(errMsg, errMsgLength,
967 "active samplers with a different type "
968 "refer to the same texture image unit");
969 return false;
970 }
971 return true;
972 }
973
974 extern "C" bool
975 _mesa_sampler_uniforms_pipeline_are_valid(struct gl_pipeline_object *pipeline)
976 {
977 /* Section 2.11.11 (Shader Execution), subheading "Validation," of the
978 * OpenGL 4.1 spec says:
979 *
980 * "[INVALID_OPERATION] is generated by any command that transfers
981 * vertices to the GL if:
982 *
983 * ...
984 *
985 * - Any two active samplers in the current program object are of
986 * different types, but refer to the same texture image unit.
987 *
988 * - The number of active samplers in the program exceeds the
989 * maximum number of texture image units allowed."
990 */
991 unsigned active_samplers = 0;
992 const struct gl_shader_program **shProg =
993 (const struct gl_shader_program **) pipeline->CurrentProgram;
994
995 const glsl_type *unit_types[MAX_COMBINED_TEXTURE_IMAGE_UNITS];
996 memset(unit_types, 0, sizeof(unit_types));
997
998 for (unsigned idx = 0; idx < ARRAY_SIZE(pipeline->CurrentProgram); idx++) {
999 if (!shProg[idx])
1000 continue;
1001
1002 for (unsigned i = 0; i < shProg[idx]->NumUserUniformStorage; i++) {
1003 const struct gl_uniform_storage *const storage =
1004 &shProg[idx]->UniformStorage[i];
1005 const glsl_type *const t = (storage->type->is_array())
1006 ? storage->type->fields.array : storage->type;
1007
1008 if (!t->is_sampler())
1009 continue;
1010
1011 active_samplers++;
1012
1013 const unsigned count = MAX2(1, storage->type->array_size());
1014 for (unsigned j = 0; j < count; j++) {
1015 const unsigned unit = storage->storage[j].i;
1016
1017 /* The types of the samplers associated with a particular texture
1018 * unit must be an exact match. Page 74 (page 89 of the PDF) of
1019 * the OpenGL 3.3 core spec says:
1020 *
1021 * "It is not allowed to have variables of different sampler
1022 * types pointing to the same texture image unit within a
1023 * program object."
1024 */
1025 if (unit_types[unit] == NULL) {
1026 unit_types[unit] = t;
1027 } else if (unit_types[unit] != t) {
1028 pipeline->InfoLog =
1029 ralloc_asprintf(pipeline,
1030 "Texture unit %d is accessed both as %s "
1031 "and %s",
1032 unit, unit_types[unit]->name, t->name);
1033 return false;
1034 }
1035 }
1036 }
1037 }
1038
1039 if (active_samplers > MAX_COMBINED_TEXTURE_IMAGE_UNITS) {
1040 pipeline->InfoLog =
1041 ralloc_asprintf(pipeline,
1042 "the number of active samplers %d exceed the "
1043 "maximum %d",
1044 active_samplers, MAX_COMBINED_TEXTURE_IMAGE_UNITS);
1045 return false;
1046 }
1047
1048 return true;
1049 }