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