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