1/*
2 * Mesa 3-D graphics library
3 * Version:  7.3
4 *
5 * Copyright (C) 1999-2008  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 prog_parameter.c
27 * Program parameter lists and functions.
28 * \author Brian Paul
29 */
30
31
32#include "main/glheader.h"
33#include "main/imports.h"
34#include "main/macros.h"
35#include "prog_instruction.h"
36#include "prog_parameter.h"
37#include "prog_statevars.h"
38
39
40struct gl_program_parameter_list *
41_mesa_new_parameter_list(void)
42{
43   return CALLOC_STRUCT(gl_program_parameter_list);
44}
45
46
47struct gl_program_parameter_list *
48_mesa_new_parameter_list_sized(unsigned size)
49{
50   struct gl_program_parameter_list *p = _mesa_new_parameter_list();
51
52   if ((p != NULL) && (size != 0)) {
53      p->Size = size;
54
55      /* alloc arrays */
56      p->Parameters = (struct gl_program_parameter *)
57	 calloc(1, size * sizeof(struct gl_program_parameter));
58
59      p->ParameterValues = (gl_constant_value (*)[4])
60         _mesa_align_malloc(size * 4 *sizeof(gl_constant_value), 16);
61
62
63      if ((p->Parameters == NULL) || (p->ParameterValues == NULL)) {
64	 free(p->Parameters);
65	 _mesa_align_free(p->ParameterValues);
66	 free(p);
67	 p = NULL;
68      }
69   }
70
71   return p;
72}
73
74
75/**
76 * Free a parameter list and all its parameters
77 */
78void
79_mesa_free_parameter_list(struct gl_program_parameter_list *paramList)
80{
81   GLuint i;
82   for (i = 0; i < paramList->NumParameters; i++) {
83      if (paramList->Parameters[i].Name)
84	 free((void *) paramList->Parameters[i].Name);
85   }
86   free(paramList->Parameters);
87   if (paramList->ParameterValues)
88      _mesa_align_free(paramList->ParameterValues);
89   free(paramList);
90}
91
92
93/**
94 * Add a new parameter to a parameter list.
95 * Note that parameter values are usually 4-element GLfloat vectors.
96 * When size > 4 we'll allocate a sequential block of parameters to
97 * store all the values (in blocks of 4).
98 *
99 * \param paramList  the list to add the parameter to
100 * \param type  type of parameter, such as
101 * \param name  the parameter name, will be duplicated/copied!
102 * \param size  number of elements in 'values' vector (1..4, or more)
103 * \param datatype  GL_FLOAT, GL_FLOAT_VECx, GL_INT, GL_INT_VECx or GL_NONE.
104 * \param values  initial parameter value, up to 4 gl_constant_values, or NULL
105 * \param state  state indexes, or NULL
106 * \return  index of new parameter in the list, or -1 if error (out of mem)
107 */
108GLint
109_mesa_add_parameter(struct gl_program_parameter_list *paramList,
110                    gl_register_file type, const char *name,
111                    GLuint size, GLenum datatype,
112                    const gl_constant_value *values,
113                    const gl_state_index state[STATE_LENGTH],
114                    GLbitfield flags)
115{
116   const GLuint oldNum = paramList->NumParameters;
117   const GLuint sz4 = (size + 3) / 4; /* no. of new param slots needed */
118
119   assert(size > 0);
120
121   if (oldNum + sz4 > paramList->Size) {
122      /* Need to grow the parameter list array (alloc some extra) */
123      paramList->Size = paramList->Size + 4 * sz4;
124
125      /* realloc arrays */
126      paramList->Parameters = (struct gl_program_parameter *)
127	 _mesa_realloc(paramList->Parameters,
128		       oldNum * sizeof(struct gl_program_parameter),
129		       paramList->Size * sizeof(struct gl_program_parameter));
130
131      paramList->ParameterValues = (gl_constant_value (*)[4])
132         _mesa_align_realloc(paramList->ParameterValues,         /* old buf */
133                             oldNum * 4 * sizeof(gl_constant_value),/* old sz */
134                             paramList->Size*4*sizeof(gl_constant_value),/*new*/
135                             16);
136   }
137
138   if (!paramList->Parameters ||
139       !paramList->ParameterValues) {
140      /* out of memory */
141      paramList->NumParameters = 0;
142      paramList->Size = 0;
143      return -1;
144   }
145   else {
146      GLuint i, j;
147
148      paramList->NumParameters = oldNum + sz4;
149
150      memset(&paramList->Parameters[oldNum], 0,
151             sz4 * sizeof(struct gl_program_parameter));
152
153      for (i = 0; i < sz4; i++) {
154         struct gl_program_parameter *p = paramList->Parameters + oldNum + i;
155         p->Name = name ? _mesa_strdup(name) : NULL;
156         p->Type = type;
157         p->Size = size;
158         p->DataType = datatype;
159         p->Flags = flags;
160         if (values) {
161            if (size >= (i+1)*4) {
162               COPY_4V(paramList->ParameterValues[oldNum + i], values);
163            } else {
164               /* silence asan */
165               for (j = 0; j < 4; j++) {
166                  if (i*4+j < size) {
167                     paramList->ParameterValues[oldNum + i][j] = values[i*4+j];
168                  } else {
169                     paramList->ParameterValues[oldNum + i][j].f = 0.0f;
170                  }
171               }
172            }
173            values += 4;
174            p->Initialized = GL_TRUE;
175         }
176         else {
177            /* silence valgrind */
178            for (j = 0; j < 4; j++)
179            	paramList->ParameterValues[oldNum + i][j].f = 0;
180         }
181         size -= 4;
182      }
183
184      if (state) {
185         for (i = 0; i < STATE_LENGTH; i++)
186            paramList->Parameters[oldNum].StateIndexes[i] = state[i];
187      }
188
189      return (GLint) oldNum;
190   }
191}
192
193
194/**
195 * Add a new named program parameter (Ex: NV_fragment_program DEFINE statement)
196 * \return index of the new entry in the parameter list
197 */
198GLint
199_mesa_add_named_parameter(struct gl_program_parameter_list *paramList,
200                          const char *name, const gl_constant_value values[4])
201{
202   return _mesa_add_parameter(paramList, PROGRAM_NAMED_PARAM, name,
203                              4, GL_NONE, values, NULL, 0x0);
204
205}
206
207
208/**
209 * Add a new named constant to the parameter list.
210 * This will be used when the program contains something like this:
211 *    PARAM myVals = { 0, 1, 2, 3 };
212 *
213 * \param paramList  the parameter list
214 * \param name  the name for the constant
215 * \param values  four float values
216 * \return index/position of the new parameter in the parameter list
217 */
218GLint
219_mesa_add_named_constant(struct gl_program_parameter_list *paramList,
220                         const char *name, const gl_constant_value values[4],
221                         GLuint size)
222{
223   /* first check if this is a duplicate constant */
224   GLint pos;
225   for (pos = 0; pos < (GLint)paramList->NumParameters; pos++) {
226      const gl_constant_value *pvals = paramList->ParameterValues[pos];
227      if (pvals[0].u == values[0].u &&
228          pvals[1].u == values[1].u &&
229          pvals[2].u == values[2].u &&
230          pvals[3].u == values[3].u &&
231          strcmp(paramList->Parameters[pos].Name, name) == 0) {
232         /* Same name and value is already in the param list - reuse it */
233         return pos;
234      }
235   }
236   /* not found, add new parameter */
237   return _mesa_add_parameter(paramList, PROGRAM_CONSTANT, name,
238                              size, GL_NONE, values, NULL, 0x0);
239}
240
241
242/**
243 * Add a new unnamed constant to the parameter list.  This will be used
244 * when a fragment/vertex program contains something like this:
245 *    MOV r, { 0, 1, 2, 3 };
246 * If swizzleOut is non-null we'll search the parameter list for an
247 * existing instance of the constant which matches with a swizzle.
248 *
249 * \param paramList  the parameter list
250 * \param values  four float values
251 * \param swizzleOut  returns swizzle mask for accessing the constant
252 * \return index/position of the new parameter in the parameter list.
253 */
254GLint
255_mesa_add_typed_unnamed_constant(struct gl_program_parameter_list *paramList,
256                           const gl_constant_value values[4], GLuint size,
257                           GLenum datatype, GLuint *swizzleOut)
258{
259   GLint pos;
260   ASSERT(size >= 1);
261   ASSERT(size <= 4);
262
263   if (swizzleOut &&
264       _mesa_lookup_parameter_constant(paramList, values,
265                                       size, &pos, swizzleOut)) {
266      return pos;
267   }
268
269   /* Look for empty space in an already unnamed constant parameter
270    * to add this constant.  This will only work for single-element
271    * constants because we rely on smearing (i.e. .yyyy or .zzzz).
272    */
273   if (size == 1 && swizzleOut) {
274      for (pos = 0; pos < (GLint) paramList->NumParameters; pos++) {
275         struct gl_program_parameter *p = paramList->Parameters + pos;
276         if (p->Type == PROGRAM_CONSTANT && p->Size + size <= 4) {
277            /* ok, found room */
278            gl_constant_value *pVal = paramList->ParameterValues[pos];
279            GLuint swz = p->Size; /* 1, 2 or 3 for Y, Z, W */
280            pVal[p->Size] = values[0];
281            p->Size++;
282            *swizzleOut = MAKE_SWIZZLE4(swz, swz, swz, swz);
283            return pos;
284         }
285      }
286   }
287
288   /* add a new parameter to store this constant */
289   pos = _mesa_add_parameter(paramList, PROGRAM_CONSTANT, NULL,
290                             size, datatype, values, NULL, 0x0);
291   if (pos >= 0 && swizzleOut) {
292      if (size == 1)
293         *swizzleOut = SWIZZLE_XXXX;
294      else
295         *swizzleOut = SWIZZLE_NOOP;
296   }
297   return pos;
298}
299
300/**
301 * Add a new unnamed constant to the parameter list.  This will be used
302 * when a fragment/vertex program contains something like this:
303 *    MOV r, { 0, 1, 2, 3 };
304 * If swizzleOut is non-null we'll search the parameter list for an
305 * existing instance of the constant which matches with a swizzle.
306 *
307 * \param paramList  the parameter list
308 * \param values  four float values
309 * \param swizzleOut  returns swizzle mask for accessing the constant
310 * \return index/position of the new parameter in the parameter list.
311 * \sa _mesa_add_typed_unnamed_constant
312 */
313GLint
314_mesa_add_unnamed_constant(struct gl_program_parameter_list *paramList,
315                           const gl_constant_value values[4], GLuint size,
316                           GLuint *swizzleOut)
317{
318   return _mesa_add_typed_unnamed_constant(paramList, values, size, GL_NONE,
319                                           swizzleOut);
320}
321
322/**
323 * Add parameter representing a varying variable.
324 */
325GLint
326_mesa_add_varying(struct gl_program_parameter_list *paramList,
327                  const char *name, GLuint size, GLenum datatype,
328                  GLbitfield flags)
329{
330   GLint i = _mesa_lookup_parameter_index(paramList, -1, name);
331   if (i >= 0 && paramList->Parameters[i].Type == PROGRAM_VARYING) {
332      /* already in list */
333      return i;
334   }
335   else {
336      /*assert(size == 4);*/
337      i = _mesa_add_parameter(paramList, PROGRAM_VARYING, name,
338                              size, datatype, NULL, NULL, flags);
339      return i;
340   }
341}
342
343
344/**
345 * Add parameter representing a vertex program attribute.
346 * \param size  size of attribute (in floats), may be -1 if unknown
347 * \param attrib  the attribute index, or -1 if unknown
348 */
349GLint
350_mesa_add_attribute(struct gl_program_parameter_list *paramList,
351                    const char *name, GLint size, GLenum datatype, GLint attrib)
352{
353   GLint i = _mesa_lookup_parameter_index(paramList, -1, name);
354   if (i >= 0) {
355      /* replace */
356      if (attrib < 0)
357         attrib = i;
358      paramList->Parameters[i].StateIndexes[0] = attrib;
359   }
360   else {
361      /* add */
362      gl_state_index state[STATE_LENGTH];
363      state[0] = (gl_state_index) attrib;
364      if (size < 0)
365         size = 4;
366      i = _mesa_add_parameter(paramList, PROGRAM_INPUT, name,
367                              size, datatype, NULL, state, 0x0);
368   }
369   return i;
370}
371
372
373
374#if 0 /* not used yet */
375/**
376 * Returns the number of 4-component registers needed to store a piece
377 * of GL state.  For matrices this may be as many as 4 registers,
378 * everything else needs
379 * just 1 register.
380 */
381static GLuint
382sizeof_state_reference(const GLint *stateTokens)
383{
384   if (stateTokens[0] == STATE_MATRIX) {
385      GLuint rows = stateTokens[4] - stateTokens[3] + 1;
386      assert(rows >= 1);
387      assert(rows <= 4);
388      return rows;
389   }
390   else {
391      return 1;
392   }
393}
394#endif
395
396
397/**
398 * Add a new state reference to the parameter list.
399 * This will be used when the program contains something like this:
400 *    PARAM ambient = state.material.front.ambient;
401 *
402 * \param paramList  the parameter list
403 * \param stateTokens  an array of 5 (STATE_LENGTH) state tokens
404 * \return index of the new parameter.
405 */
406GLint
407_mesa_add_state_reference(struct gl_program_parameter_list *paramList,
408                          const gl_state_index stateTokens[STATE_LENGTH])
409{
410   const GLuint size = 4; /* XXX fix */
411   char *name;
412   GLint index;
413
414   /* Check if the state reference is already in the list */
415   for (index = 0; index < (GLint) paramList->NumParameters; index++) {
416      if (!memcmp(paramList->Parameters[index].StateIndexes,
417		  stateTokens, STATE_LENGTH * sizeof(gl_state_index))) {
418	 return index;
419      }
420   }
421
422   name = _mesa_program_state_string(stateTokens);
423   index = _mesa_add_parameter(paramList, PROGRAM_STATE_VAR, name,
424                               size, GL_NONE,
425                               NULL, (gl_state_index *) stateTokens, 0x0);
426   paramList->StateFlags |= _mesa_program_state_flags(stateTokens);
427
428   /* free name string here since we duplicated it in add_parameter() */
429   free(name);
430
431   return index;
432}
433
434
435/**
436 * Lookup a parameter value by name in the given parameter list.
437 * \return pointer to the float[4] values.
438 */
439gl_constant_value *
440_mesa_lookup_parameter_value(const struct gl_program_parameter_list *paramList,
441                             GLsizei nameLen, const char *name)
442{
443   GLint i = _mesa_lookup_parameter_index(paramList, nameLen, name);
444   if (i < 0)
445      return NULL;
446   else
447      return paramList->ParameterValues[i];
448}
449
450
451/**
452 * Given a program parameter name, find its position in the list of parameters.
453 * \param paramList  the parameter list to search
454 * \param nameLen  length of name (in chars).
455 *                 If length is negative, assume that name is null-terminated.
456 * \param name  the name to search for
457 * \return index of parameter in the list.
458 */
459GLint
460_mesa_lookup_parameter_index(const struct gl_program_parameter_list *paramList,
461                             GLsizei nameLen, const char *name)
462{
463   GLint i;
464
465   if (!paramList)
466      return -1;
467
468   if (nameLen == -1) {
469      /* name is null-terminated */
470      for (i = 0; i < (GLint) paramList->NumParameters; i++) {
471         if (paramList->Parameters[i].Name &&
472	     strcmp(paramList->Parameters[i].Name, name) == 0)
473            return i;
474      }
475   }
476   else {
477      /* name is not null-terminated, use nameLen */
478      for (i = 0; i < (GLint) paramList->NumParameters; i++) {
479         if (paramList->Parameters[i].Name &&
480	     strncmp(paramList->Parameters[i].Name, name, nameLen) == 0
481             && strlen(paramList->Parameters[i].Name) == (size_t)nameLen)
482            return i;
483      }
484   }
485   return -1;
486}
487
488
489/**
490 * Look for a float vector in the given parameter list.  The float vector
491 * may be of length 1, 2, 3 or 4.  If swizzleOut is non-null, we'll try
492 * swizzling to find a match.
493 * \param list  the parameter list to search
494 * \param v  the float vector to search for
495 * \param vSize  number of element in v
496 * \param posOut  returns the position of the constant, if found
497 * \param swizzleOut  returns a swizzle mask describing location of the
498 *                    vector elements if found.
499 * \return GL_TRUE if found, GL_FALSE if not found
500 */
501GLboolean
502_mesa_lookup_parameter_constant(const struct gl_program_parameter_list *list,
503                                const gl_constant_value v[], GLuint vSize,
504                                GLint *posOut, GLuint *swizzleOut)
505{
506   GLuint i;
507
508   assert(vSize >= 1);
509   assert(vSize <= 4);
510
511   if (!list) {
512      *posOut = -1;
513      return GL_FALSE;
514   }
515
516   for (i = 0; i < list->NumParameters; i++) {
517      if (list->Parameters[i].Type == PROGRAM_CONSTANT) {
518         if (!swizzleOut) {
519            /* swizzle not allowed */
520            GLuint j, match = 0;
521            for (j = 0; j < vSize; j++) {
522               if (v[j].u == list->ParameterValues[i][j].u)
523                  match++;
524            }
525            if (match == vSize) {
526               *posOut = i;
527               return GL_TRUE;
528            }
529         }
530         else {
531            /* try matching w/ swizzle */
532             if (vSize == 1) {
533                /* look for v[0] anywhere within float[4] value */
534                GLuint j;
535                for (j = 0; j < list->Parameters[i].Size; j++) {
536                   if (list->ParameterValues[i][j].u == v[0].u) {
537                      /* found it */
538                      *posOut = i;
539                      *swizzleOut = MAKE_SWIZZLE4(j, j, j, j);
540                      return GL_TRUE;
541                   }
542                }
543             }
544             else if (vSize <= list->Parameters[i].Size) {
545                /* see if we can match this constant (with a swizzle) */
546                GLuint swz[4];
547                GLuint match = 0, j, k;
548                for (j = 0; j < vSize; j++) {
549                   if (v[j].u == list->ParameterValues[i][j].u) {
550                      swz[j] = j;
551                      match++;
552                   }
553                   else {
554                      for (k = 0; k < list->Parameters[i].Size; k++) {
555                         if (v[j].u == list->ParameterValues[i][k].u) {
556                            swz[j] = k;
557                            match++;
558                            break;
559                         }
560                      }
561                   }
562                }
563                /* smear last value to remaining positions */
564                for (; j < 4; j++)
565                   swz[j] = swz[j-1];
566
567                if (match == vSize) {
568                   *posOut = i;
569                   *swizzleOut = MAKE_SWIZZLE4(swz[0], swz[1], swz[2], swz[3]);
570                   return GL_TRUE;
571                }
572             }
573         }
574      }
575   }
576
577   *posOut = -1;
578   return GL_FALSE;
579}
580
581
582struct gl_program_parameter_list *
583_mesa_clone_parameter_list(const struct gl_program_parameter_list *list)
584{
585   struct gl_program_parameter_list *clone;
586   GLuint i;
587
588   clone = _mesa_new_parameter_list();
589   if (!clone)
590      return NULL;
591
592   /** Not too efficient, but correct */
593   for (i = 0; i < list->NumParameters; i++) {
594      struct gl_program_parameter *p = list->Parameters + i;
595      struct gl_program_parameter *pCopy;
596      GLuint size = MIN2(p->Size, 4);
597      GLint j = _mesa_add_parameter(clone, p->Type, p->Name, size, p->DataType,
598                                    list->ParameterValues[i], NULL, 0x0);
599      ASSERT(j >= 0);
600      pCopy = clone->Parameters + j;
601      pCopy->Flags = p->Flags;
602      /* copy state indexes */
603      if (p->Type == PROGRAM_STATE_VAR) {
604         GLint k;
605         for (k = 0; k < STATE_LENGTH; k++) {
606            pCopy->StateIndexes[k] = p->StateIndexes[k];
607         }
608      }
609      else {
610         clone->Parameters[j].Size = p->Size;
611      }
612
613   }
614
615   clone->StateFlags = list->StateFlags;
616
617   return clone;
618}
619
620
621/**
622 * Return a new parameter list which is listA + listB.
623 */
624struct gl_program_parameter_list *
625_mesa_combine_parameter_lists(const struct gl_program_parameter_list *listA,
626                              const struct gl_program_parameter_list *listB)
627{
628   struct gl_program_parameter_list *list;
629
630   if (listA) {
631      list = _mesa_clone_parameter_list(listA);
632      if (list && listB) {
633         GLuint i;
634         for (i = 0; i < listB->NumParameters; i++) {
635            struct gl_program_parameter *param = listB->Parameters + i;
636            _mesa_add_parameter(list, param->Type, param->Name, param->Size,
637                                param->DataType,
638                                listB->ParameterValues[i],
639                                param->StateIndexes,
640                                param->Flags);
641         }
642      }
643   }
644   else if (listB) {
645      list = _mesa_clone_parameter_list(listB);
646   }
647   else {
648      list = NULL;
649   }
650   return list;
651}
652
653
654/**
655 * Count the number of parameters in the last that match the given type.
656 */
657GLuint
658_mesa_num_parameters_of_type(const struct gl_program_parameter_list *list,
659                             gl_register_file type)
660{
661   GLuint i, count = 0;
662   if (list) {
663      for (i = 0; i < list->NumParameters; i++) {
664         if (list->Parameters[i].Type == type)
665            count++;
666      }
667   }
668   return count;
669}
670