mesa: Remove PROGRAM_ENV_PARAM enum.
[mesa.git] / src / mesa / program / program.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 /**
26 * \file program.c
27 * Vertex and fragment program support functions.
28 * \author Brian Paul
29 */
30
31
32 #include "main/glheader.h"
33 #include "main/context.h"
34 #include "main/hash.h"
35 #include "main/macros.h"
36 #include "program.h"
37 #include "prog_cache.h"
38 #include "prog_parameter.h"
39 #include "prog_instruction.h"
40
41
42 /**
43 * A pointer to this dummy program is put into the hash table when
44 * glGenPrograms is called.
45 */
46 struct gl_program _mesa_DummyProgram;
47
48
49 /**
50 * Init context's vertex/fragment program state
51 */
52 void
53 _mesa_init_program(struct gl_context *ctx)
54 {
55 /*
56 * If this assertion fails, we need to increase the field
57 * size for register indexes (see INST_INDEX_BITS).
58 */
59 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents / 4
60 <= (1 << INST_INDEX_BITS));
61 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents / 4
62 <= (1 << INST_INDEX_BITS));
63
64 ASSERT(ctx->Const.VertexProgram.MaxTemps <= (1 << INST_INDEX_BITS));
65 ASSERT(ctx->Const.VertexProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
66 ASSERT(ctx->Const.FragmentProgram.MaxTemps <= (1 << INST_INDEX_BITS));
67 ASSERT(ctx->Const.FragmentProgram.MaxLocalParams <= (1 << INST_INDEX_BITS));
68
69 ASSERT(ctx->Const.VertexProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
70 ASSERT(ctx->Const.FragmentProgram.MaxUniformComponents <= 4 * MAX_UNIFORMS);
71
72 ASSERT(ctx->Const.VertexProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
73 ASSERT(ctx->Const.FragmentProgram.MaxAddressOffset <= (1 << INST_INDEX_BITS));
74
75 /* If this fails, increase prog_instruction::TexSrcUnit size */
76 STATIC_ASSERT(MAX_TEXTURE_UNITS <= (1 << 5));
77
78 /* If this fails, increase prog_instruction::TexSrcTarget size */
79 STATIC_ASSERT(NUM_TEXTURE_TARGETS <= (1 << 4));
80
81 ctx->Program.ErrorPos = -1;
82 ctx->Program.ErrorString = _mesa_strdup("");
83
84 ctx->VertexProgram.Enabled = GL_FALSE;
85 ctx->VertexProgram.PointSizeEnabled =
86 (ctx->API == API_OPENGLES2) ? GL_TRUE : GL_FALSE;
87 ctx->VertexProgram.TwoSideEnabled = GL_FALSE;
88 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
89 ctx->Shared->DefaultVertexProgram);
90 assert(ctx->VertexProgram.Current);
91 ctx->VertexProgram.Cache = _mesa_new_program_cache();
92
93 ctx->FragmentProgram.Enabled = GL_FALSE;
94 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
95 ctx->Shared->DefaultFragmentProgram);
96 assert(ctx->FragmentProgram.Current);
97 ctx->FragmentProgram.Cache = _mesa_new_program_cache();
98
99 ctx->GeometryProgram.Enabled = GL_FALSE;
100 /* right now by default we don't have a geometry program */
101 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
102 NULL);
103 ctx->GeometryProgram.Cache = _mesa_new_program_cache();
104
105 /* XXX probably move this stuff */
106 ctx->ATIFragmentShader.Enabled = GL_FALSE;
107 ctx->ATIFragmentShader.Current = ctx->Shared->DefaultFragmentShader;
108 assert(ctx->ATIFragmentShader.Current);
109 ctx->ATIFragmentShader.Current->RefCount++;
110 }
111
112
113 /**
114 * Free a context's vertex/fragment program state
115 */
116 void
117 _mesa_free_program_data(struct gl_context *ctx)
118 {
119 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
120 _mesa_delete_program_cache(ctx, ctx->VertexProgram.Cache);
121 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
122 _mesa_delete_shader_cache(ctx, ctx->FragmentProgram.Cache);
123 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current, NULL);
124 _mesa_delete_program_cache(ctx, ctx->GeometryProgram.Cache);
125
126 /* XXX probably move this stuff */
127 if (ctx->ATIFragmentShader.Current) {
128 ctx->ATIFragmentShader.Current->RefCount--;
129 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
130 free(ctx->ATIFragmentShader.Current);
131 }
132 }
133
134 free((void *) ctx->Program.ErrorString);
135 }
136
137
138 /**
139 * Update the default program objects in the given context to reference those
140 * specified in the shared state and release those referencing the old
141 * shared state.
142 */
143 void
144 _mesa_update_default_objects_program(struct gl_context *ctx)
145 {
146 _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current,
147 ctx->Shared->DefaultVertexProgram);
148 assert(ctx->VertexProgram.Current);
149
150 _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current,
151 ctx->Shared->DefaultFragmentProgram);
152 assert(ctx->FragmentProgram.Current);
153
154 _mesa_reference_geomprog(ctx, &ctx->GeometryProgram.Current,
155 ctx->Shared->DefaultGeometryProgram);
156
157 /* XXX probably move this stuff */
158 if (ctx->ATIFragmentShader.Current) {
159 ctx->ATIFragmentShader.Current->RefCount--;
160 if (ctx->ATIFragmentShader.Current->RefCount <= 0) {
161 free(ctx->ATIFragmentShader.Current);
162 }
163 }
164 ctx->ATIFragmentShader.Current = (struct ati_fragment_shader *) ctx->Shared->DefaultFragmentShader;
165 assert(ctx->ATIFragmentShader.Current);
166 ctx->ATIFragmentShader.Current->RefCount++;
167 }
168
169
170 /**
171 * Set the vertex/fragment program error state (position and error string).
172 * This is generally called from within the parsers.
173 */
174 void
175 _mesa_set_program_error(struct gl_context *ctx, GLint pos, const char *string)
176 {
177 ctx->Program.ErrorPos = pos;
178 free((void *) ctx->Program.ErrorString);
179 if (!string)
180 string = "";
181 ctx->Program.ErrorString = _mesa_strdup(string);
182 }
183
184
185 /**
186 * Find the line number and column for 'pos' within 'string'.
187 * Return a copy of the line which contains 'pos'. Free the line with
188 * free().
189 * \param string the program string
190 * \param pos the position within the string
191 * \param line returns the line number corresponding to 'pos'.
192 * \param col returns the column number corresponding to 'pos'.
193 * \return copy of the line containing 'pos'.
194 */
195 const GLubyte *
196 _mesa_find_line_column(const GLubyte *string, const GLubyte *pos,
197 GLint *line, GLint *col)
198 {
199 const GLubyte *lineStart = string;
200 const GLubyte *p = string;
201 GLubyte *s;
202 int len;
203
204 *line = 1;
205
206 while (p != pos) {
207 if (*p == (GLubyte) '\n') {
208 (*line)++;
209 lineStart = p + 1;
210 }
211 p++;
212 }
213
214 *col = (pos - lineStart) + 1;
215
216 /* return copy of this line */
217 while (*p != 0 && *p != '\n')
218 p++;
219 len = p - lineStart;
220 s = malloc(len + 1);
221 memcpy(s, lineStart, len);
222 s[len] = 0;
223
224 return s;
225 }
226
227
228 /**
229 * Initialize a new vertex/fragment program object.
230 */
231 static struct gl_program *
232 _mesa_init_program_struct( struct gl_context *ctx, struct gl_program *prog,
233 GLenum target, GLuint id)
234 {
235 (void) ctx;
236 if (prog) {
237 GLuint i;
238 memset(prog, 0, sizeof(*prog));
239 prog->Id = id;
240 prog->Target = target;
241 prog->RefCount = 1;
242 prog->Format = GL_PROGRAM_FORMAT_ASCII_ARB;
243
244 /* default mapping from samplers to texture units */
245 for (i = 0; i < MAX_SAMPLERS; i++)
246 prog->SamplerUnits[i] = i;
247 }
248
249 return prog;
250 }
251
252
253 /**
254 * Initialize a new fragment program object.
255 */
256 struct gl_program *
257 _mesa_init_fragment_program( struct gl_context *ctx, struct gl_fragment_program *prog,
258 GLenum target, GLuint id)
259 {
260 if (prog)
261 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
262 else
263 return NULL;
264 }
265
266
267 /**
268 * Initialize a new vertex program object.
269 */
270 struct gl_program *
271 _mesa_init_vertex_program( struct gl_context *ctx, struct gl_vertex_program *prog,
272 GLenum target, GLuint id)
273 {
274 if (prog)
275 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
276 else
277 return NULL;
278 }
279
280
281 /**
282 * Initialize a new geometry program object.
283 */
284 struct gl_program *
285 _mesa_init_geometry_program( struct gl_context *ctx, struct gl_geometry_program *prog,
286 GLenum target, GLuint id)
287 {
288 if (prog)
289 return _mesa_init_program_struct( ctx, &prog->Base, target, id );
290 else
291 return NULL;
292 }
293
294
295 /**
296 * Allocate and initialize a new fragment/vertex program object but
297 * don't put it into the program hash table. Called via
298 * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a
299 * device driver function to implement OO deriviation with additional
300 * types not understood by this function.
301 *
302 * \param ctx context
303 * \param id program id/number
304 * \param target program target/type
305 * \return pointer to new program object
306 */
307 struct gl_program *
308 _mesa_new_program(struct gl_context *ctx, GLenum target, GLuint id)
309 {
310 struct gl_program *prog;
311 switch (target) {
312 case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */
313 prog = _mesa_init_vertex_program(ctx, CALLOC_STRUCT(gl_vertex_program),
314 target, id );
315 break;
316 case GL_FRAGMENT_PROGRAM_NV:
317 case GL_FRAGMENT_PROGRAM_ARB:
318 prog =_mesa_init_fragment_program(ctx,
319 CALLOC_STRUCT(gl_fragment_program),
320 target, id );
321 break;
322 case MESA_GEOMETRY_PROGRAM:
323 prog = _mesa_init_geometry_program(ctx,
324 CALLOC_STRUCT(gl_geometry_program),
325 target, id);
326 break;
327 default:
328 _mesa_problem(ctx, "bad target in _mesa_new_program");
329 prog = NULL;
330 }
331 return prog;
332 }
333
334
335 /**
336 * Delete a program and remove it from the hash table, ignoring the
337 * reference count.
338 * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation)
339 * by a device driver function.
340 */
341 void
342 _mesa_delete_program(struct gl_context *ctx, struct gl_program *prog)
343 {
344 (void) ctx;
345 ASSERT(prog);
346 ASSERT(prog->RefCount==0);
347
348 if (prog == &_mesa_DummyProgram)
349 return;
350
351 free(prog->String);
352
353 if (prog->Instructions) {
354 _mesa_free_instructions(prog->Instructions, prog->NumInstructions);
355 }
356 if (prog->Parameters) {
357 _mesa_free_parameter_list(prog->Parameters);
358 }
359
360 free(prog);
361 }
362
363
364 /**
365 * Return the gl_program object for a given ID.
366 * Basically just a wrapper for _mesa_HashLookup() to avoid a lot of
367 * casts elsewhere.
368 */
369 struct gl_program *
370 _mesa_lookup_program(struct gl_context *ctx, GLuint id)
371 {
372 if (id)
373 return (struct gl_program *) _mesa_HashLookup(ctx->Shared->Programs, id);
374 else
375 return NULL;
376 }
377
378
379 /**
380 * Reference counting for vertex/fragment programs
381 * This is normally only called from the _mesa_reference_program() macro
382 * when there's a real pointer change.
383 */
384 void
385 _mesa_reference_program_(struct gl_context *ctx,
386 struct gl_program **ptr,
387 struct gl_program *prog)
388 {
389 #ifndef NDEBUG
390 assert(ptr);
391 if (*ptr && prog) {
392 /* sanity check */
393 if ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB)
394 ASSERT(prog->Target == GL_VERTEX_PROGRAM_ARB);
395 else if ((*ptr)->Target == GL_FRAGMENT_PROGRAM_ARB)
396 ASSERT(prog->Target == GL_FRAGMENT_PROGRAM_ARB ||
397 prog->Target == GL_FRAGMENT_PROGRAM_NV);
398 else if ((*ptr)->Target == MESA_GEOMETRY_PROGRAM)
399 ASSERT(prog->Target == MESA_GEOMETRY_PROGRAM);
400 }
401 #endif
402
403 if (*ptr) {
404 GLboolean deleteFlag;
405
406 /*_glthread_LOCK_MUTEX((*ptr)->Mutex);*/
407 #if 0
408 printf("Program %p ID=%u Target=%s Refcount-- to %d\n",
409 *ptr, (*ptr)->Id,
410 ((*ptr)->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
411 ((*ptr)->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
412 (*ptr)->RefCount - 1);
413 #endif
414 ASSERT((*ptr)->RefCount > 0);
415 (*ptr)->RefCount--;
416
417 deleteFlag = ((*ptr)->RefCount == 0);
418 /*_glthread_UNLOCK_MUTEX((*ptr)->Mutex);*/
419
420 if (deleteFlag) {
421 ASSERT(ctx);
422 ctx->Driver.DeleteProgram(ctx, *ptr);
423 }
424
425 *ptr = NULL;
426 }
427
428 assert(!*ptr);
429 if (prog) {
430 /*_glthread_LOCK_MUTEX(prog->Mutex);*/
431 prog->RefCount++;
432 #if 0
433 printf("Program %p ID=%u Target=%s Refcount++ to %d\n",
434 prog, prog->Id,
435 (prog->Target == GL_VERTEX_PROGRAM_ARB ? "VP" :
436 (prog->Target == MESA_GEOMETRY_PROGRAM ? "GP" : "FP")),
437 prog->RefCount);
438 #endif
439 /*_glthread_UNLOCK_MUTEX(prog->Mutex);*/
440 }
441
442 *ptr = prog;
443 }
444
445
446 /**
447 * Return a copy of a program.
448 * XXX Problem here if the program object is actually OO-derivation
449 * made by a device driver.
450 */
451 struct gl_program *
452 _mesa_clone_program(struct gl_context *ctx, const struct gl_program *prog)
453 {
454 struct gl_program *clone;
455
456 clone = ctx->Driver.NewProgram(ctx, prog->Target, prog->Id);
457 if (!clone)
458 return NULL;
459
460 assert(clone->Target == prog->Target);
461 assert(clone->RefCount == 1);
462
463 clone->String = (GLubyte *) _mesa_strdup((char *) prog->String);
464 clone->Format = prog->Format;
465 clone->Instructions = _mesa_alloc_instructions(prog->NumInstructions);
466 if (!clone->Instructions) {
467 _mesa_reference_program(ctx, &clone, NULL);
468 return NULL;
469 }
470 _mesa_copy_instructions(clone->Instructions, prog->Instructions,
471 prog->NumInstructions);
472 clone->InputsRead = prog->InputsRead;
473 clone->OutputsWritten = prog->OutputsWritten;
474 clone->SamplersUsed = prog->SamplersUsed;
475 clone->ShadowSamplers = prog->ShadowSamplers;
476 memcpy(clone->TexturesUsed, prog->TexturesUsed, sizeof(prog->TexturesUsed));
477
478 if (prog->Parameters)
479 clone->Parameters = _mesa_clone_parameter_list(prog->Parameters);
480 memcpy(clone->LocalParams, prog->LocalParams, sizeof(clone->LocalParams));
481 clone->IndirectRegisterFiles = prog->IndirectRegisterFiles;
482 clone->NumInstructions = prog->NumInstructions;
483 clone->NumTemporaries = prog->NumTemporaries;
484 clone->NumParameters = prog->NumParameters;
485 clone->NumAttributes = prog->NumAttributes;
486 clone->NumAddressRegs = prog->NumAddressRegs;
487 clone->NumNativeInstructions = prog->NumNativeInstructions;
488 clone->NumNativeTemporaries = prog->NumNativeTemporaries;
489 clone->NumNativeParameters = prog->NumNativeParameters;
490 clone->NumNativeAttributes = prog->NumNativeAttributes;
491 clone->NumNativeAddressRegs = prog->NumNativeAddressRegs;
492 clone->NumAluInstructions = prog->NumAluInstructions;
493 clone->NumTexInstructions = prog->NumTexInstructions;
494 clone->NumTexIndirections = prog->NumTexIndirections;
495 clone->NumNativeAluInstructions = prog->NumNativeAluInstructions;
496 clone->NumNativeTexInstructions = prog->NumNativeTexInstructions;
497 clone->NumNativeTexIndirections = prog->NumNativeTexIndirections;
498
499 switch (prog->Target) {
500 case GL_VERTEX_PROGRAM_ARB:
501 {
502 const struct gl_vertex_program *vp = gl_vertex_program_const(prog);
503 struct gl_vertex_program *vpc = gl_vertex_program(clone);
504 vpc->IsPositionInvariant = vp->IsPositionInvariant;
505 }
506 break;
507 case GL_FRAGMENT_PROGRAM_ARB:
508 {
509 const struct gl_fragment_program *fp = gl_fragment_program_const(prog);
510 struct gl_fragment_program *fpc = gl_fragment_program(clone);
511 fpc->UsesKill = fp->UsesKill;
512 fpc->UsesDFdy = fp->UsesDFdy;
513 fpc->OriginUpperLeft = fp->OriginUpperLeft;
514 fpc->PixelCenterInteger = fp->PixelCenterInteger;
515 }
516 break;
517 case MESA_GEOMETRY_PROGRAM:
518 {
519 const struct gl_geometry_program *gp = gl_geometry_program_const(prog);
520 struct gl_geometry_program *gpc = gl_geometry_program(clone);
521 gpc->VerticesOut = gp->VerticesOut;
522 gpc->InputType = gp->InputType;
523 gpc->OutputType = gp->OutputType;
524 }
525 break;
526 default:
527 _mesa_problem(NULL, "Unexpected target in _mesa_clone_program");
528 }
529
530 return clone;
531 }
532
533
534 /**
535 * Insert 'count' NOP instructions at 'start' in the given program.
536 * Adjust branch targets accordingly.
537 */
538 GLboolean
539 _mesa_insert_instructions(struct gl_program *prog, GLuint start, GLuint count)
540 {
541 const GLuint origLen = prog->NumInstructions;
542 const GLuint newLen = origLen + count;
543 struct prog_instruction *newInst;
544 GLuint i;
545
546 /* adjust branches */
547 for (i = 0; i < prog->NumInstructions; i++) {
548 struct prog_instruction *inst = prog->Instructions + i;
549 if (inst->BranchTarget > 0) {
550 if ((GLuint)inst->BranchTarget >= start) {
551 inst->BranchTarget += count;
552 }
553 }
554 }
555
556 /* Alloc storage for new instructions */
557 newInst = _mesa_alloc_instructions(newLen);
558 if (!newInst) {
559 return GL_FALSE;
560 }
561
562 /* Copy 'start' instructions into new instruction buffer */
563 _mesa_copy_instructions(newInst, prog->Instructions, start);
564
565 /* init the new instructions */
566 _mesa_init_instructions(newInst + start, count);
567
568 /* Copy the remaining/tail instructions to new inst buffer */
569 _mesa_copy_instructions(newInst + start + count,
570 prog->Instructions + start,
571 origLen - start);
572
573 /* free old instructions */
574 _mesa_free_instructions(prog->Instructions, origLen);
575
576 /* install new instructions */
577 prog->Instructions = newInst;
578 prog->NumInstructions = newLen;
579
580 return GL_TRUE;
581 }
582
583 /**
584 * Delete 'count' instructions at 'start' in the given program.
585 * Adjust branch targets accordingly.
586 */
587 GLboolean
588 _mesa_delete_instructions(struct gl_program *prog, GLuint start, GLuint count)
589 {
590 const GLuint origLen = prog->NumInstructions;
591 const GLuint newLen = origLen - count;
592 struct prog_instruction *newInst;
593 GLuint i;
594
595 /* adjust branches */
596 for (i = 0; i < prog->NumInstructions; i++) {
597 struct prog_instruction *inst = prog->Instructions + i;
598 if (inst->BranchTarget > 0) {
599 if (inst->BranchTarget > (GLint) start) {
600 inst->BranchTarget -= count;
601 }
602 }
603 }
604
605 /* Alloc storage for new instructions */
606 newInst = _mesa_alloc_instructions(newLen);
607 if (!newInst) {
608 return GL_FALSE;
609 }
610
611 /* Copy 'start' instructions into new instruction buffer */
612 _mesa_copy_instructions(newInst, prog->Instructions, start);
613
614 /* Copy the remaining/tail instructions to new inst buffer */
615 _mesa_copy_instructions(newInst + start,
616 prog->Instructions + start + count,
617 newLen - start);
618
619 /* free old instructions */
620 _mesa_free_instructions(prog->Instructions, origLen);
621
622 /* install new instructions */
623 prog->Instructions = newInst;
624 prog->NumInstructions = newLen;
625
626 return GL_TRUE;
627 }
628
629
630 /**
631 * Search instructions for registers that match (oldFile, oldIndex),
632 * replacing them with (newFile, newIndex).
633 */
634 static void
635 replace_registers(struct prog_instruction *inst, GLuint numInst,
636 GLuint oldFile, GLuint oldIndex,
637 GLuint newFile, GLuint newIndex)
638 {
639 GLuint i, j;
640 for (i = 0; i < numInst; i++) {
641 /* src regs */
642 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
643 if (inst[i].SrcReg[j].File == oldFile &&
644 inst[i].SrcReg[j].Index == oldIndex) {
645 inst[i].SrcReg[j].File = newFile;
646 inst[i].SrcReg[j].Index = newIndex;
647 }
648 }
649 /* dst reg */
650 if (inst[i].DstReg.File == oldFile && inst[i].DstReg.Index == oldIndex) {
651 inst[i].DstReg.File = newFile;
652 inst[i].DstReg.Index = newIndex;
653 }
654 }
655 }
656
657
658 /**
659 * Search instructions for references to program parameters. When found,
660 * increment the parameter index by 'offset'.
661 * Used when combining programs.
662 */
663 static void
664 adjust_param_indexes(struct prog_instruction *inst, GLuint numInst,
665 GLuint offset)
666 {
667 GLuint i, j;
668 for (i = 0; i < numInst; i++) {
669 for (j = 0; j < _mesa_num_inst_src_regs(inst[i].Opcode); j++) {
670 GLuint f = inst[i].SrcReg[j].File;
671 if (f == PROGRAM_CONSTANT ||
672 f == PROGRAM_UNIFORM ||
673 f == PROGRAM_STATE_VAR) {
674 inst[i].SrcReg[j].Index += offset;
675 }
676 }
677 }
678 }
679
680
681 /**
682 * Combine two programs into one. Fix instructions so the outputs of
683 * the first program go to the inputs of the second program.
684 */
685 struct gl_program *
686 _mesa_combine_programs(struct gl_context *ctx,
687 const struct gl_program *progA,
688 const struct gl_program *progB)
689 {
690 struct prog_instruction *newInst;
691 struct gl_program *newProg;
692 const GLuint lenA = progA->NumInstructions - 1; /* omit END instr */
693 const GLuint lenB = progB->NumInstructions;
694 const GLuint numParamsA = _mesa_num_parameters(progA->Parameters);
695 const GLuint newLength = lenA + lenB;
696 GLboolean usedTemps[MAX_PROGRAM_TEMPS];
697 GLuint firstTemp = 0;
698 GLbitfield64 inputsB;
699 GLuint i;
700
701 ASSERT(progA->Target == progB->Target);
702
703 newInst = _mesa_alloc_instructions(newLength);
704 if (!newInst)
705 return GL_FALSE;
706
707 _mesa_copy_instructions(newInst, progA->Instructions, lenA);
708 _mesa_copy_instructions(newInst + lenA, progB->Instructions, lenB);
709
710 /* adjust branch / instruction addresses for B's instructions */
711 for (i = 0; i < lenB; i++) {
712 newInst[lenA + i].BranchTarget += lenA;
713 }
714
715 newProg = ctx->Driver.NewProgram(ctx, progA->Target, 0);
716 newProg->Instructions = newInst;
717 newProg->NumInstructions = newLength;
718
719 /* find used temp regs (we may need new temps below) */
720 _mesa_find_used_registers(newProg, PROGRAM_TEMPORARY,
721 usedTemps, MAX_PROGRAM_TEMPS);
722
723 if (newProg->Target == GL_FRAGMENT_PROGRAM_ARB) {
724 const struct gl_fragment_program *fprogA, *fprogB;
725 struct gl_fragment_program *newFprog;
726 GLbitfield64 progB_inputsRead = progB->InputsRead;
727 GLint progB_colorFile, progB_colorIndex;
728
729 fprogA = gl_fragment_program_const(progA);
730 fprogB = gl_fragment_program_const(progB);
731 newFprog = gl_fragment_program(newProg);
732
733 newFprog->UsesKill = fprogA->UsesKill || fprogB->UsesKill;
734 newFprog->UsesDFdy = fprogA->UsesDFdy || fprogB->UsesDFdy;
735
736 /* We'll do a search and replace for instances
737 * of progB_colorFile/progB_colorIndex below...
738 */
739 progB_colorFile = PROGRAM_INPUT;
740 progB_colorIndex = VARYING_SLOT_COL0;
741
742 /*
743 * The fragment program may get color from a state var rather than
744 * a fragment input (vertex output) if it's constant.
745 * See the texenvprogram.c code.
746 * So, search the program's parameter list now to see if the program
747 * gets color from a state var instead of a conventional fragment
748 * input register.
749 */
750 for (i = 0; i < progB->Parameters->NumParameters; i++) {
751 struct gl_program_parameter *p = &progB->Parameters->Parameters[i];
752 if (p->Type == PROGRAM_STATE_VAR &&
753 p->StateIndexes[0] == STATE_INTERNAL &&
754 p->StateIndexes[1] == STATE_CURRENT_ATTRIB &&
755 (int) p->StateIndexes[2] == (int) VERT_ATTRIB_COLOR0) {
756 progB_inputsRead |= VARYING_BIT_COL0;
757 progB_colorFile = PROGRAM_STATE_VAR;
758 progB_colorIndex = i;
759 break;
760 }
761 }
762
763 /* Connect color outputs of fprogA to color inputs of fprogB, via a
764 * new temporary register.
765 */
766 if ((progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) &&
767 (progB_inputsRead & VARYING_BIT_COL0)) {
768 GLint tempReg = _mesa_find_free_register(usedTemps, MAX_PROGRAM_TEMPS,
769 firstTemp);
770 if (tempReg < 0) {
771 _mesa_problem(ctx, "No free temp regs found in "
772 "_mesa_combine_programs(), using 31");
773 tempReg = 31;
774 }
775 firstTemp = tempReg + 1;
776
777 /* replace writes to result.color[0] with tempReg */
778 replace_registers(newInst, lenA,
779 PROGRAM_OUTPUT, FRAG_RESULT_COLOR,
780 PROGRAM_TEMPORARY, tempReg);
781 /* replace reads from the input color with tempReg */
782 replace_registers(newInst + lenA, lenB,
783 progB_colorFile, progB_colorIndex, /* search for */
784 PROGRAM_TEMPORARY, tempReg /* replace with */ );
785 }
786
787 /* compute combined program's InputsRead */
788 inputsB = progB_inputsRead;
789 if (progA->OutputsWritten & BITFIELD64_BIT(FRAG_RESULT_COLOR)) {
790 inputsB &= ~(1 << VARYING_SLOT_COL0);
791 }
792 newProg->InputsRead = progA->InputsRead | inputsB;
793 newProg->OutputsWritten = progB->OutputsWritten;
794 newProg->SamplersUsed = progA->SamplersUsed | progB->SamplersUsed;
795 }
796 else {
797 /* vertex program */
798 assert(0); /* XXX todo */
799 }
800
801 /*
802 * Merge parameters (uniforms, constants, etc)
803 */
804 newProg->Parameters = _mesa_combine_parameter_lists(progA->Parameters,
805 progB->Parameters);
806
807 adjust_param_indexes(newInst + lenA, lenB, numParamsA);
808
809
810 return newProg;
811 }
812
813
814 /**
815 * Populate the 'used' array with flags indicating which registers (TEMPs,
816 * INPUTs, OUTPUTs, etc, are used by the given program.
817 * \param file type of register to scan for
818 * \param used returns true/false flags for in use / free
819 * \param usedSize size of the 'used' array
820 */
821 void
822 _mesa_find_used_registers(const struct gl_program *prog,
823 gl_register_file file,
824 GLboolean used[], GLuint usedSize)
825 {
826 GLuint i, j;
827
828 memset(used, 0, usedSize);
829
830 for (i = 0; i < prog->NumInstructions; i++) {
831 const struct prog_instruction *inst = prog->Instructions + i;
832 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
833
834 if (inst->DstReg.File == file) {
835 ASSERT(inst->DstReg.Index < usedSize);
836 if(inst->DstReg.Index < usedSize)
837 used[inst->DstReg.Index] = GL_TRUE;
838 }
839
840 for (j = 0; j < n; j++) {
841 if (inst->SrcReg[j].File == file) {
842 ASSERT(inst->SrcReg[j].Index < (GLint) usedSize);
843 if (inst->SrcReg[j].Index < (GLint) usedSize)
844 used[inst->SrcReg[j].Index] = GL_TRUE;
845 }
846 }
847 }
848 }
849
850
851 /**
852 * Scan the given 'used' register flag array for the first entry
853 * that's >= firstReg.
854 * \param used vector of flags indicating registers in use (as returned
855 * by _mesa_find_used_registers())
856 * \param usedSize size of the 'used' array
857 * \param firstReg first register to start searching at
858 * \return index of unused register, or -1 if none.
859 */
860 GLint
861 _mesa_find_free_register(const GLboolean used[],
862 GLuint usedSize, GLuint firstReg)
863 {
864 GLuint i;
865
866 assert(firstReg < usedSize);
867
868 for (i = firstReg; i < usedSize; i++)
869 if (!used[i])
870 return i;
871
872 return -1;
873 }
874
875
876
877 /**
878 * Check if the given register index is valid (doesn't exceed implementation-
879 * dependent limits).
880 * \return GL_TRUE if OK, GL_FALSE if bad index
881 */
882 GLboolean
883 _mesa_valid_register_index(const struct gl_context *ctx,
884 gl_shader_type shaderType,
885 gl_register_file file, GLint index)
886 {
887 const struct gl_program_constants *c;
888
889 switch (shaderType) {
890 case MESA_SHADER_VERTEX:
891 c = &ctx->Const.VertexProgram;
892 break;
893 case MESA_SHADER_FRAGMENT:
894 c = &ctx->Const.FragmentProgram;
895 break;
896 case MESA_SHADER_GEOMETRY:
897 c = &ctx->Const.GeometryProgram;
898 break;
899 default:
900 _mesa_problem(ctx,
901 "unexpected shader type in _mesa_valid_register_index()");
902 return GL_FALSE;
903 }
904
905 switch (file) {
906 case PROGRAM_UNDEFINED:
907 return GL_TRUE; /* XXX or maybe false? */
908
909 case PROGRAM_TEMPORARY:
910 return index >= 0 && index < (GLint) c->MaxTemps;
911
912 case PROGRAM_UNIFORM:
913 case PROGRAM_STATE_VAR:
914 /* aka constant buffer */
915 return index >= 0 && index < (GLint) c->MaxUniformComponents / 4;
916
917 case PROGRAM_CONSTANT:
918 /* constant buffer w/ possible relative negative addressing */
919 return (index > (int) c->MaxUniformComponents / -4 &&
920 index < (int) c->MaxUniformComponents / 4);
921
922 case PROGRAM_INPUT:
923 if (index < 0)
924 return GL_FALSE;
925
926 switch (shaderType) {
927 case MESA_SHADER_VERTEX:
928 return index < VERT_ATTRIB_GENERIC0 + (GLint) c->MaxAttribs;
929 case MESA_SHADER_FRAGMENT:
930 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
931 case MESA_SHADER_GEOMETRY:
932 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
933 default:
934 return GL_FALSE;
935 }
936
937 case PROGRAM_OUTPUT:
938 if (index < 0)
939 return GL_FALSE;
940
941 switch (shaderType) {
942 case MESA_SHADER_VERTEX:
943 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
944 case MESA_SHADER_FRAGMENT:
945 return index < FRAG_RESULT_DATA0 + (GLint) ctx->Const.MaxDrawBuffers;
946 case MESA_SHADER_GEOMETRY:
947 return index < VARYING_SLOT_VAR0 + (GLint) ctx->Const.MaxVarying;
948 default:
949 return GL_FALSE;
950 }
951
952 case PROGRAM_ADDRESS:
953 return index >= 0 && index < (GLint) c->MaxAddressRegs;
954
955 default:
956 _mesa_problem(ctx,
957 "unexpected register file in _mesa_valid_register_index()");
958 return GL_FALSE;
959 }
960 }
961
962
963
964 /**
965 * "Post-process" a GPU program. This is intended to be used for debugging.
966 * Example actions include no-op'ing instructions or changing instruction
967 * behaviour.
968 */
969 void
970 _mesa_postprocess_program(struct gl_context *ctx, struct gl_program *prog)
971 {
972 static const GLfloat white[4] = { 0.5, 0.5, 0.5, 0.5 };
973 GLuint i;
974 GLuint whiteSwizzle;
975 GLint whiteIndex = _mesa_add_unnamed_constant(prog->Parameters,
976 (gl_constant_value *) white,
977 4, &whiteSwizzle);
978
979 (void) whiteIndex;
980
981 for (i = 0; i < prog->NumInstructions; i++) {
982 struct prog_instruction *inst = prog->Instructions + i;
983 const GLuint n = _mesa_num_inst_src_regs(inst->Opcode);
984
985 (void) n;
986
987 if (_mesa_is_tex_instruction(inst->Opcode)) {
988 #if 0
989 /* replace TEX/TXP/TXB with MOV */
990 inst->Opcode = OPCODE_MOV;
991 inst->DstReg.WriteMask = WRITEMASK_XYZW;
992 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
993 inst->SrcReg[0].Negate = NEGATE_NONE;
994 #endif
995
996 #if 0
997 /* disable shadow texture mode */
998 inst->TexShadow = 0;
999 #endif
1000 }
1001
1002 if (inst->Opcode == OPCODE_TXP) {
1003 #if 0
1004 inst->Opcode = OPCODE_MOV;
1005 inst->DstReg.WriteMask = WRITEMASK_XYZW;
1006 inst->SrcReg[0].File = PROGRAM_CONSTANT;
1007 inst->SrcReg[0].Index = whiteIndex;
1008 inst->SrcReg[0].Swizzle = SWIZZLE_XYZW;
1009 inst->SrcReg[0].Negate = NEGATE_NONE;
1010 #endif
1011 #if 0
1012 inst->TexShadow = 0;
1013 #endif
1014 #if 0
1015 inst->Opcode = OPCODE_TEX;
1016 inst->TexShadow = 0;
1017 #endif
1018 }
1019
1020 }
1021 }
1022
1023 /* Gets the minimum number of shader invocations per fragment.
1024 * This function is useful to determine if we need to do per
1025 * sample shading or per fragment shading.
1026 */
1027 GLint
1028 _mesa_get_min_invocations_per_fragment(struct gl_context *ctx,
1029 const struct gl_fragment_program *prog)
1030 {
1031 /* From ARB_sample_shading specification:
1032 * "Using gl_SampleID in a fragment shader causes the entire shader
1033 * to be evaluated per-sample."
1034 *
1035 * "Using gl_SamplePosition in a fragment shader causes the entire
1036 * shader to be evaluated per-sample."
1037 *
1038 * "If MULTISAMPLE or SAMPLE_SHADING_ARB is disabled, sample shading
1039 * has no effect."
1040 */
1041 if (ctx->Multisample.Enabled) {
1042 if (prog->Base.SystemValuesRead & (SYSTEM_BIT_SAMPLE_ID |
1043 SYSTEM_BIT_SAMPLE_POS))
1044 return MAX2(ctx->DrawBuffer->Visual.samples, 1);
1045 else if (ctx->Multisample.SampleShading)
1046 return MAX2(ceil(ctx->Multisample.MinSampleShadingValue *
1047 ctx->DrawBuffer->Visual.samples), 1);
1048 else
1049 return 1;
1050 }
1051 return 1;
1052 }