2 * Mesa 3-D graphics library
5 * Copyright (C) 2008 Brian Paul All Rights Reserved.
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:
14 * The above copyright notice and this permission notice shall be included
15 * in all copies or substantial portions of the Software.
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 * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
21 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 #include "main/imports.h"
32 #include "main/context.h"
33 #include "main/hash.h"
34 #include "main/macros.h"
35 #include "shader/program.h"
36 #include "shader/prog_instruction.h"
37 #include "shader/prog_parameter.h"
38 #include "shader/prog_print.h"
39 #include "shader/prog_statevars.h"
40 #include "shader/prog_uniform.h"
41 #include "shader/shader_api.h"
42 #include "slang_link.h"
46 static struct gl_vertex_program *
47 vertex_program(struct gl_program *prog)
49 assert(prog->Target == GL_VERTEX_PROGRAM_ARB);
50 return (struct gl_vertex_program *) prog;
55 static struct gl_fragment_program *
56 fragment_program(struct gl_program *prog)
58 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
59 return (struct gl_fragment_program *) prog;
64 * Record a linking error.
67 link_error(struct gl_shader_program *shProg, const char *msg)
69 if (shProg->InfoLog) {
70 _mesa_free(shProg->InfoLog);
72 shProg->InfoLog = _mesa_strdup(msg);
73 shProg->LinkStatus = GL_FALSE;
79 * Check if the given bit is either set or clear in both bitfields.
82 bits_agree(GLbitfield flags1, GLbitfield flags2, GLbitfield bit)
84 return (flags1 & bit) == (flags2 & bit);
89 * Linking varying vars involves rearranging varying vars so that the
90 * vertex program's output varyings matches the order of the fragment
91 * program's input varyings.
92 * We'll then rewrite instructions to replace PROGRAM_VARYING with either
93 * PROGRAM_INPUT or PROGRAM_OUTPUT depending on whether it's a vertex or
95 * This is also where we set program Input/OutputFlags to indicate
96 * which inputs are centroid-sampled, invariant, etc.
99 link_varying_vars(struct gl_shader_program *shProg, struct gl_program *prog)
101 GLuint *map, i, firstVarying, newFile;
102 GLbitfield *inOutFlags;
104 map = (GLuint *) malloc(prog->Varying->NumParameters * sizeof(GLuint));
108 /* Varying variables are treated like other vertex program outputs
109 * (and like other fragment program inputs). The position of the
110 * first varying differs for vertex/fragment programs...
111 * Also, replace File=PROGRAM_VARYING with File=PROGRAM_INPUT/OUTPUT.
113 if (prog->Target == GL_VERTEX_PROGRAM_ARB) {
114 firstVarying = VERT_RESULT_VAR0;
115 newFile = PROGRAM_OUTPUT;
116 inOutFlags = prog->OutputFlags;
119 assert(prog->Target == GL_FRAGMENT_PROGRAM_ARB);
120 firstVarying = FRAG_ATTRIB_VAR0;
121 newFile = PROGRAM_INPUT;
122 inOutFlags = prog->InputFlags;
125 for (i = 0; i < prog->Varying->NumParameters; i++) {
126 /* see if this varying is in the linked varying list */
127 const struct gl_program_parameter *var = prog->Varying->Parameters + i;
128 GLint j = _mesa_lookup_parameter_index(shProg->Varying, -1, var->Name);
130 /* varying is already in list, do some error checking */
131 const struct gl_program_parameter *v =
132 &shProg->Varying->Parameters[j];
133 if (var->Size != v->Size) {
134 link_error(shProg, "mismatched varying variable types");
137 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_CENTROID)) {
139 snprintf(msg, sizeof(msg),
140 "centroid modifier mismatch for '%s'", var->Name);
141 link_error(shProg, msg);
144 if (!bits_agree(var->Flags, v->Flags, PROG_PARAM_BIT_INVARIANT)) {
146 snprintf(msg, sizeof(msg),
147 "invariant modifier mismatch for '%s'", var->Name);
148 link_error(shProg, msg);
153 /* not already in linked list */
154 j = _mesa_add_varying(shProg->Varying, var->Name, var->Size,
158 /* Map varying[i] to varying[j].
159 * Plus, set prog->Input/OutputFlags[] as described above.
160 * Note: the loop here takes care of arrays or large (sz>4) vars.
163 GLint sz = var->Size;
165 inOutFlags[firstVarying + j] = var->Flags;
166 /*printf("Link varying from %d to %d\n", i, j);*/
170 i--; /* go back one */
175 /* OK, now scan the program/shader instructions looking for varying vars,
176 * replacing the old index with the new index.
178 for (i = 0; i < prog->NumInstructions; i++) {
179 struct prog_instruction *inst = prog->Instructions + i;
182 if (inst->DstReg.File == PROGRAM_VARYING) {
183 inst->DstReg.File = newFile;
184 inst->DstReg.Index = map[ inst->DstReg.Index ] + firstVarying;
187 for (j = 0; j < 3; j++) {
188 if (inst->SrcReg[j].File == PROGRAM_VARYING) {
189 inst->SrcReg[j].File = newFile;
190 inst->SrcReg[j].Index = map[ inst->SrcReg[j].Index ] + firstVarying;
197 /* these will get recomputed before linking is completed */
198 prog->InputsRead = 0x0;
199 prog->OutputsWritten = 0x0;
206 * Build the shProg->Uniforms list.
207 * This is basically a list/index of all uniforms found in either/both of
208 * the vertex and fragment shaders.
211 link_uniform_vars(struct gl_shader_program *shProg,
212 struct gl_program *prog,
215 GLuint samplerMap[MAX_SAMPLERS];
218 for (i = 0; i < prog->Parameters->NumParameters; i++) {
219 const struct gl_program_parameter *p = prog->Parameters->Parameters + i;
222 * XXX FIX NEEDED HERE
223 * We should also be adding a uniform if p->Type == PROGRAM_STATE_VAR.
224 * For example, modelview matrix, light pos, etc.
225 * Also, we need to update the state-var name-generator code to
226 * generate GLSL-style names, like "gl_LightSource[0].position".
227 * Furthermore, we'll need to fix the state-var's size/datatype info.
230 if ((p->Type == PROGRAM_UNIFORM && p->Used) ||
231 p->Type == PROGRAM_SAMPLER) {
232 struct gl_uniform *uniform =
233 _mesa_append_uniform(shProg->Uniforms, p->Name, prog->Target, i);
235 uniform->Initialized = p->Initialized;
238 if (p->Type == PROGRAM_SAMPLER) {
239 /* Allocate a new sampler index */
240 GLuint sampNum = *numSamplers;
241 GLuint oldSampNum = (GLuint) prog->Parameters->ParameterValues[i][0];
242 assert(oldSampNum < MAX_SAMPLERS);
243 samplerMap[oldSampNum] = sampNum;
249 /* OK, now scan the program/shader instructions looking for sampler vars,
250 * replacing the old index with the new index.
252 prog->SamplersUsed = 0x0;
253 for (i = 0; i < prog->NumInstructions; i++) {
254 struct prog_instruction *inst = prog->Instructions + i;
255 if (_mesa_is_tex_instruction(inst->Opcode)) {
257 printf("====== remap sampler from %d to %d\n",
258 inst->Sampler, map[ inst->Sampler ]);
260 /* here, texUnit is really samplerUnit */
261 assert(inst->TexSrcUnit < MAX_SAMPLERS);
262 inst->TexSrcUnit = samplerMap[inst->TexSrcUnit];
263 prog->SamplerTargets[inst->TexSrcUnit] = inst->TexSrcTarget;
264 prog->SamplersUsed |= (1 << inst->TexSrcUnit);
272 * Resolve binding of generic vertex attributes.
273 * For example, if the vertex shader declared "attribute vec4 foobar" we'll
274 * allocate a generic vertex attribute for "foobar" and plug that value into
275 * the vertex program instructions.
276 * But if the user called glBindAttributeLocation(), those bindings will
280 _slang_resolve_attributes(struct gl_shader_program *shProg,
281 const struct gl_program *origProg,
282 struct gl_program *linkedProg)
284 GLint attribMap[MAX_VERTEX_ATTRIBS];
286 GLbitfield usedAttributes;
288 assert(origProg != linkedProg);
289 assert(origProg->Target == GL_VERTEX_PROGRAM_ARB);
290 assert(linkedProg->Target == GL_VERTEX_PROGRAM_ARB);
292 if (!shProg->Attributes)
293 shProg->Attributes = _mesa_new_parameter_list();
295 if (linkedProg->Attributes) {
296 _mesa_free_parameter_list(linkedProg->Attributes);
298 linkedProg->Attributes = _mesa_new_parameter_list();
301 /* Build a bitmask indicating which attribute indexes have been
302 * explicitly bound by the user with glBindAttributeLocation().
304 usedAttributes = 0x0;
305 for (i = 0; i < shProg->Attributes->NumParameters; i++) {
306 GLint attr = shProg->Attributes->Parameters[i].StateIndexes[0];
307 usedAttributes |= (1 << attr);
310 /* initialize the generic attribute map entries to -1 */
311 for (i = 0; i < MAX_VERTEX_ATTRIBS; i++) {
316 * Scan program for generic attribute references
318 for (i = 0; i < linkedProg->NumInstructions; i++) {
319 struct prog_instruction *inst = linkedProg->Instructions + i;
320 for (j = 0; j < 3; j++) {
321 if (inst->SrcReg[j].File == PROGRAM_INPUT &&
322 inst->SrcReg[j].Index >= VERT_ATTRIB_GENERIC0) {
324 * OK, we've found a generic vertex attribute reference.
326 const GLint k = inst->SrcReg[j].Index - VERT_ATTRIB_GENERIC0;
328 GLint attr = attribMap[k];
331 /* Need to figure out attribute mapping now.
333 const char *name = origProg->Attributes->Parameters[k].Name;
334 const GLint size = origProg->Attributes->Parameters[k].Size;
335 const GLenum type =origProg->Attributes->Parameters[k].DataType;
338 /* See if there's a user-defined attribute binding for
341 index = _mesa_lookup_parameter_index(shProg->Attributes,
344 /* Found a user-defined binding */
345 attr = shProg->Attributes->Parameters[index].StateIndexes[0];
348 /* No user-defined binding, choose our own attribute number.
349 * Start at 1 since generic attribute 0 always aliases
352 for (attr = 1; attr < MAX_VERTEX_ATTRIBS; attr++) {
353 if (((1 << attr) & usedAttributes) == 0)
356 if (attr == MAX_VERTEX_ATTRIBS) {
357 link_error(shProg, "Too many vertex attributes");
361 /* mark this attribute as used */
362 usedAttributes |= (1 << attr);
367 /* Save the final name->attrib binding so it can be queried
368 * with glGetAttributeLocation().
370 _mesa_add_attribute(linkedProg->Attributes, name,
376 /* update the instruction's src reg */
377 inst->SrcReg[j].Index = VERT_ATTRIB_GENERIC0 + attr;
387 * Scan program instructions to update the program's NumTemporaries field.
388 * Note: this implemenation relies on the code generator allocating
389 * temps in increasing order (0, 1, 2, ... ).
392 _slang_count_temporaries(struct gl_program *prog)
397 for (i = 0; i < prog->NumInstructions; i++) {
398 const struct prog_instruction *inst = prog->Instructions + i;
399 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
400 for (j = 0; j < numSrc; j++) {
401 if (inst->SrcReg[j].File == PROGRAM_TEMPORARY) {
402 if (maxIndex < inst->SrcReg[j].Index)
403 maxIndex = inst->SrcReg[j].Index;
405 if (inst->DstReg.File == PROGRAM_TEMPORARY) {
406 if (maxIndex < (GLint) inst->DstReg.Index)
407 maxIndex = inst->DstReg.Index;
412 prog->NumTemporaries = (GLuint) (maxIndex + 1);
417 * Scan program instructions to update the program's InputsRead and
418 * OutputsWritten fields.
421 _slang_update_inputs_outputs(struct gl_program *prog)
424 GLuint maxAddrReg = 0;
426 prog->InputsRead = 0x0;
427 prog->OutputsWritten = 0x0;
429 for (i = 0; i < prog->NumInstructions; i++) {
430 const struct prog_instruction *inst = prog->Instructions + i;
431 const GLuint numSrc = _mesa_num_inst_src_regs(inst->Opcode);
432 for (j = 0; j < numSrc; j++) {
433 if (inst->SrcReg[j].File == PROGRAM_INPUT) {
434 prog->InputsRead |= 1 << inst->SrcReg[j].Index;
435 if (prog->Target == GL_FRAGMENT_PROGRAM_ARB &&
436 inst->SrcReg[j].Index == FRAG_ATTRIB_FOGC) {
437 /* The fragment shader FOGC input is used for fog,
438 * front-facing and sprite/point coord.
440 struct gl_fragment_program *fp = fragment_program(prog);
441 const GLint swz = GET_SWZ(inst->SrcReg[j].Swizzle, 0);
442 if (swz == SWIZZLE_X)
443 fp->UsesFogFragCoord = GL_TRUE;
444 else if (swz == SWIZZLE_Y)
445 fp->UsesFrontFacing = GL_TRUE;
446 else if (swz == SWIZZLE_Z || swz == SWIZZLE_W)
447 fp->UsesPointCoord = GL_TRUE;
450 else if (inst->SrcReg[j].File == PROGRAM_ADDRESS) {
451 maxAddrReg = MAX2(maxAddrReg, (GLuint) (inst->SrcReg[j].Index + 1));
454 if (inst->DstReg.File == PROGRAM_OUTPUT) {
455 prog->OutputsWritten |= 1 << inst->DstReg.Index;
457 else if (inst->DstReg.File == PROGRAM_ADDRESS) {
458 maxAddrReg = MAX2(maxAddrReg, inst->DstReg.Index + 1);
461 prog->NumAddressRegs = maxAddrReg;
466 * Shader linker. Currently:
468 * 1. The last attached vertex shader and fragment shader are linked.
469 * 2. Varying vars in the two shaders are combined so their locations
470 * agree between the vertex and fragment stages. They're treated as
471 * vertex program output attribs and as fragment program input attribs.
472 * 3. The vertex and fragment programs are cloned and modified to update
473 * src/dst register references so they use the new, linked varying
477 _slang_link(GLcontext *ctx,
478 GLhandleARB programObj,
479 struct gl_shader_program *shProg)
481 const struct gl_vertex_program *vertProg;
482 const struct gl_fragment_program *fragProg;
483 GLuint numSamplers = 0;
486 _mesa_clear_shader_program_data(ctx, shProg);
488 /* check that all programs compiled successfully */
489 for (i = 0; i < shProg->NumShaders; i++) {
490 if (!shProg->Shaders[i]->CompileStatus) {
491 link_error(shProg, "linking with uncompiled shader\n");
496 shProg->Uniforms = _mesa_new_uniform_list();
497 shProg->Varying = _mesa_new_parameter_list();
500 * Find attached vertex, fragment shaders defining main()
504 for (i = 0; i < shProg->NumShaders; i++) {
505 struct gl_shader *shader = shProg->Shaders[i];
506 if (shader->Type == GL_VERTEX_SHADER) {
508 vertProg = vertex_program(shader->Program);
510 else if (shader->Type == GL_FRAGMENT_SHADER) {
512 fragProg = fragment_program(shader->Program);
515 _mesa_problem(ctx, "unexpected shader target in slang_link()");
520 /* must have both a vertex and fragment program for ES2 */
522 link_error(shProg, "missing vertex shader\n");
526 link_error(shProg, "missing fragment shader\n");
532 * Make copies of the vertex/fragment programs now since we'll be
533 * changing src/dst registers after merging the uniforms and varying vars.
535 _mesa_reference_vertprog(ctx, &shProg->VertexProgram, NULL);
537 struct gl_vertex_program *linked_vprog =
538 vertex_program(_mesa_clone_program(ctx, &vertProg->Base));
539 shProg->VertexProgram = linked_vprog; /* refcount OK */
540 ASSERT(shProg->VertexProgram->Base.RefCount == 1);
543 _mesa_reference_fragprog(ctx, &shProg->FragmentProgram, NULL);
545 struct gl_fragment_program *linked_fprog =
546 fragment_program(_mesa_clone_program(ctx, &fragProg->Base));
547 shProg->FragmentProgram = linked_fprog; /* refcount OK */
548 ASSERT(shProg->FragmentProgram->Base.RefCount == 1);
551 /* link varying vars */
552 if (shProg->VertexProgram) {
553 if (!link_varying_vars(shProg, &shProg->VertexProgram->Base))
556 if (shProg->FragmentProgram) {
557 if (!link_varying_vars(shProg, &shProg->FragmentProgram->Base))
561 /* link uniform vars */
562 if (shProg->VertexProgram)
563 link_uniform_vars(shProg, &shProg->VertexProgram->Base, &numSamplers);
564 if (shProg->FragmentProgram)
565 link_uniform_vars(shProg, &shProg->FragmentProgram->Base, &numSamplers);
567 /*_mesa_print_uniforms(shProg->Uniforms);*/
569 if (shProg->VertexProgram) {
570 if (!_slang_resolve_attributes(shProg, &vertProg->Base,
571 &shProg->VertexProgram->Base)) {
576 if (shProg->VertexProgram) {
577 _slang_update_inputs_outputs(&shProg->VertexProgram->Base);
578 _slang_count_temporaries(&shProg->VertexProgram->Base);
579 if (!(shProg->VertexProgram->Base.OutputsWritten & (1 << VERT_RESULT_HPOS))) {
580 /* the vertex program did not compute a vertex position */
582 "gl_Position was not written by vertex shader\n");
586 if (shProg->FragmentProgram) {
587 _slang_count_temporaries(&shProg->FragmentProgram->Base);
588 _slang_update_inputs_outputs(&shProg->FragmentProgram->Base);
591 /* Check that all the varying vars needed by the fragment shader are
592 * actually produced by the vertex shader.
594 if (shProg->FragmentProgram) {
595 const GLbitfield varyingRead
596 = shProg->FragmentProgram->Base.InputsRead >> FRAG_ATTRIB_VAR0;
597 const GLbitfield varyingWritten = shProg->VertexProgram ?
598 shProg->VertexProgram->Base.OutputsWritten >> VERT_RESULT_VAR0 : 0x0;
599 if ((varyingRead & varyingWritten) != varyingRead) {
601 "Fragment program using varying vars not written by vertex shader\n");
607 if (fragProg && shProg->FragmentProgram) {
608 /* Compute initial program's TexturesUsed info */
609 _mesa_update_shader_textures_used(&shProg->FragmentProgram->Base);
611 /* notify driver that a new fragment program has been compiled/linked */
612 ctx->Driver.ProgramStringNotify(ctx, GL_FRAGMENT_PROGRAM_ARB,
613 &shProg->FragmentProgram->Base);
614 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
615 printf("Mesa original fragment program:\n");
616 _mesa_print_program(&fragProg->Base);
617 _mesa_print_program_parameters(ctx, &fragProg->Base);
619 printf("Mesa post-link fragment program:\n");
620 _mesa_print_program(&shProg->FragmentProgram->Base);
621 _mesa_print_program_parameters(ctx, &shProg->FragmentProgram->Base);
625 if (vertProg && shProg->VertexProgram) {
626 /* Compute initial program's TexturesUsed info */
627 _mesa_update_shader_textures_used(&shProg->VertexProgram->Base);
629 /* notify driver that a new vertex program has been compiled/linked */
630 ctx->Driver.ProgramStringNotify(ctx, GL_VERTEX_PROGRAM_ARB,
631 &shProg->VertexProgram->Base);
632 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
633 printf("Mesa original vertex program:\n");
634 _mesa_print_program(&vertProg->Base);
635 _mesa_print_program_parameters(ctx, &vertProg->Base);
637 printf("Mesa post-link vertex program:\n");
638 _mesa_print_program(&shProg->VertexProgram->Base);
639 _mesa_print_program_parameters(ctx, &shProg->VertexProgram->Base);
643 if (MESA_VERBOSE & VERBOSE_GLSL_DUMP) {
644 printf("Varying vars:\n");
645 _mesa_print_parameter_list(shProg->Varying);
648 shProg->LinkStatus = (shProg->VertexProgram || shProg->FragmentProgram);