t_vp_build.c revision 447697885634a92ffc3b9da2a23407406406af97
1/*
2 * Mesa 3-D graphics library
3 * Version:  6.3
4 *
5 * Copyright (C) 2005  Tungsten Graphics   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 * TUNGSTEN GRAPHICS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 * WHETHER IN
22 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25
26/**
27 * \file t_vp_build.c
28 * Create a vertex program to execute the current fixed function T&L pipeline.
29 * \author Keith Whitwell
30 */
31
32
33#include "glheader.h"
34#include "macros.h"
35#include "enums.h"
36#include "t_context.h"
37#include "t_vp_build.h"
38
39#include "shader/program.h"
40#include "shader/nvvertprog.h"
41#include "shader/arbvertparse.h"
42
43struct state_key {
44   unsigned light_global_enabled:1;
45   unsigned light_local_viewer:1;
46   unsigned light_twoside:1;
47   unsigned light_color_material:1;
48   unsigned light_color_material_mask:12;
49   unsigned light_material_mask:12;
50
51   unsigned normalize:1;
52   unsigned rescale_normals:1;
53   unsigned fog_source_is_depth:1;
54   unsigned tnl_do_vertex_fog:1;
55   unsigned separate_specular:1;
56   unsigned fog_enabled:1;
57   unsigned fog_mode:2;
58   unsigned point_attenuated:1;
59   unsigned texture_enabled_global:1;
60
61   struct {
62      unsigned light_enabled:1;
63      unsigned light_eyepos3_is_zero:1;
64      unsigned light_spotcutoff_is_180:1;
65      unsigned light_attenuated:1;
66      unsigned texunit_really_enabled:1;
67      unsigned texmat_enabled:1;
68      unsigned texgen_enabled:4;
69      unsigned texgen_mode0:4;
70      unsigned texgen_mode1:4;
71      unsigned texgen_mode2:4;
72      unsigned texgen_mode3:4;
73   } unit[8];
74};
75
76
77
78#define FOG_LINEAR   0
79#define FOG_EXP      1
80#define FOG_EXP2     2
81#define FOG_UNKNOWN  3
82
83static GLuint translate_fog_mode( GLenum mode )
84{
85   switch (mode) {
86   case GL_LINEAR: return FOG_LINEAR;
87   case GL_EXP: return FOG_EXP;
88   case GL_EXP2: return FOG_EXP2;
89   default: return FOG_UNKNOWN;
90   }
91}
92
93#define TXG_NONE           0
94#define TXG_OBJ_LINEAR     1
95#define TXG_EYE_LINEAR     2
96#define TXG_SPHERE_MAP     3
97#define TXG_REFLECTION_MAP 4
98#define TXG_NORMAL_MAP     5
99
100static GLuint translate_texgen( GLboolean enabled, GLenum mode )
101{
102   if (!enabled)
103      return TXG_NONE;
104
105   switch (mode) {
106   case GL_OBJECT_LINEAR: return TXG_OBJ_LINEAR;
107   case GL_EYE_LINEAR: return TXG_EYE_LINEAR;
108   case GL_SPHERE_MAP: return TXG_SPHERE_MAP;
109   case GL_REFLECTION_MAP_NV: return TXG_REFLECTION_MAP;
110   case GL_NORMAL_MAP_NV: return TXG_NORMAL_MAP;
111   default: return TXG_NONE;
112   }
113}
114
115static struct state_key *make_state_key( GLcontext *ctx )
116{
117   TNLcontext *tnl = TNL_CONTEXT(ctx);
118   struct vertex_buffer *VB = &tnl->vb;
119   struct state_key *key = CALLOC_STRUCT(state_key);
120   GLuint i;
121
122   key->separate_specular = (ctx->Light.Model.ColorControl ==
123			     GL_SEPARATE_SPECULAR_COLOR);
124
125   if (ctx->Light.Enabled) {
126      key->light_global_enabled = 1;
127
128      if (ctx->Light.Model.LocalViewer)
129	 key->light_local_viewer = 1;
130
131      if (ctx->Light.Model.TwoSide)
132	 key->light_twoside = 1;
133
134      if (ctx->Light.ColorMaterialEnabled) {
135	 key->light_color_material = 1;
136	 key->light_color_material_mask = ctx->Light.ColorMaterialBitmask;
137      }
138
139      for (i = _TNL_ATTRIB_MAT_FRONT_AMBIENT ; i < _TNL_ATTRIB_INDEX ; i++)
140	 if (VB->AttribPtr[i]->stride)
141	    key->light_material_mask |= 1<<(i-_TNL_ATTRIB_MAT_FRONT_AMBIENT);
142
143      for (i = 0; i < MAX_LIGHTS; i++) {
144	 struct gl_light *light = &ctx->Light.Light[i];
145
146	 if (light->Enabled) {
147	    key->unit[i].light_enabled = 1;
148
149	    if (light->EyePosition[3] == 0.0)
150	       key->unit[i].light_eyepos3_is_zero = 1;
151
152	    if (light->SpotCutoff == 180.0)
153	       key->unit[i].light_spotcutoff_is_180 = 1;
154
155	    if (light->ConstantAttenuation != 1.0 ||
156		light->LinearAttenuation != 0.0 ||
157		light->QuadraticAttenuation != 0.0)
158	       key->unit[i].light_attenuated = 1;
159	 }
160      }
161   }
162
163   if (ctx->Transform.Normalize)
164      key->normalize = 1;
165
166   if (ctx->Transform.RescaleNormals)
167      key->rescale_normals = 1;
168
169   if (ctx->Fog.Enabled)
170      key->fog_enabled = 1;
171
172   if (key->fog_enabled) {
173      if (ctx->Fog.FogCoordinateSource == GL_FRAGMENT_DEPTH_EXT)
174	 key->fog_source_is_depth = 1;
175
176      if (tnl->_DoVertexFog)
177	 key->tnl_do_vertex_fog = 1;
178
179      key->fog_mode = translate_fog_mode(ctx->Fog.Mode);
180   }
181
182   if (ctx->Point._Attenuated)
183      key->point_attenuated = 1;
184
185   if (ctx->Texture._TexGenEnabled ||
186       ctx->Texture._TexMatEnabled ||
187       ctx->Texture._EnabledUnits)
188      key->texture_enabled_global = 1;
189
190   for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
191      struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
192
193      if (texUnit->_ReallyEnabled)
194	 key->unit[i].texunit_really_enabled = 1;
195
196      if (ctx->Texture._TexMatEnabled & ENABLE_TEXMAT(i))
197	 key->unit[i].texmat_enabled = 1;
198
199      if (texUnit->TexGenEnabled) {
200	 key->unit[i].texgen_enabled = 1;
201
202	 key->unit[i].texgen_mode0 =
203	    translate_texgen( texUnit->TexGenEnabled & (1<<0),
204			      texUnit->GenModeS );
205	 key->unit[i].texgen_mode1 =
206	    translate_texgen( texUnit->TexGenEnabled & (1<<1),
207			      texUnit->GenModeT );
208	 key->unit[i].texgen_mode2 =
209	    translate_texgen( texUnit->TexGenEnabled & (1<<2),
210			      texUnit->GenModeR );
211	 key->unit[i].texgen_mode3 =
212	    translate_texgen( texUnit->TexGenEnabled & (1<<3),
213			      texUnit->GenModeQ );
214      }
215   }
216
217   return key;
218}
219
220
221
222/* Very useful debugging tool - produces annotated listing of
223 * generated program with line/function references for each
224 * instruction back into this file:
225 */
226#define DISASSEM (MESA_VERBOSE&VERBOSE_DISASSEM)
227
228/* Should be tunable by the driver - do we want to do matrix
229 * multiplications with DP4's or with MUL/MAD's?  SSE works better
230 * with the latter, drivers may differ.
231 */
232#define PREFER_DP4 0
233
234#define MAX_INSN 200
235
236/* Use uregs to represent registers internally, translate to Mesa's
237 * expected formats on emit.
238 *
239 * NOTE: These are passed by value extensively in this file rather
240 * than as usual by pointer reference.  If this disturbs you, try
241 * remembering they are just 32bits in size.
242 *
243 * GCC is smart enough to deal with these dword-sized structures in
244 * much the same way as if I had defined them as dwords and was using
245 * macros to access and set the fields.  This is much nicer and easier
246 * to evolve.
247 */
248struct ureg {
249   GLuint file:4;
250   GLuint idx:8;
251   GLuint negate:1;
252   GLuint swz:12;
253   GLuint pad:7;
254};
255
256
257struct tnl_program {
258   const struct state_key *state;
259   struct vertex_program *program;
260
261   GLuint temp_in_use;
262   GLuint temp_reserved;
263
264   struct ureg eye_position;
265   struct ureg eye_position_normalized;
266   struct ureg eye_normal;
267   struct ureg identity;
268
269   GLuint materials;
270   GLuint color_materials;
271};
272
273
274const static struct ureg undef = {
275   ~0,
276   ~0,
277   0,
278   0,
279   0
280};
281
282/* Local shorthand:
283 */
284#define X    SWIZZLE_X
285#define Y    SWIZZLE_Y
286#define Z    SWIZZLE_Z
287#define W    SWIZZLE_W
288
289
290/* Construct a ureg:
291 */
292static struct ureg make_ureg(GLuint file, GLuint idx)
293{
294   struct ureg reg;
295   reg.file = file;
296   reg.idx = idx;
297   reg.negate = 0;
298   reg.swz = SWIZZLE_NOOP;
299   reg.pad = 0;
300   return reg;
301}
302
303
304
305static struct ureg negate( struct ureg reg )
306{
307   reg.negate ^= 1;
308   return reg;
309}
310
311
312static struct ureg swizzle( struct ureg reg, int x, int y, int z, int w )
313{
314   reg.swz = MAKE_SWIZZLE4(GET_SWZ(reg.swz, x),
315			   GET_SWZ(reg.swz, y),
316			   GET_SWZ(reg.swz, z),
317			   GET_SWZ(reg.swz, w));
318
319   return reg;
320}
321
322static struct ureg swizzle1( struct ureg reg, int x )
323{
324   return swizzle(reg, x, x, x, x);
325}
326
327static struct ureg get_temp( struct tnl_program *p )
328{
329   int bit = ffs( ~p->temp_in_use );
330   if (!bit) {
331      fprintf(stderr, "%s: out of temporaries\n", __FILE__);
332      exit(1);
333   }
334
335   p->temp_in_use |= 1<<(bit-1);
336   return make_ureg(PROGRAM_TEMPORARY, bit-1);
337}
338
339static struct ureg reserve_temp( struct tnl_program *p )
340{
341   struct ureg temp = get_temp( p );
342   p->temp_reserved |= 1<<temp.idx;
343   return temp;
344}
345
346static void release_temp( struct tnl_program *p, struct ureg reg )
347{
348   if (reg.file == PROGRAM_TEMPORARY) {
349      p->temp_in_use &= ~(1<<reg.idx);
350      p->temp_in_use |= p->temp_reserved; /* can't release reserved temps */
351   }
352}
353
354static void release_temps( struct tnl_program *p )
355{
356   p->temp_in_use = p->temp_reserved;
357}
358
359
360
361static struct ureg register_input( struct tnl_program *p, GLuint input )
362{
363   p->program->InputsRead |= (1<<input);
364   return make_ureg(PROGRAM_INPUT, input);
365}
366
367static struct ureg register_output( struct tnl_program *p, GLuint output )
368{
369   p->program->OutputsWritten |= (1<<output);
370   return make_ureg(PROGRAM_OUTPUT, output);
371}
372
373static struct ureg register_const4f( struct tnl_program *p,
374			      GLfloat s0,
375			      GLfloat s1,
376			      GLfloat s2,
377			      GLfloat s3)
378{
379   GLfloat values[4];
380   GLuint idx;
381   values[0] = s0;
382   values[1] = s1;
383   values[2] = s2;
384   values[3] = s3;
385   idx = _mesa_add_unnamed_constant( p->program->Parameters, values );
386   return make_ureg(PROGRAM_STATE_VAR, idx);
387}
388
389#define register_const1f(p, s0)         register_const4f(p, s0, 0, 0, 1)
390#define register_scalar_const(p, s0)    register_const4f(p, s0, s0, s0, s0)
391#define register_const2f(p, s0, s1)     register_const4f(p, s0, s1, 0, 1)
392#define register_const3f(p, s0, s1, s2) register_const4f(p, s0, s1, s2, 1)
393
394static GLboolean is_undef( struct ureg reg )
395{
396   return reg.file == 0xf;
397}
398
399static struct ureg get_identity_param( struct tnl_program *p )
400{
401   if (is_undef(p->identity))
402      p->identity = register_const4f(p, 0,0,0,1);
403
404   return p->identity;
405}
406
407static struct ureg register_param6( struct tnl_program *p,
408				   GLint s0,
409				   GLint s1,
410				   GLint s2,
411				   GLint s3,
412				   GLint s4,
413				   GLint s5)
414{
415   GLint tokens[6];
416   GLuint idx;
417   tokens[0] = s0;
418   tokens[1] = s1;
419   tokens[2] = s2;
420   tokens[3] = s3;
421   tokens[4] = s4;
422   tokens[5] = s5;
423   idx = _mesa_add_state_reference( p->program->Parameters, tokens );
424   return make_ureg(PROGRAM_STATE_VAR, idx);
425}
426
427
428#define register_param1(p,s0)          register_param6(p,s0,0,0,0,0,0)
429#define register_param2(p,s0,s1)       register_param6(p,s0,s1,0,0,0,0)
430#define register_param3(p,s0,s1,s2)    register_param6(p,s0,s1,s2,0,0,0)
431#define register_param4(p,s0,s1,s2,s3) register_param6(p,s0,s1,s2,s3,0,0)
432
433
434static void register_matrix_param6( struct tnl_program *p,
435				    GLint s0,
436				    GLint s1,
437				    GLint s2,
438				    GLint s3,
439				    GLint s4,
440				    GLint s5,
441				    struct ureg *matrix )
442{
443   GLuint i;
444
445   /* This is a bit sad as the support is there to pull the whole
446    * matrix out in one go:
447    */
448   for (i = 0; i <= s4 - s3; i++)
449      matrix[i] = register_param6( p, s0, s1, s2, i, i, s5 );
450}
451
452
453static void emit_arg( struct vp_src_register *src,
454		      struct ureg reg )
455{
456   src->File = reg.file;
457   src->Index = reg.idx;
458   src->Swizzle = reg.swz;
459   src->Negate = reg.negate;
460   src->RelAddr = 0;
461   src->pad = 0;
462}
463
464static void emit_dst( struct vp_dst_register *dst,
465		      struct ureg reg, GLuint mask )
466{
467   dst->File = reg.file;
468   dst->Index = reg.idx;
469   /* allow zero as a shorthand for xyzw */
470   dst->WriteMask = mask ? mask : WRITEMASK_XYZW;
471   dst->pad = 0;
472}
473
474static void debug_insn( struct vp_instruction *inst, const char *fn,
475			GLuint line )
476{
477   if (DISASSEM) {
478      static const char *last_fn;
479
480      if (fn != last_fn) {
481	 last_fn = fn;
482	 _mesa_printf("%s:\n", fn);
483      }
484
485      _mesa_printf("%d:\t", line);
486      _mesa_debug_vp_inst(1, inst);
487   }
488}
489
490
491static void emit_op3fn(struct tnl_program *p,
492		       GLuint op,
493		       struct ureg dest,
494		       GLuint mask,
495		       struct ureg src0,
496		       struct ureg src1,
497		       struct ureg src2,
498		       const char *fn,
499		       GLuint line)
500{
501   GLuint nr = p->program->Base.NumInstructions++;
502   struct vp_instruction *inst = &p->program->Instructions[nr];
503
504   if (p->program->Base.NumInstructions > MAX_INSN) {
505      _mesa_problem(0, "Out of instructions in emit_op3fn\n");
506      return;
507   }
508
509   inst->Opcode = op;
510   inst->StringPos = 0;
511   inst->Data = 0;
512
513   emit_arg( &inst->SrcReg[0], src0 );
514   emit_arg( &inst->SrcReg[1], src1 );
515   emit_arg( &inst->SrcReg[2], src2 );
516
517   emit_dst( &inst->DstReg, dest, mask );
518
519   debug_insn(inst, fn, line);
520}
521
522
523
524#define emit_op3(p, op, dst, mask, src0, src1, src2) \
525   emit_op3fn(p, op, dst, mask, src0, src1, src2, __FUNCTION__, __LINE__)
526
527#define emit_op2(p, op, dst, mask, src0, src1) \
528    emit_op3fn(p, op, dst, mask, src0, src1, undef, __FUNCTION__, __LINE__)
529
530#define emit_op1(p, op, dst, mask, src0) \
531    emit_op3fn(p, op, dst, mask, src0, undef, undef, __FUNCTION__, __LINE__)
532
533
534static struct ureg make_temp( struct tnl_program *p, struct ureg reg )
535{
536   if (reg.file == PROGRAM_TEMPORARY &&
537       !(p->temp_reserved & (1<<reg.idx)))
538      return reg;
539   else {
540      struct ureg temp = get_temp(p);
541      emit_op1(p, VP_OPCODE_MOV, temp, 0, reg);
542      return temp;
543   }
544}
545
546
547/* Currently no tracking performed of input/output/register size or
548 * active elements.  Could be used to reduce these operations, as
549 * could the matrix type.
550 */
551static void emit_matrix_transform_vec4( struct tnl_program *p,
552					struct ureg dest,
553					const struct ureg *mat,
554					struct ureg src)
555{
556   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_X, src, mat[0]);
557   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_Y, src, mat[1]);
558   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_Z, src, mat[2]);
559   emit_op2(p, VP_OPCODE_DP4, dest, WRITEMASK_W, src, mat[3]);
560}
561
562/* This version is much easier to implement if writemasks are not
563 * supported natively on the target or (like SSE), the target doesn't
564 * have a clean/obvious dotproduct implementation.
565 */
566static void emit_transpose_matrix_transform_vec4( struct tnl_program *p,
567						  struct ureg dest,
568						  const struct ureg *mat,
569						  struct ureg src)
570{
571   struct ureg tmp;
572
573   if (dest.file != PROGRAM_TEMPORARY)
574      tmp = get_temp(p);
575   else
576      tmp = dest;
577
578   emit_op2(p, VP_OPCODE_MUL, tmp, 0, swizzle1(src,X), mat[0]);
579   emit_op3(p, VP_OPCODE_MAD, tmp, 0, swizzle1(src,Y), mat[1], tmp);
580   emit_op3(p, VP_OPCODE_MAD, tmp, 0, swizzle1(src,Z), mat[2], tmp);
581   emit_op3(p, VP_OPCODE_MAD, dest, 0, swizzle1(src,W), mat[3], tmp);
582
583   if (dest.file != PROGRAM_TEMPORARY)
584      release_temp(p, tmp);
585}
586
587static void emit_matrix_transform_vec3( struct tnl_program *p,
588					struct ureg dest,
589					const struct ureg *mat,
590					struct ureg src)
591{
592   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_X, src, mat[0]);
593   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_Y, src, mat[1]);
594   emit_op2(p, VP_OPCODE_DP3, dest, WRITEMASK_Z, src, mat[2]);
595}
596
597
598static void emit_normalize_vec3( struct tnl_program *p,
599				 struct ureg dest,
600				 struct ureg src )
601{
602   struct ureg tmp = get_temp(p);
603   emit_op2(p, VP_OPCODE_DP3, tmp, 0, src, src);
604   emit_op1(p, VP_OPCODE_RSQ, tmp, 0, tmp);
605   emit_op2(p, VP_OPCODE_MUL, dest, 0, src, tmp);
606   release_temp(p, tmp);
607}
608
609static void emit_passthrough( struct tnl_program *p,
610			      GLuint input,
611			      GLuint output )
612{
613   struct ureg out = register_output(p, output);
614   emit_op1(p, VP_OPCODE_MOV, out, 0, register_input(p, input));
615}
616
617static struct ureg get_eye_position( struct tnl_program *p )
618{
619   if (is_undef(p->eye_position)) {
620      struct ureg pos = register_input( p, VERT_ATTRIB_POS );
621      struct ureg modelview[4];
622
623      p->eye_position = reserve_temp(p);
624
625      if (PREFER_DP4) {
626	 register_matrix_param6( p, STATE_MATRIX, STATE_MODELVIEW, 0, 0, 3,
627				 STATE_MATRIX, modelview );
628
629	 emit_matrix_transform_vec4(p, p->eye_position, modelview, pos);
630      }
631      else {
632	 register_matrix_param6( p, STATE_MATRIX, STATE_MODELVIEW, 0, 0, 3,
633				 STATE_MATRIX_TRANSPOSE, modelview );
634
635	 emit_transpose_matrix_transform_vec4(p, p->eye_position, modelview, pos);
636      }
637   }
638
639   return p->eye_position;
640}
641
642
643static struct ureg get_eye_position_normalized( struct tnl_program *p )
644{
645   if (is_undef(p->eye_position_normalized)) {
646      struct ureg eye = get_eye_position(p);
647      p->eye_position_normalized = reserve_temp(p);
648      emit_normalize_vec3(p, p->eye_position_normalized, eye);
649   }
650
651   return p->eye_position_normalized;
652}
653
654
655static struct ureg get_eye_normal( struct tnl_program *p )
656{
657   if (is_undef(p->eye_normal)) {
658      struct ureg normal = register_input(p, VERT_ATTRIB_NORMAL );
659      struct ureg mvinv[3];
660
661      register_matrix_param6( p, STATE_MATRIX, STATE_MODELVIEW, 0, 0, 2,
662			      STATE_MATRIX_INVTRANS, mvinv );
663
664      p->eye_normal = reserve_temp(p);
665
666      /* Transform to eye space:
667       */
668      emit_matrix_transform_vec3( p, p->eye_normal, mvinv, normal );
669
670      /* Normalize/Rescale:
671       */
672      if (p->state->normalize) {
673	 emit_normalize_vec3( p, p->eye_normal, p->eye_normal );
674      }
675      else if (p->state->rescale_normals) {
676	 struct ureg rescale = register_param2(p, STATE_INTERNAL,
677					       STATE_NORMAL_SCALE);
678
679	 emit_op2( p, VP_OPCODE_MUL, p->eye_normal, 0, normal,
680		   swizzle1(rescale, X));
681      }
682   }
683
684   return p->eye_normal;
685}
686
687
688
689static void build_hpos( struct tnl_program *p )
690{
691   struct ureg pos = register_input( p, VERT_ATTRIB_POS );
692   struct ureg hpos = register_output( p, VERT_RESULT_HPOS );
693   struct ureg mvp[4];
694
695   if (PREFER_DP4) {
696      register_matrix_param6( p, STATE_MATRIX, STATE_MVP, 0, 0, 3,
697			      STATE_MATRIX, mvp );
698      emit_matrix_transform_vec4( p, hpos, mvp, pos );
699   }
700   else {
701      register_matrix_param6( p, STATE_MATRIX, STATE_MVP, 0, 0, 3,
702			      STATE_MATRIX_TRANSPOSE, mvp );
703      emit_transpose_matrix_transform_vec4( p, hpos, mvp, pos );
704   }
705}
706
707
708static GLuint material_attrib( GLuint side, GLuint property )
709{
710   return ((property - STATE_AMBIENT) * 2 +
711	   side);
712}
713
714static void set_material_flags( struct tnl_program *p )
715{
716   p->color_materials = 0;
717   p->materials = 0;
718
719   if (p->state->light_color_material) {
720      p->materials =
721	 p->color_materials = p->state->light_color_material_mask;
722   }
723
724   p->materials |= p->state->light_material_mask;
725}
726
727
728static struct ureg get_material( struct tnl_program *p, GLuint side,
729				 GLuint property )
730{
731   GLuint attrib = material_attrib(side, property);
732
733   if (p->color_materials & (1<<attrib))
734      return register_input(p, VERT_ATTRIB_COLOR0);
735   else if (p->materials & (1<<attrib))
736      return register_input( p, attrib + _TNL_ATTRIB_MAT_FRONT_AMBIENT );
737   else
738      return register_param3( p, STATE_MATERIAL, side, property );
739}
740
741#define SCENE_COLOR_BITS(side) (( MAT_BIT_FRONT_EMISSION | \
742				   MAT_BIT_FRONT_AMBIENT | \
743				   MAT_BIT_FRONT_DIFFUSE) << (side))
744
745/* Either return a precalculated constant value or emit code to
746 * calculate these values dynamically in the case where material calls
747 * are present between begin/end pairs.
748 *
749 * Probably want to shift this to the program compilation phase - if
750 * we always emitted the calculation here, a smart compiler could
751 * detect that it was constant (given a certain set of inputs), and
752 * lift it out of the main loop.  That way the programs created here
753 * would be independent of the vertex_buffer details.
754 */
755static struct ureg get_scenecolor( struct tnl_program *p, GLuint side )
756{
757   if (p->materials & SCENE_COLOR_BITS(side)) {
758      struct ureg lm_ambient = register_param1(p, STATE_LIGHTMODEL_AMBIENT);
759      struct ureg material_emission = get_material(p, side, STATE_EMISSION);
760      struct ureg material_ambient = get_material(p, side, STATE_AMBIENT);
761      struct ureg material_diffuse = get_material(p, side, STATE_DIFFUSE);
762      struct ureg tmp = make_temp(p, material_diffuse);
763      emit_op3(p, VP_OPCODE_MAD, tmp,  WRITEMASK_XYZ, lm_ambient,
764	       material_ambient, material_emission);
765      return tmp;
766   }
767   else
768      return register_param2( p, STATE_LIGHTMODEL_SCENECOLOR, side );
769}
770
771
772static struct ureg get_lightprod( struct tnl_program *p, GLuint light,
773				  GLuint side, GLuint property )
774{
775   GLuint attrib = material_attrib(side, property);
776   if (p->materials & (1<<attrib)) {
777      struct ureg light_value =
778	 register_param3(p, STATE_LIGHT, light, property);
779      struct ureg material_value = get_material(p, side, property);
780      struct ureg tmp = get_temp(p);
781      emit_op2(p, VP_OPCODE_MUL, tmp,  0, light_value, material_value);
782      return tmp;
783   }
784   else
785      return register_param4(p, STATE_LIGHTPROD, light, side, property);
786}
787
788static struct ureg calculate_light_attenuation( struct tnl_program *p,
789						GLuint i,
790						struct ureg VPpli,
791						struct ureg dist )
792{
793   struct ureg attenuation = register_param3(p, STATE_LIGHT, i,
794					     STATE_ATTENUATION);
795   struct ureg att = get_temp(p);
796
797   /* Calculate spot attenuation:
798    */
799   if (!p->state->unit[i].light_spotcutoff_is_180) {
800      struct ureg spot_dir = register_param3(p, STATE_LIGHT, i,
801					     STATE_SPOT_DIRECTION);
802      struct ureg spot = get_temp(p);
803      struct ureg slt = get_temp(p);
804
805      emit_normalize_vec3( p, spot, spot_dir ); /* XXX: precompute! */
806      emit_op2(p, VP_OPCODE_DP3, spot, 0, negate(VPpli), spot);
807      emit_op2(p, VP_OPCODE_SLT, slt, 0, swizzle1(spot_dir,W), spot);
808      emit_op2(p, VP_OPCODE_POW, spot, 0, spot, swizzle1(attenuation, W));
809      emit_op2(p, VP_OPCODE_MUL, att, 0, slt, spot);
810
811      release_temp(p, spot);
812      release_temp(p, slt);
813   }
814
815   /* Calculate distance attenuation:
816    */
817   if (p->state->unit[i].light_attenuated) {
818
819      /* 1/d,d,d,1/d */
820      emit_op1(p, VP_OPCODE_RCP, dist, WRITEMASK_YZ, dist);
821      /* 1,d,d*d,1/d */
822      emit_op2(p, VP_OPCODE_MUL, dist, WRITEMASK_XZ, dist, swizzle1(dist,Y));
823      /* 1/dist-atten */
824      emit_op2(p, VP_OPCODE_DP3, dist, 0, attenuation, dist);
825
826      if (!p->state->unit[i].light_spotcutoff_is_180) {
827	 /* dist-atten */
828	 emit_op1(p, VP_OPCODE_RCP, dist, 0, dist);
829	 /* spot-atten * dist-atten */
830	 emit_op2(p, VP_OPCODE_MUL, att, 0, dist, att);
831      } else {
832	 /* dist-atten */
833	 emit_op1(p, VP_OPCODE_RCP, att, 0, dist);
834      }
835   }
836
837   return att;
838}
839
840
841
842
843
844/* Need to add some addtional parameters to allow lighting in object
845 * space - STATE_SPOT_DIRECTION and STATE_HALF implicitly assume eye
846 * space lighting.
847 */
848static void build_lighting( struct tnl_program *p )
849{
850   const GLboolean twoside = p->state->light_twoside;
851   const GLboolean separate = p->state->separate_specular;
852   GLuint nr_lights = 0, count = 0;
853   struct ureg normal = get_eye_normal(p);
854   struct ureg lit = get_temp(p);
855   struct ureg dots = get_temp(p);
856   struct ureg _col0 = undef, _col1 = undef;
857   struct ureg _bfc0 = undef, _bfc1 = undef;
858   GLuint i;
859
860   for (i = 0; i < MAX_LIGHTS; i++)
861      if (p->state->unit[i].light_enabled)
862	 nr_lights++;
863
864   set_material_flags(p);
865
866   {
867      struct ureg shininess = get_material(p, 0, STATE_SHININESS);
868      emit_op1(p, VP_OPCODE_MOV, dots,  WRITEMASK_W, swizzle1(shininess,X));
869      release_temp(p, shininess);
870
871      _col0 = make_temp(p, get_scenecolor(p, 0));
872      if (separate)
873	 _col1 = make_temp(p, get_identity_param(p));
874      else
875	 _col1 = _col0;
876
877   }
878
879   if (twoside) {
880      struct ureg shininess = get_material(p, 1, STATE_SHININESS);
881      emit_op1(p, VP_OPCODE_MOV, dots, WRITEMASK_Z,
882	       negate(swizzle1(shininess,X)));
883      release_temp(p, shininess);
884
885      _bfc0 = make_temp(p, get_scenecolor(p, 1));
886      if (separate)
887	 _bfc1 = make_temp(p, get_identity_param(p));
888      else
889	 _bfc1 = _bfc0;
890   }
891
892
893   /* If no lights, still need to emit the scenecolor.
894    */
895      {
896	 struct ureg res0 = register_output( p, VERT_RESULT_COL0 );
897	 emit_op1(p, VP_OPCODE_MOV, res0, 0, _col0);
898      }
899
900      if (separate) {
901	 struct ureg res1 = register_output( p, VERT_RESULT_COL1 );
902	 emit_op1(p, VP_OPCODE_MOV, res1, 0, _col1);
903      }
904
905      if (twoside) {
906	 struct ureg res0 = register_output( p, VERT_RESULT_BFC0 );
907	 emit_op1(p, VP_OPCODE_MOV, res0, 0, _bfc0);
908      }
909
910      if (twoside && separate) {
911	 struct ureg res1 = register_output( p, VERT_RESULT_BFC1 );
912	 emit_op1(p, VP_OPCODE_MOV, res1, 0, _bfc1);
913      }
914
915   if (nr_lights == 0) {
916      release_temps(p);
917      return;
918   }
919
920
921   for (i = 0; i < MAX_LIGHTS; i++) {
922      if (p->state->unit[i].light_enabled) {
923	 struct ureg half = undef;
924	 struct ureg att = undef, VPpli = undef;
925
926	 count++;
927
928	 if (p->state->unit[i].light_eyepos3_is_zero) {
929	    /* Can used precomputed constants in this case.
930	     * Attenuation never applies to infinite lights.
931	     */
932	    VPpli = register_param3(p, STATE_LIGHT, i,
933				    STATE_POSITION_NORMALIZED);
934	    half = register_param3(p, STATE_LIGHT, i, STATE_HALF);
935	 }
936	 else {
937	    struct ureg Ppli = register_param3(p, STATE_LIGHT, i,
938					       STATE_POSITION);
939	    struct ureg V = get_eye_position(p);
940	    struct ureg dist = get_temp(p);
941
942	    VPpli = get_temp(p);
943	    half = get_temp(p);
944
945	    /* Calulate VPpli vector
946	     */
947	    emit_op2(p, VP_OPCODE_SUB, VPpli, 0, Ppli, V);
948
949	    /* Normalize VPpli.  The dist value also used in
950	     * attenuation below.
951	     */
952	    emit_op2(p, VP_OPCODE_DP3, dist, 0, VPpli, VPpli);
953	    emit_op1(p, VP_OPCODE_RSQ, dist, 0, dist);
954	    emit_op2(p, VP_OPCODE_MUL, VPpli, 0, VPpli, dist);
955
956
957	    /* Calculate  attenuation:
958	     */
959	    if (!p->state->unit[i].light_spotcutoff_is_180 ||
960		p->state->unit[i].light_attenuated) {
961	       att = calculate_light_attenuation(p, i, VPpli, dist);
962	    }
963
964
965	    /* Calculate viewer direction, or use infinite viewer:
966	     */
967	    if (p->state->light_local_viewer) {
968	       struct ureg eye_hat = get_eye_position_normalized(p);
969	       emit_op2(p, VP_OPCODE_SUB, half, 0, VPpli, eye_hat);
970	    }
971	    else {
972	       struct ureg z_dir = swizzle(get_identity_param(p),X,Y,W,Z);
973	       emit_op2(p, VP_OPCODE_ADD, half, 0, VPpli, z_dir);
974	    }
975
976	    emit_normalize_vec3(p, half, half);
977
978	    release_temp(p, dist);
979	 }
980
981	 /* Calculate dot products:
982	  */
983	 emit_op2(p, VP_OPCODE_DP3, dots, WRITEMASK_X, normal, VPpli);
984	 emit_op2(p, VP_OPCODE_DP3, dots, WRITEMASK_Y, normal, half);
985
986
987	 /* Front face lighting:
988	  */
989	 {
990	    struct ureg ambient = get_lightprod(p, i, 0, STATE_AMBIENT);
991	    struct ureg diffuse = get_lightprod(p, i, 0, STATE_DIFFUSE);
992	    struct ureg specular = get_lightprod(p, i, 0, STATE_SPECULAR);
993	    struct ureg res0, res1;
994	    GLuint mask0, mask1;
995
996	    emit_op1(p, VP_OPCODE_LIT, lit, 0, dots);
997
998	    if (!is_undef(att))
999	       emit_op2(p, VP_OPCODE_MUL, lit, 0, lit, att);
1000
1001
1002	    if (count == nr_lights) {
1003	       if (separate) {
1004		  mask0 = WRITEMASK_XYZ;
1005		  mask1 = WRITEMASK_XYZ;
1006		  res0 = register_output( p, VERT_RESULT_COL0 );
1007		  res1 = register_output( p, VERT_RESULT_COL1 );
1008	       }
1009	       else {
1010		  mask0 = 0;
1011		  mask1 = WRITEMASK_XYZ;
1012		  res0 = _col0;
1013		  res1 = register_output( p, VERT_RESULT_COL0 );
1014	       }
1015	    } else {
1016	       mask0 = 0;
1017	       mask1 = 0;
1018	       res0 = _col0;
1019	       res1 = _col1;
1020	    }
1021
1022	    emit_op3(p, VP_OPCODE_MAD, _col0, 0, swizzle1(lit,X), ambient, _col0);
1023	    emit_op3(p, VP_OPCODE_MAD, res0, mask0, swizzle1(lit,Y), diffuse, _col0);
1024	    emit_op3(p, VP_OPCODE_MAD, res1, mask1, swizzle1(lit,Z), specular, _col1);
1025
1026	    release_temp(p, ambient);
1027	    release_temp(p, diffuse);
1028	    release_temp(p, specular);
1029	 }
1030
1031	 /* Back face lighting:
1032	  */
1033	 if (twoside) {
1034	    struct ureg ambient = get_lightprod(p, i, 1, STATE_AMBIENT);
1035	    struct ureg diffuse = get_lightprod(p, i, 1, STATE_DIFFUSE);
1036	    struct ureg specular = get_lightprod(p, i, 1, STATE_SPECULAR);
1037	    struct ureg res0, res1;
1038	    GLuint mask0, mask1;
1039
1040	    emit_op1(p, VP_OPCODE_LIT, lit, 0, negate(swizzle(dots,X,Y,W,Z)));
1041
1042	    if (!is_undef(att))
1043	       emit_op2(p, VP_OPCODE_MUL, lit, 0, lit, att);
1044
1045	    if (count == nr_lights) {
1046	       if (separate) {
1047		  mask0 = WRITEMASK_XYZ;
1048		  mask1 = WRITEMASK_XYZ;
1049		  res0 = register_output( p, VERT_RESULT_BFC0 );
1050		  res1 = register_output( p, VERT_RESULT_BFC1 );
1051	       }
1052	       else {
1053		  mask0 = 0;
1054		  mask1 = WRITEMASK_XYZ;
1055		  res0 = _bfc0;
1056		  res1 = register_output( p, VERT_RESULT_BFC0 );
1057	       }
1058	    } else {
1059	       res0 = _bfc0;
1060	       res1 = _bfc1;
1061	       mask0 = 0;
1062	       mask1 = 0;
1063	    }
1064
1065	    emit_op3(p, VP_OPCODE_MAD, _bfc0, 0, swizzle1(lit,X), ambient, _bfc0);
1066	    emit_op3(p, VP_OPCODE_MAD, res0, mask0, swizzle1(lit,Y), diffuse, _bfc0);
1067	    emit_op3(p, VP_OPCODE_MAD, res1, mask1, swizzle1(lit,Z), specular, _bfc1);
1068
1069	    release_temp(p, ambient);
1070	    release_temp(p, diffuse);
1071	    release_temp(p, specular);
1072	 }
1073
1074	 release_temp(p, half);
1075	 release_temp(p, VPpli);
1076	 release_temp(p, att);
1077      }
1078   }
1079
1080   release_temps( p );
1081}
1082
1083
1084static void build_fog( struct tnl_program *p )
1085{
1086   struct ureg fog = register_output(p, VERT_RESULT_FOGC);
1087   struct ureg input;
1088
1089   if (p->state->fog_source_is_depth) {
1090      input = swizzle1(get_eye_position(p), Z);
1091   }
1092   else {
1093      input = swizzle1(register_input(p, VERT_ATTRIB_FOG), X);
1094   }
1095
1096   if (p->state->tnl_do_vertex_fog) {
1097      struct ureg params = register_param1(p, STATE_FOG_PARAMS);
1098      struct ureg tmp = get_temp(p);
1099
1100      switch (p->state->fog_mode) {
1101      case FOG_LINEAR: {
1102	 struct ureg id = get_identity_param(p);
1103	 emit_op2(p, VP_OPCODE_SUB, tmp, 0, swizzle1(params,Z), input);
1104	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, swizzle1(params,W));
1105	 emit_op2(p, VP_OPCODE_MAX, tmp, 0, tmp, swizzle1(id,X)); /* saturate */
1106	 emit_op2(p, VP_OPCODE_MIN, fog, WRITEMASK_X, tmp, swizzle1(id,W));
1107	 break;
1108      }
1109      case FOG_EXP:
1110	 emit_op1(p, VP_OPCODE_ABS, tmp, 0, input);
1111	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, swizzle1(params,X));
1112	 emit_op2(p, VP_OPCODE_POW, fog, WRITEMASK_X,
1113		  register_const1f(p, M_E), negate(tmp));
1114	 break;
1115      case FOG_EXP2:
1116	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, input, swizzle1(params,X));
1117	 emit_op2(p, VP_OPCODE_MUL, tmp, 0, tmp, tmp);
1118	 emit_op2(p, VP_OPCODE_POW, fog, WRITEMASK_X,
1119		  register_const1f(p, M_E), negate(tmp));
1120	 break;
1121      }
1122
1123      release_temp(p, tmp);
1124   }
1125   else {
1126      /* results = incoming fog coords (compute fog per-fragment later)
1127       *
1128       * KW:  Is it really necessary to do anything in this case?
1129       */
1130      emit_op1(p, VP_OPCODE_MOV, fog, WRITEMASK_X, input);
1131   }
1132}
1133
1134static void build_reflect_texgen( struct tnl_program *p,
1135				  struct ureg dest,
1136				  GLuint writemask )
1137{
1138   struct ureg normal = get_eye_normal(p);
1139   struct ureg eye_hat = get_eye_position_normalized(p);
1140   struct ureg tmp = get_temp(p);
1141
1142   /* n.u */
1143   emit_op2(p, VP_OPCODE_DP3, tmp, 0, normal, eye_hat);
1144   /* 2n.u */
1145   emit_op2(p, VP_OPCODE_ADD, tmp, 0, tmp, tmp);
1146   /* (-2n.u)n + u */
1147   emit_op3(p, VP_OPCODE_MAD, dest, writemask, negate(tmp), normal, eye_hat);
1148}
1149
1150static void build_sphere_texgen( struct tnl_program *p,
1151				 struct ureg dest,
1152				 GLuint writemask )
1153{
1154   struct ureg normal = get_eye_normal(p);
1155   struct ureg eye_hat = get_eye_position_normalized(p);
1156   struct ureg tmp = get_temp(p);
1157   struct ureg half = register_scalar_const(p, .5);
1158   struct ureg r = get_temp(p);
1159   struct ureg inv_m = get_temp(p);
1160   struct ureg id = get_identity_param(p);
1161
1162   /* Could share the above calculations, but it would be
1163    * a fairly odd state for someone to set (both sphere and
1164    * reflection active for different texture coordinate
1165    * components.  Of course - if two texture units enable
1166    * reflect and/or sphere, things start to tilt in favour
1167    * of seperating this out:
1168    */
1169
1170   /* n.u */
1171   emit_op2(p, VP_OPCODE_DP3, tmp, 0, normal, eye_hat);
1172   /* 2n.u */
1173   emit_op2(p, VP_OPCODE_ADD, tmp, 0, tmp, tmp);
1174   /* (-2n.u)n + u */
1175   emit_op3(p, VP_OPCODE_MAD, r, 0, negate(tmp), normal, eye_hat);
1176   /* r + 0,0,1 */
1177   emit_op2(p, VP_OPCODE_ADD, tmp, 0, r, swizzle(id,X,Y,W,Z));
1178   /* rx^2 + ry^2 + (rz+1)^2 */
1179   emit_op2(p, VP_OPCODE_DP3, tmp, 0, tmp, tmp);
1180   /* 2/m */
1181   emit_op1(p, VP_OPCODE_RSQ, tmp, 0, tmp);
1182   /* 1/m */
1183   emit_op2(p, VP_OPCODE_MUL, inv_m, 0, tmp, half);
1184   /* r/m + 1/2 */
1185   emit_op3(p, VP_OPCODE_MAD, dest, writemask, r, inv_m, half);
1186
1187   release_temp(p, tmp);
1188   release_temp(p, r);
1189   release_temp(p, inv_m);
1190}
1191
1192
1193static void build_texture_transform( struct tnl_program *p )
1194{
1195   GLuint i, j;
1196
1197   for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
1198      GLuint texmat_enabled = p->state->unit[i].texmat_enabled;
1199
1200      if (p->state->unit[i].texgen_enabled || texmat_enabled) {
1201	 struct ureg out = register_output(p, VERT_RESULT_TEX0 + i);
1202	 struct ureg out_texgen = undef;
1203
1204	 if (p->state->unit[i].texgen_enabled) {
1205	    GLuint copy_mask = 0;
1206	    GLuint sphere_mask = 0;
1207	    GLuint reflect_mask = 0;
1208	    GLuint normal_mask = 0;
1209	    GLuint modes[4];
1210
1211	    if (texmat_enabled)
1212	       out_texgen = get_temp(p);
1213	    else
1214	       out_texgen = out;
1215
1216	    modes[0] = p->state->unit[i].texgen_mode0;
1217	    modes[1] = p->state->unit[i].texgen_mode1;
1218	    modes[2] = p->state->unit[i].texgen_mode2;
1219	    modes[3] = p->state->unit[i].texgen_mode3;
1220
1221	    for (j = 0; j < 4; j++) {
1222	       switch (modes[j]) {
1223	       case TXG_OBJ_LINEAR: {
1224		  struct ureg obj = register_input(p, VERT_ATTRIB_POS);
1225		  struct ureg plane =
1226		     register_param3(p, STATE_TEXGEN, i,
1227				     STATE_TEXGEN_OBJECT_S + j);
1228
1229		  emit_op2(p, VP_OPCODE_DP4, out_texgen, WRITEMASK_X << j,
1230			   obj, plane );
1231		  break;
1232	       }
1233	       case TXG_EYE_LINEAR: {
1234		  struct ureg eye = get_eye_position(p);
1235		  struct ureg plane =
1236		     register_param3(p, STATE_TEXGEN, i,
1237				     STATE_TEXGEN_EYE_S + j);
1238
1239		  emit_op2(p, VP_OPCODE_DP4, out_texgen, WRITEMASK_X << j,
1240			   eye, plane );
1241		  break;
1242	       }
1243	       case TXG_SPHERE_MAP:
1244		  sphere_mask |= WRITEMASK_X << j;
1245		  break;
1246	       case TXG_REFLECTION_MAP:
1247		  reflect_mask |= WRITEMASK_X << j;
1248		  break;
1249	       case TXG_NORMAL_MAP:
1250		  normal_mask |= WRITEMASK_X << j;
1251		  break;
1252	       case TXG_NONE:
1253		  copy_mask |= WRITEMASK_X << j;
1254	       }
1255
1256	    }
1257
1258
1259	    if (sphere_mask) {
1260	       build_sphere_texgen(p, out_texgen, sphere_mask);
1261	    }
1262
1263	    if (reflect_mask) {
1264	       build_reflect_texgen(p, out_texgen, reflect_mask);
1265	    }
1266
1267	    if (normal_mask) {
1268	       struct ureg normal = get_eye_normal(p);
1269	       emit_op1(p, VP_OPCODE_MOV, out_texgen, normal_mask, normal );
1270	    }
1271
1272	    if (copy_mask) {
1273	       struct ureg in = register_input(p, VERT_ATTRIB_TEX0+i);
1274	       emit_op1(p, VP_OPCODE_MOV, out_texgen, copy_mask, in );
1275	    }
1276	 }
1277
1278	 if (texmat_enabled) {
1279	    struct ureg texmat[4];
1280	    struct ureg in = (!is_undef(out_texgen) ?
1281			      out_texgen :
1282			      register_input(p, VERT_ATTRIB_TEX0+i));
1283	    if (PREFER_DP4) {
1284	       register_matrix_param6( p, STATE_MATRIX, STATE_TEXTURE, i,
1285				       0, 3, STATE_MATRIX, texmat );
1286	       emit_matrix_transform_vec4( p, out, texmat, in );
1287	    }
1288	    else {
1289	       register_matrix_param6( p, STATE_MATRIX, STATE_TEXTURE, i,
1290				       0, 3, STATE_MATRIX_TRANSPOSE, texmat );
1291	       emit_transpose_matrix_transform_vec4( p, out, texmat, in );
1292	    }
1293	 }
1294
1295	 release_temps(p);
1296      }
1297      else if (p->state->unit[i].texunit_really_enabled) {
1298	 /* KW: _ReallyEnabled isn't sufficient?  Need to know whether
1299	  * this texture unit is referenced by the fragment shader.
1300	  */
1301	 emit_passthrough(p, VERT_ATTRIB_TEX0+i, VERT_RESULT_TEX0+i);
1302      }
1303   }
1304}
1305
1306
1307/* Seems like it could be tighter:
1308 */
1309static void build_pointsize( struct tnl_program *p )
1310{
1311   struct ureg eye = get_eye_position(p);
1312   struct ureg state_size = register_param1(p, STATE_POINT_SIZE);
1313   struct ureg state_attenuation = register_param1(p, STATE_POINT_ATTENUATION);
1314   struct ureg out = register_output(p, VERT_RESULT_PSIZ);
1315   struct ureg ut = get_temp(p);
1316
1317   /* 1, -Z, Z * Z, 1 */
1318   emit_op1(p, VP_OPCODE_MOV, ut, 0, swizzle1(get_identity_param(p), W));
1319   emit_op2(p, VP_OPCODE_MUL, ut, WRITEMASK_YZ, ut, negate(swizzle1(eye, Z)));
1320   emit_op2(p, VP_OPCODE_MUL, ut, WRITEMASK_Z, ut, negate(swizzle1(eye, Z)));
1321
1322
1323   /* p1 +  p2 * dist + p3 * dist * dist, 0 */
1324   emit_op2(p, VP_OPCODE_DP3, ut, 0, ut, state_attenuation);
1325
1326   /* 1 / factor */
1327   emit_op1(p, VP_OPCODE_RCP, ut, 0, ut );
1328
1329   /* out = pointSize / factor */
1330   emit_op2(p, VP_OPCODE_MUL, out, WRITEMASK_X, ut, state_size);
1331
1332   release_temp(p, ut);
1333}
1334
1335static void build_tnl_program( struct tnl_program *p )
1336{   /* Emit the program, starting with modelviewproject:
1337    */
1338   build_hpos(p);
1339
1340   /* Lighting calculations:
1341    */
1342   if (p->state->light_global_enabled)
1343      build_lighting(p);
1344   else
1345      emit_passthrough(p, VERT_ATTRIB_COLOR0, VERT_RESULT_COL0);
1346
1347   if (p->state->fog_enabled)
1348      build_fog(p);
1349
1350   if (p->state->texture_enabled_global)
1351      build_texture_transform(p);
1352
1353   if (p->state->point_attenuated)
1354      build_pointsize(p);
1355
1356   /* Finish up:
1357    */
1358   emit_op1(p, VP_OPCODE_END, undef, 0, undef);
1359
1360   /* Disassemble:
1361    */
1362   if (DISASSEM) {
1363      _mesa_printf ("\n");
1364   }
1365}
1366
1367
1368void create_new_program( const struct state_key *key,
1369			 struct vertex_program *program,
1370			 GLuint max_temps)
1371{
1372   struct tnl_program p;
1373
1374   _mesa_memset(&p, 0, sizeof(p));
1375   p.state = key;
1376   p.program = program;
1377   p.eye_position = undef;
1378   p.eye_position_normalized = undef;
1379   p.eye_normal = undef;
1380   p.identity = undef;
1381   p.temp_in_use = 0;
1382
1383   if (max_temps >= sizeof(int) * 8)
1384      p.temp_reserved = 0;
1385   else
1386      p.temp_reserved = ~((1<<max_temps)-1);
1387
1388   p.program->Instructions = MALLOC(sizeof(struct vp_instruction) * MAX_INSN);
1389   p.program->Base.String = 0;
1390   p.program->Base.NumInstructions =
1391   p.program->Base.NumTemporaries =
1392   p.program->Base.NumParameters =
1393   p.program->Base.NumAttributes = p.program->Base.NumAddressRegs = 0;
1394   p.program->Parameters = _mesa_new_parameter_list();
1395   p.program->InputsRead = 0;
1396   p.program->OutputsWritten = 0;
1397
1398   build_tnl_program( &p );
1399}
1400
1401static void *search_cache( struct tnl_cache *cache,
1402			   GLuint hash,
1403			   const void *key,
1404			   GLuint keysize)
1405{
1406   struct tnl_cache *c;
1407
1408   for (c = cache; c; c = c->next) {
1409      if (c->hash == hash && memcmp(c->key, key, keysize) == 0)
1410	 return c->data;
1411   }
1412
1413   return NULL;
1414}
1415
1416static void cache_item( struct tnl_cache **cache,
1417			GLuint hash,
1418			void *key,
1419			void *data )
1420{
1421   struct tnl_cache *c = MALLOC(sizeof(*c));
1422   c->hash = hash;
1423   c->key = key;
1424   c->data = data;
1425   c->next = *cache;
1426   *cache = c;
1427}
1428
1429static GLuint hash_key( struct state_key *key )
1430{
1431   GLuint *ikey = (GLuint *)key;
1432   GLuint hash = 0, i;
1433
1434   /* I'm sure this can be improved on, but speed is important:
1435    */
1436   for (i = 0; i < sizeof(*key)/sizeof(GLuint); i++)
1437      hash ^= ikey[i];
1438
1439   return hash;
1440}
1441
1442void _tnl_UpdateFixedFunctionProgram( GLcontext *ctx )
1443{
1444   TNLcontext *tnl = TNL_CONTEXT(ctx);
1445   struct state_key *key;
1446   GLuint hash;
1447
1448   if (ctx->VertexProgram._Enabled)
1449      return;
1450
1451   /* Grab all the relevent state and put it in a single structure:
1452    */
1453   key = make_state_key(ctx);
1454   hash = hash_key(key);
1455
1456   /* Look for an already-prepared program for this state:
1457    */
1458   ctx->_TnlProgram = (struct vertex_program *)
1459      search_cache( tnl->vp_cache, hash, key, sizeof(*key) );
1460
1461   /* OK, we'll have to build a new one:
1462    */
1463   if (!ctx->_TnlProgram) {
1464      if (0)
1465	 _mesa_printf("Build new TNL program\n");
1466
1467      ctx->_TnlProgram = (struct vertex_program *)
1468	 ctx->Driver.NewProgram(ctx, GL_VERTEX_PROGRAM_ARB, 0);
1469
1470      create_new_program( key, ctx->_TnlProgram,
1471			  ctx->Const.MaxVertexProgramTemps );
1472
1473      cache_item(&tnl->vp_cache, hash, key, ctx->_TnlProgram );
1474   }
1475   else {
1476      if (0)
1477	 _mesa_printf("Found existing TNL program for key %x\n", hash);
1478   }
1479
1480   /* Need a BindProgram callback for the driver?
1481    */
1482}
1483
1484
1485void _tnl_ProgramCacheDestroy( GLcontext *ctx )
1486{
1487   TNLcontext *tnl = TNL_CONTEXT(ctx);
1488   struct tnl_cache *a, *tmp;
1489
1490   for (a = tnl->vp_cache ; a; a = tmp) {
1491      tmp = a->next;
1492      FREE(a->key);
1493      FREE(a->data);
1494      FREE(a);
1495   }
1496}
1497