From 2702c90d7a39fca2a3319c5e915fd290cb31fc70 Mon Sep 17 00:00:00 2001 From: RadosÅ‚aw Kujawa Date: Fri, 17 Jul 2026 14:54:32 +0200 Subject: Initial import. --- src/mesa/shader/arbfragparse.c | 246 +++ src/mesa/shader/arbfragparse.h | 39 + src/mesa/shader/arbprogparse.c | 3988 ++++++++++++++++++++++++++++++++++++++ src/mesa/shader/arbprogparse.h | 74 + src/mesa/shader/arbprogram.c | 721 +++++++ src/mesa/shader/arbprogram.h | 128 ++ src/mesa/shader/arbprogram_syn.h | 1344 +++++++++++++ src/mesa/shader/arbvertparse.c | 234 +++ src/mesa/shader/arbvertparse.h | 33 + src/mesa/shader/descrip.mms | 69 + src/mesa/shader/grammar.c | 2802 ++++++++++++++++++++++++++ src/mesa/shader/grammar.h | 92 + src/mesa/shader/grammar_mesa.c | 87 + src/mesa/shader/grammar_mesa.h | 43 + src/mesa/shader/grammar_syn.h | 226 +++ src/mesa/shader/nvfragparse.c | 1767 +++++++++++++++++ src/mesa/shader/nvfragparse.h | 52 + src/mesa/shader/nvfragprog.h | 164 ++ src/mesa/shader/nvprogram.c | 869 +++++++++ src/mesa/shader/nvprogram.h | 119 ++ src/mesa/shader/nvvertexec.c | 837 ++++++++ src/mesa/shader/nvvertexec.h | 43 + src/mesa/shader/nvvertparse.c | 1498 ++++++++++++++ src/mesa/shader/nvvertparse.h | 50 + src/mesa/shader/nvvertprog.h | 107 + src/mesa/shader/program.c | 1312 +++++++++++++ src/mesa/shader/program.h | 267 +++ src/mesa/shader/shader.dsp | 197 ++ 28 files changed, 17408 insertions(+) create mode 100644 src/mesa/shader/arbfragparse.c create mode 100644 src/mesa/shader/arbfragparse.h create mode 100644 src/mesa/shader/arbprogparse.c create mode 100644 src/mesa/shader/arbprogparse.h create mode 100644 src/mesa/shader/arbprogram.c create mode 100644 src/mesa/shader/arbprogram.h create mode 100644 src/mesa/shader/arbprogram_syn.h create mode 100644 src/mesa/shader/arbvertparse.c create mode 100644 src/mesa/shader/arbvertparse.h create mode 100644 src/mesa/shader/descrip.mms create mode 100644 src/mesa/shader/grammar.c create mode 100644 src/mesa/shader/grammar.h create mode 100644 src/mesa/shader/grammar_mesa.c create mode 100644 src/mesa/shader/grammar_mesa.h create mode 100644 src/mesa/shader/grammar_syn.h create mode 100644 src/mesa/shader/nvfragparse.c create mode 100644 src/mesa/shader/nvfragparse.h create mode 100644 src/mesa/shader/nvfragprog.h create mode 100644 src/mesa/shader/nvprogram.c create mode 100644 src/mesa/shader/nvprogram.h create mode 100644 src/mesa/shader/nvvertexec.c create mode 100644 src/mesa/shader/nvvertexec.h create mode 100644 src/mesa/shader/nvvertparse.c create mode 100644 src/mesa/shader/nvvertparse.h create mode 100644 src/mesa/shader/nvvertprog.h create mode 100644 src/mesa/shader/program.c create mode 100644 src/mesa/shader/program.h create mode 100644 src/mesa/shader/shader.dsp (limited to 'src/mesa/shader') diff --git a/src/mesa/shader/arbfragparse.c b/src/mesa/shader/arbfragparse.c new file mode 100644 index 0000000..7154859 --- /dev/null +++ b/src/mesa/shader/arbfragparse.c @@ -0,0 +1,246 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define DEBUG_FP 0 + +/** + * \file arbfragparse.c + * ARB_fragment_program parser. + * \author Karl Rasche + */ + +#include "glheader.h" +#include "context.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "arbprogparse.h" +#include "arbfragparse.h" + +#if DEBUG_FP +void +_mesa_debug_fp_inst(GLint num, struct fp_instruction *fp) +{ + GLint a; + + fprintf(stderr, "PROGRAM_OUTPUT: 0x%x\n", PROGRAM_OUTPUT); + fprintf(stderr, "PROGRAM_INPUT: 0x%x\n", PROGRAM_INPUT); + fprintf(stderr, "PROGRAM_TEMPORARY: 0x%x\n", PROGRAM_TEMPORARY); + + for (a=0; aInstructions = (struct fp_instruction *) _mesa_malloc ( + sizeof(struct fp_instruction) ); + program->Instructions[0].Opcode = FP_OPCODE_END; + return; + } + + /* copy the relvant contents of the arb_program struct into the + * fragment_program struct + */ + program->Base.String = ap.Base.String; + program->Base.NumInstructions = ap.Base.NumInstructions; + program->Base.NumTemporaries = ap.Base.NumTemporaries; + program->Base.NumParameters = ap.Base.NumParameters; + program->Base.NumAttributes = ap.Base.NumAttributes; + program->Base.NumAddressRegs = ap.Base.NumAddressRegs; + + program->InputsRead = ap.InputsRead; + program->OutputsWritten = ap.OutputsWritten; + for (a=0; aTexturesUsed[a] = ap.TexturesUsed[a]; + program->NumAluInstructions = ap.NumAluInstructions; + program->NumTexInstructions = ap.NumTexInstructions; + program->NumTexIndirections = ap.NumTexIndirections; + program->Parameters = ap.Parameters; + program->FogOption = ap.FogOption; + + /* XXX: Eh.. we parsed something that wasn't a fragment program. doh! */ + /* this wont happen any more */ +/* + if (ap.Base.Target != GL_FRAGMENT_PROGRAM_ARB) + { + program->Instructions = (struct fp_instruction *) _mesa_malloc ( + sizeof(struct fp_instruction) ); + program->Instructions[0].Opcode = FP_OPCODE_END; + + _mesa_error (ctx, GL_INVALID_OPERATION, "Parsed a non-fragment program as a fragment program"); + return; + } +*/ + +#if DEBUG_FP + _mesa_debug_fp_inst(ap.Base.NumInstructions, ap.FPInstructions); +#endif + + program->Instructions = ap.FPInstructions; +} diff --git a/src/mesa/shader/arbfragparse.h b/src/mesa/shader/arbfragparse.h new file mode 100644 index 0000000..0d3e69f --- /dev/null +++ b/src/mesa/shader/arbfragparse.h @@ -0,0 +1,39 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ARBFRAGPARSE_H +#define ARBFRAGPARSE_H + +#include "mtypes.h" + +extern void +_mesa_parse_arb_fragment_program(GLcontext * ctx, GLenum target, + const GLubyte * str, GLsizei len, + struct fragment_program *program); + +extern void +_mesa_debug_fp_inst(GLint num, struct fp_instruction *fp); + + +#endif diff --git a/src/mesa/shader/arbprogparse.c b/src/mesa/shader/arbprogparse.c new file mode 100644 index 0000000..dd0a876 --- /dev/null +++ b/src/mesa/shader/arbprogparse.c @@ -0,0 +1,3988 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define DEBUG_PARSING 0 + +/** + * \file arbprogparse.c + * ARB_*_program parser core + * \author Karl Rasche + */ + +#include "mtypes.h" +#include "glheader.h" +#include "context.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "program.h" +#include "nvvertprog.h" +#include "nvfragprog.h" +#include "arbprogparse.h" +#include "grammar_mesa.h" + +#ifndef __extension__ +#if !defined(__GNUC__) || (__GNUC__ < 2) || \ + ((__GNUC__ == 2) && (__GNUC_MINOR__ <= 7)) +# define __extension__ +#endif +#endif + +/* TODO: + * Fragment Program Stuff: + * ----------------------------------------------------- + * + * - things from Michal's email + * + overflow on atoi + * + not-overflowing floats (don't use parse_integer..) + * + can remove range checking in arbparse.c + * + * - check all limits of number of various variables + * + parameters + * + * - test! test! test! + * + * Vertex Program Stuff: + * ----------------------------------------------------- + * - Optimize param array usage and count limits correctly, see spec, + * section 2.14.3.7 + * + Record if an array is reference absolutly or relatively (or both) + * + For absolute arrays, store a bitmap of accesses + * + For single parameters, store an access flag + * + After parsing, make a parameter cleanup and merging pass, where + * relative arrays are layed out first, followed by abs arrays, and + * finally single state. + * + Remap offsets for param src and dst registers + * + Now we can properly count parameter usage + * + * - Multiple state binding errors in param arrays (see spec, just before + * section 2.14.3.3) + * - grep for XXX + * + * Mesa Stuff + * ----------------------------------------------------- + * - User clipping planes vs. PositionInvariant + * - Is it sufficient to just multiply by the mvp to transform in the + * PositionInvariant case? Or do we need something more involved? + * + * - vp_src swizzle is GLubyte, fp_src swizzle is GLuint + * - fetch state listed in program_parameters list + * + WTF should this go??? + * + currently in nvvertexec.c and s_nvfragprog.c + * + * - allow for multiple address registers (and fetch address regs properly) + * + * Cosmetic Stuff + * ----------------------------------------------------- + * - remove any leftover unused grammer.c stuff (dict_ ?) + * - fix grammer.c error handling so its not static + * - #ifdef around stuff pertaining to extentions + * + * Outstanding Questions: + * ----------------------------------------------------- + * - ARB_matrix_palette / ARB_vertex_blend -- not supported + * what gets hacked off because of this: + * + VERTEX_ATTRIB_MATRIXINDEX + * + VERTEX_ATTRIB_WEIGHT + * + MATRIX_MODELVIEW + * + MATRIX_PALETTE + * + * - When can we fetch env/local params from their own register files, and + * when to we have to fetch them into the main state register file? + * (think arrays) + * + * Grammar Changes: + * ----------------------------------------------------- + */ + +/* Changes since moving the file to shader directory + +2004-III-4 ------------------------------------------------------------ +- added #include "grammar_mesa.h" +- removed grammar specific code part (it resides now in grammar.c) +- added GL_ARB_fragment_program_shadow tokens +- modified #include "arbparse_syn.h" +- major changes inside _mesa_parse_arb_program() +- check the program string for '\0' characters +- copy the program string to a one-byte-longer location to have + it null-terminated +- position invariance test (not writing to result.position) moved + to syntax part +*/ + +typedef GLubyte *production; + +/** + * This is the text describing the rules to parse the grammar + */ +__extension__ static char arb_grammar_text[] = +#include "arbprogram_syn.h" +; + +/** + * These should match up with the values defined in arbprogram.syn + */ + +/* + Changes: + - changed and merged V_* and F_* opcode values to OP_*. + - added GL_ARB_fragment_program_shadow specific tokens (michal) +*/ +#define REVISION 0x07 + +/* program type */ +#define FRAGMENT_PROGRAM 0x01 +#define VERTEX_PROGRAM 0x02 + +/* program section */ +#define OPTION 0x01 +#define INSTRUCTION 0x02 +#define DECLARATION 0x03 +#define END 0x04 + +/* GL_ARB_fragment_program option flags */ +#define ARB_PRECISION_HINT_FASTEST 0x01 +#define ARB_PRECISION_HINT_NICEST 0x02 +#define ARB_FOG_EXP 0x04 +#define ARB_FOG_EXP2 0x08 +#define ARB_FOG_LINEAR 0x10 + +/* GL_ARB_vertex_program option flags */ +#define ARB_POSITION_INVARIANT 0x20 + +/* GL_ARB_fragment_program_shadow option flags */ +#define ARB_FRAGMENT_PROGRAM_SHADOW 0x40 + +/* GL_ARB_fragment_program instruction class */ +#define OP_ALU_INST 0x00 +#define OP_TEX_INST 0x01 + +/* GL_ARB_vertex_program instruction class */ +/* OP_ALU_INST */ + +/* GL_ARB_fragment_program instruction type */ +#define OP_ALU_VECTOR 0x00 +#define OP_ALU_SCALAR 0x01 +#define OP_ALU_BINSC 0x02 +#define OP_ALU_BIN 0x03 +#define OP_ALU_TRI 0x04 +#define OP_ALU_SWZ 0x05 +#define OP_TEX_SAMPLE 0x06 +#define OP_TEX_KIL 0x07 + +/* GL_ARB_vertex_program instruction type */ +#define OP_ALU_ARL 0x08 +/* OP_ALU_VECTOR */ +/* OP_ALU_SCALAR */ +/* OP_ALU_BINSC */ +/* OP_ALU_BIN */ +/* OP_ALU_TRI */ +/* OP_ALU_SWZ */ + +/* GL_ARB_fragment_program instruction code */ +#define OP_ABS 0x00 +#define OP_ABS_SAT 0x1B +#define OP_FLR 0x09 +#define OP_FLR_SAT 0x26 +#define OP_FRC 0x0A +#define OP_FRC_SAT 0x27 +#define OP_LIT 0x0C +#define OP_LIT_SAT 0x2A +#define OP_MOV 0x11 +#define OP_MOV_SAT 0x30 +#define OP_COS 0x1F +#define OP_COS_SAT 0x20 +#define OP_EX2 0x07 +#define OP_EX2_SAT 0x25 +#define OP_LG2 0x0B +#define OP_LG2_SAT 0x29 +#define OP_RCP 0x14 +#define OP_RCP_SAT 0x33 +#define OP_RSQ 0x15 +#define OP_RSQ_SAT 0x34 +#define OP_SIN 0x38 +#define OP_SIN_SAT 0x39 +#define OP_SCS 0x35 +#define OP_SCS_SAT 0x36 +#define OP_POW 0x13 +#define OP_POW_SAT 0x32 +#define OP_ADD 0x01 +#define OP_ADD_SAT 0x1C +#define OP_DP3 0x03 +#define OP_DP3_SAT 0x21 +#define OP_DP4 0x04 +#define OP_DP4_SAT 0x22 +#define OP_DPH 0x05 +#define OP_DPH_SAT 0x23 +#define OP_DST 0x06 +#define OP_DST_SAT 0x24 +#define OP_MAX 0x0F +#define OP_MAX_SAT 0x2E +#define OP_MIN 0x10 +#define OP_MIN_SAT 0x2F +#define OP_MUL 0x12 +#define OP_MUL_SAT 0x31 +#define OP_SGE 0x16 +#define OP_SGE_SAT 0x37 +#define OP_SLT 0x17 +#define OP_SLT_SAT 0x3A +#define OP_SUB 0x18 +#define OP_SUB_SAT 0x3B +#define OP_XPD 0x1A +#define OP_XPD_SAT 0x43 +#define OP_CMP 0x1D +#define OP_CMP_SAT 0x1E +#define OP_LRP 0x2B +#define OP_LRP_SAT 0x2C +#define OP_MAD 0x0E +#define OP_MAD_SAT 0x2D +#define OP_SWZ 0x19 +#define OP_SWZ_SAT 0x3C +#define OP_TEX 0x3D +#define OP_TEX_SAT 0x3E +#define OP_TXB 0x3F +#define OP_TXB_SAT 0x40 +#define OP_TXP 0x41 +#define OP_TXP_SAT 0x42 +#define OP_KIL 0x28 + +/* GL_ARB_vertex_program instruction code */ +#define OP_ARL 0x02 +/* OP_ABS */ +/* OP_FLR */ +/* OP_FRC */ +/* OP_LIT */ +/* OP_MOV */ +/* OP_EX2 */ +#define OP_EXP 0x08 +/* OP_LG2 */ +#define OP_LOG 0x0D +/* OP_RCP */ +/* OP_RSQ */ +/* OP_POW */ +/* OP_ADD */ +/* OP_DP3 */ +/* OP_DP4 */ +/* OP_DPH */ +/* OP_DST */ +/* OP_MAX */ +/* OP_MIN */ +/* OP_MUL */ +/* OP_SGE */ +/* OP_SLT */ +/* OP_SUB */ +/* OP_XPD */ +/* OP_MAD */ +/* OP_SWZ */ + +/* fragment attribute binding */ +#define FRAGMENT_ATTRIB_COLOR 0x01 +#define FRAGMENT_ATTRIB_TEXCOORD 0x02 +#define FRAGMENT_ATTRIB_FOGCOORD 0x03 +#define FRAGMENT_ATTRIB_POSITION 0x04 + +/* vertex attribute binding */ +#define VERTEX_ATTRIB_POSITION 0x01 +#define VERTEX_ATTRIB_WEIGHT 0x02 +#define VERTEX_ATTRIB_NORMAL 0x03 +#define VERTEX_ATTRIB_COLOR 0x04 +#define VERTEX_ATTRIB_FOGCOORD 0x05 +#define VERTEX_ATTRIB_TEXCOORD 0x06 +#define VERTEX_ATTRIB_MATRIXINDEX 0x07 +#define VERTEX_ATTRIB_GENERIC 0x08 + +/* fragment result binding */ +#define FRAGMENT_RESULT_COLOR 0x01 +#define FRAGMENT_RESULT_DEPTH 0x02 + +/* vertex result binding */ +#define VERTEX_RESULT_POSITION 0x01 +#define VERTEX_RESULT_COLOR 0x02 +#define VERTEX_RESULT_FOGCOORD 0x03 +#define VERTEX_RESULT_POINTSIZE 0x04 +#define VERTEX_RESULT_TEXCOORD 0x05 + +/* texture target */ +#define TEXTARGET_1D 0x01 +#define TEXTARGET_2D 0x02 +#define TEXTARGET_3D 0x03 +#define TEXTARGET_RECT 0x04 +#define TEXTARGET_CUBE 0x05 +/* GL_ARB_fragment_program_shadow */ +#define TEXTARGET_SHADOW1D 0x06 +#define TEXTARGET_SHADOW2D 0x07 +#define TEXTARGET_SHADOWRECT 0x08 + +/* face type */ +#define FACE_FRONT 0x00 +#define FACE_BACK 0x01 + +/* color type */ +#define COLOR_PRIMARY 0x00 +#define COLOR_SECONDARY 0x01 + +/* component */ +#define COMPONENT_X 0x00 +#define COMPONENT_Y 0x01 +#define COMPONENT_Z 0x02 +#define COMPONENT_W 0x03 +#define COMPONENT_0 0x04 +#define COMPONENT_1 0x05 + +/* array index type */ +#define ARRAY_INDEX_ABSOLUTE 0x00 +#define ARRAY_INDEX_RELATIVE 0x01 + +/* matrix name */ +#define MATRIX_MODELVIEW 0x01 +#define MATRIX_PROJECTION 0x02 +#define MATRIX_MVP 0x03 +#define MATRIX_TEXTURE 0x04 +#define MATRIX_PALETTE 0x05 +#define MATRIX_PROGRAM 0x06 + +/* matrix modifier */ +#define MATRIX_MODIFIER_IDENTITY 0x00 +#define MATRIX_MODIFIER_INVERSE 0x01 +#define MATRIX_MODIFIER_TRANSPOSE 0x02 +#define MATRIX_MODIFIER_INVTRANS 0x03 + +/* constant type */ +#define CONSTANT_SCALAR 0x01 +#define CONSTANT_VECTOR 0x02 + +/* program param type */ +#define PROGRAM_PARAM_ENV 0x01 +#define PROGRAM_PARAM_LOCAL 0x02 + +/* register type */ +#define REGISTER_ATTRIB 0x01 +#define REGISTER_PARAM 0x02 +#define REGISTER_RESULT 0x03 +#define REGISTER_ESTABLISHED_NAME 0x04 + +/* param binding */ +#define PARAM_NULL 0x00 +#define PARAM_ARRAY_ELEMENT 0x01 +#define PARAM_STATE_ELEMENT 0x02 +#define PARAM_PROGRAM_ELEMENT 0x03 +#define PARAM_PROGRAM_ELEMENTS 0x04 +#define PARAM_CONSTANT 0x05 + +/* param state property */ +#define STATE_MATERIAL_PARSER 0x01 +#define STATE_LIGHT_PARSER 0x02 +#define STATE_LIGHT_MODEL 0x03 +#define STATE_LIGHT_PROD 0x04 +#define STATE_FOG 0x05 +#define STATE_MATRIX_ROWS 0x06 +/* GL_ARB_fragment_program */ +#define STATE_TEX_ENV 0x07 +#define STATE_DEPTH 0x08 +/* GL_ARB_vertex_program */ +#define STATE_TEX_GEN 0x09 +#define STATE_CLIP_PLANE 0x0A +#define STATE_POINT 0x0B + +/* state material property */ +#define MATERIAL_AMBIENT 0x01 +#define MATERIAL_DIFFUSE 0x02 +#define MATERIAL_SPECULAR 0x03 +#define MATERIAL_EMISSION 0x04 +#define MATERIAL_SHININESS 0x05 + +/* state light property */ +#define LIGHT_AMBIENT 0x01 +#define LIGHT_DIFFUSE 0x02 +#define LIGHT_SPECULAR 0x03 +#define LIGHT_POSITION 0x04 +#define LIGHT_ATTENUATION 0x05 +#define LIGHT_HALF 0x06 +#define LIGHT_SPOT_DIRECTION 0x07 + +/* state light model property */ +#define LIGHT_MODEL_AMBIENT 0x01 +#define LIGHT_MODEL_SCENECOLOR 0x02 + +/* state light product property */ +#define LIGHT_PROD_AMBIENT 0x01 +#define LIGHT_PROD_DIFFUSE 0x02 +#define LIGHT_PROD_SPECULAR 0x03 + +/* state texture environment property */ +#define TEX_ENV_COLOR 0x01 + +/* state texture generation coord property */ +#define TEX_GEN_EYE 0x01 +#define TEX_GEN_OBJECT 0x02 + +/* state fog property */ +#define FOG_COLOR 0x01 +#define FOG_PARAMS 0x02 + +/* state depth property */ +#define DEPTH_RANGE 0x01 + +/* state point parameters property */ +#define POINT_SIZE 0x01 +#define POINT_ATTENUATION 0x02 + +/* declaration */ +#define ATTRIB 0x01 +#define PARAM 0x02 +#define TEMP 0x03 +#define OUTPUT 0x04 +#define ALIAS 0x05 +/* GL_ARB_vertex_program */ +#define ADDRESS 0x06 + +/*----------------------------------------------------------------------- + * From here on down is the semantic checking portion + * + */ + +/** + * Variable Table Handling functions + */ +typedef enum +{ + vt_none, + vt_address, + vt_attrib, + vt_param, + vt_temp, + vt_output, + vt_alias +} var_type; + + +/* + * Setting an explicit field for each of the binding properties is a bit wasteful + * of space, but it should be much more clear when reading later on.. + */ +struct var_cache +{ + GLubyte *name; + var_type type; + GLuint address_binding; /* The index of the address register we should + * be using */ + GLuint attrib_binding; /* For type vt_attrib, see nvfragprog.h for values */ + GLuint attrib_binding_idx; /* The index into the attrib register file corresponding + * to the state in attrib_binding */ + GLuint attrib_is_generic; /* If the attrib was specified through a generic + * vertex attrib */ + GLuint temp_binding; /* The index of the temp register we are to use */ + GLuint output_binding; /* For type vt_output, see nvfragprog.h for values */ + GLuint output_binding_idx; /* This is the index into the result register file + * corresponding to the bound result state */ + struct var_cache *alias_binding; /* For type vt_alias, points to the var_cache entry + * that this is aliased to */ + GLuint param_binding_type; /* {PROGRAM_STATE_VAR, PROGRAM_LOCAL_PARAM, + * PROGRAM_ENV_PARAM} */ + GLuint param_binding_begin; /* This is the offset into the program_parameter_list where + * the tokens representing our bound state (or constants) + * start */ + GLuint param_binding_length; /* This is how many entries in the the program_parameter_list + * we take up with our state tokens or constants. Note that + * this is _not_ the same as the number of param registers + * we eventually use */ + struct var_cache *next; +}; + +static GLvoid +var_cache_create (struct var_cache **va) +{ + *va = (struct var_cache *) _mesa_malloc (sizeof (struct var_cache)); + if (*va) { + (**va).name = NULL; + (**va).type = vt_none; + (**va).attrib_binding = ~0; + (**va).attrib_is_generic = 0; + (**va).temp_binding = ~0; + (**va).output_binding = ~0; + (**va).output_binding_idx = ~0; + (**va).param_binding_type = ~0; + (**va).param_binding_begin = ~0; + (**va).param_binding_length = ~0; + (**va).alias_binding = NULL; + (**va).next = NULL; + } +} + +static GLvoid +var_cache_destroy (struct var_cache **va) +{ + if (*va) { + var_cache_destroy (&(**va).next); + _mesa_free (*va); + *va = NULL; + } +} + +static GLvoid +var_cache_append (struct var_cache **va, struct var_cache *nv) +{ + if (*va) + var_cache_append (&(**va).next, nv); + else + *va = nv; +} + +static struct var_cache * +var_cache_find (struct var_cache *va, GLubyte * name) +{ + struct var_cache *first = va; + + while (va) { + if (!strcmp ( (const char*) name, (const char*) va->name)) { + if (va->type == vt_alias) + return var_cache_find (first, va->name); + return va; + } + + va = va->next; + } + + return NULL; +} + +/** + * constructs an integer from 4 GLubytes in LE format + */ +static GLuint +parse_position (GLubyte ** inst) +{ + GLuint value; + + value = (GLuint) (*(*inst)++); + value += (GLuint) (*(*inst)++) * 0x100; + value += (GLuint) (*(*inst)++) * 0x10000; + value += (GLuint) (*(*inst)++) * 0x1000000; + + return value; +} + +/** + * This will, given a string, lookup the string as a variable name in the + * var cache. If the name is found, the var cache node corresponding to the + * var name is returned. If it is not found, a new entry is allocated + * + * \param I Points into the binary array where the string identifier begins + * \param found 1 if the string was found in the var_cache, 0 if it was allocated + * \return The location on the var_cache corresponding the the string starting at I + */ +static struct var_cache * +parse_string (GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program, GLuint * found) +{ + GLubyte *i = *inst; + struct var_cache *va = NULL; + (void) Program; + + *inst += _mesa_strlen ((char *) i) + 1; + + va = var_cache_find (*vc_head, i); + + if (va) { + *found = 1; + return va; + } + + *found = 0; + var_cache_create (&va); + va->name = i; + + var_cache_append (vc_head, va); + + return va; +} + +static char * +parse_string_without_adding (GLubyte ** inst, struct arb_program *Program) +{ + GLubyte *i = *inst; + (void) Program; + + *inst += _mesa_strlen ((char *) i) + 1; + + return (char *) i; +} + +/** + * \return -1 if we parse '-', return 1 otherwise + */ +static GLint +parse_sign (GLubyte ** inst) +{ + /*return *(*inst)++ != '+'; */ + + if (**inst == '-') { + (*inst)++; + return -1; + } + else if (**inst == '+') { + (*inst)++; + return 1; + } + + return 1; +} + +/** + * parses and returns signed integer + */ +static GLint +parse_integer (GLubyte ** inst, struct arb_program *Program) +{ + GLint sign; + GLint value; + + /* check if *inst points to '+' or '-' + * if yes, grab the sign and increment *inst + */ + sign = parse_sign (inst); + + /* now check if *inst points to 0 + * if yes, increment the *inst and return the default value + */ + if (**inst == 0) { + (*inst)++; + return 0; + } + + /* parse the integer as you normally would do it */ + value = _mesa_atoi (parse_string_without_adding (inst, Program)); + + /* now, after terminating 0 there is a position + * to parse it - parse_position() + */ + Program->Position = parse_position (inst); + + return value * sign; +} + +/** + Accumulate this string of digits, and return them as + a large integer represented in floating point (for range). + If scale is not NULL, also accumulates a power-of-ten + integer scale factor that represents the number of digits + in the string. +*/ +static GLdouble +parse_float_string(GLubyte ** inst, struct arb_program *Program, GLdouble *scale) +{ + GLdouble value = 0.0; + GLdouble oscale = 1.0; + + if (**inst == 0) { /* this string of digits is empty-- do nothing */ + (*inst)++; + } + else { /* nonempty string-- parse out the digits */ + while (**inst >= '0' && **inst <= '9') { + GLubyte digit = *((*inst)++); + value = value * 10.0 + (GLint) (digit - '0'); + oscale *= 10.0; + } + assert(**inst == 0); /* integer string should end with 0 */ + (*inst)++; /* skip over terminating 0 */ + Program->Position = parse_position(inst); /* skip position (from integer) */ + } + if (scale) + *scale = oscale; + return value; +} + +/** + Parse an unsigned floating-point number from this stream of tokenized + characters. Example floating-point formats supported: + 12.34 + 12 + 0.34 + .34 + 12.34e-4 + */ +static GLfloat +parse_float (GLubyte ** inst, struct arb_program *Program) +{ + GLint exponent; + GLdouble whole, fraction, fracScale = 1.0; + + whole = parse_float_string(inst, Program, 0); + fraction = parse_float_string(inst, Program, &fracScale); + + /* Parse signed exponent */ + exponent = parse_integer(inst, Program); /* This is the exponent */ + + /* Assemble parts of floating-point number: */ + return (GLfloat) ((whole + fraction / fracScale) * + _mesa_pow(10.0, (GLfloat) exponent)); +} + + +/** + */ +static GLfloat +parse_signed_float (GLubyte ** inst, struct arb_program *Program) +{ + GLint sign = parse_sign (inst); + GLfloat value = parse_float (inst, Program); + return value * sign; +} + +/** + * This picks out a constant value from the parsed array. The constant vector is r + * returned in the *values array, which should be of length 4. + * + * \param values - The 4 component vector with the constant value in it + */ +static GLvoid +parse_constant (GLubyte ** inst, GLfloat *values, struct arb_program *Program, + GLboolean use) +{ + GLuint components, i; + + + switch (*(*inst)++) { + case CONSTANT_SCALAR: + if (use == GL_TRUE) { + values[0] = + values[1] = + values[2] = values[3] = parse_float (inst, Program); + } + else { + values[0] = + values[1] = + values[2] = values[3] = parse_signed_float (inst, Program); + } + + break; + case CONSTANT_VECTOR: + values[0] = values[1] = values[2] = 0; + values[3] = 1; + components = *(*inst)++; + for (i = 0; i < components; i++) { + values[i] = parse_signed_float (inst, Program); + } + break; + } +} + +/** + * \param offset The offset from the address register that we should + * address + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_relative_offset (GLcontext *ctx, GLubyte **inst, struct arb_program *Program, + GLint *offset) +{ + *offset = parse_integer(inst, Program); + if ((*offset > 63) || (*offset < -64)) { + _mesa_set_program_error (ctx, Program->Position, + "Relative offset out of range"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Relative offset %d out of range", + *offset); + return 1; + } + + return 0; +} + +/** + * \param color 0 if color type is primary, 1 if color type is secondary + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_color_type (GLcontext * ctx, GLubyte ** inst, struct arb_program *Program, + GLint * color) +{ + (void) ctx; (void) Program; + *color = *(*inst)++ != COLOR_PRIMARY; + return 0; +} + +/** + * Get an integer corresponding to a generic vertex attribute. + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_generic_attrib_num(GLcontext *ctx, GLubyte ** inst, + struct arb_program *Program, GLuint *attrib) +{ + GLint i = parse_integer(inst, Program); + + if ((i < 0) || (i > MAX_VERTEX_PROGRAM_ATTRIBS)) + { + _mesa_set_program_error (ctx, Program->Position, + "Invalid generic vertex attribute index"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Invalid generic vertex attribute index"); + + return 1; + } + + *attrib = (GLuint) i; + + return 0; +} + + +/** + * \param coord The texture unit index + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_texcoord_num (GLcontext * ctx, GLubyte ** inst, + struct arb_program *Program, GLuint * coord) +{ + GLint i = parse_integer (inst, Program); + + if ((i < 0) || (i >= (int)ctx->Const.MaxTextureUnits)) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid texture unit index"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Invalid texture unit index"); + return 1; + } + + *coord = (GLuint) i; + return 0; +} + +/** + * \param coord The weight index + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_weight_num (GLcontext * ctx, GLubyte ** inst, struct arb_program *Program, + GLint * coord) +{ + *coord = parse_integer (inst, Program); + + if ((*coord < 0) || (*coord >= 1)) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid weight index"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Invalid weight index"); + return 1; + } + + return 0; +} + +/** + * \param coord The clip plane index + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_clipplane_num (GLcontext * ctx, GLubyte ** inst, + struct arb_program *Program, GLint * coord) +{ + *coord = parse_integer (inst, Program); + + if ((*coord < 0) || (*coord >= (GLint) ctx->Const.MaxClipPlanes)) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid clip plane index"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Invalid clip plane index"); + return 1; + } + + return 0; +} + + +/** + * \return 0 on front face, 1 on back face + */ +static GLuint +parse_face_type (GLubyte ** inst) +{ + switch (*(*inst)++) { + case FACE_FRONT: + return 0; + + case FACE_BACK: + return 1; + } + return 0; +} + + +/** + * Given a matrix and a modifier token on the binary array, return tokens + * that _mesa_fetch_state() [program.c] can understand. + * + * \param matrix - the matrix we are talking about + * \param matrix_idx - the index of the matrix we have (for texture & program matricies) + * \param matrix_modifier - the matrix modifier (trans, inv, etc) + * \return 0 on sucess, 1 on failure + */ +static GLuint +parse_matrix (GLcontext * ctx, GLubyte ** inst, struct arb_program *Program, + GLint * matrix, GLint * matrix_idx, GLint * matrix_modifier) +{ + GLubyte mat = *(*inst)++; + + *matrix_idx = 0; + + switch (mat) { + case MATRIX_MODELVIEW: + *matrix = STATE_MODELVIEW; + *matrix_idx = parse_integer (inst, Program); + if (*matrix_idx > 0) { + _mesa_set_program_error (ctx, Program->Position, + "ARB_vertex_blend not supported\n"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "ARB_vertex_blend not supported\n"); + return 1; + } + break; + + case MATRIX_PROJECTION: + *matrix = STATE_PROJECTION; + break; + + case MATRIX_MVP: + *matrix = STATE_MVP; + break; + + case MATRIX_TEXTURE: + *matrix = STATE_TEXTURE; + *matrix_idx = parse_integer (inst, Program); + if (*matrix_idx >= (GLint) ctx->Const.MaxTextureUnits) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Texture Unit"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Texture Unit: %d", *matrix_idx); + return 1; + } + break; + + /* This is not currently supported (ARB_matrix_palette) */ + case MATRIX_PALETTE: + *matrix_idx = parse_integer (inst, Program); + _mesa_set_program_error (ctx, Program->Position, + "ARB_matrix_palette not supported\n"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "ARB_matrix_palette not supported\n"); + return 1; + break; + + case MATRIX_PROGRAM: + *matrix = STATE_PROGRAM; + *matrix_idx = parse_integer (inst, Program); + if (*matrix_idx >= (GLint) ctx->Const.MaxProgramMatrices) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Program Matrix"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Program Matrix: %d", *matrix_idx); + return 1; + } + break; + } + + switch (*(*inst)++) { + case MATRIX_MODIFIER_IDENTITY: + *matrix_modifier = 0; + break; + case MATRIX_MODIFIER_INVERSE: + *matrix_modifier = STATE_MATRIX_INVERSE; + break; + case MATRIX_MODIFIER_TRANSPOSE: + *matrix_modifier = STATE_MATRIX_TRANSPOSE; + break; + case MATRIX_MODIFIER_INVTRANS: + *matrix_modifier = STATE_MATRIX_INVTRANS; + break; + } + + return 0; +} + + +/** + * This parses a state string (rather, the binary version of it) into + * a 6-token sequence as described in _mesa_fetch_state() [program.c] + * + * \param inst - the start in the binary arry to start working from + * \param state_tokens - the storage for the 6-token state description + * \return - 0 on sucess, 1 on error + */ +static GLuint +parse_state_single_item (GLcontext * ctx, GLubyte ** inst, + struct arb_program *Program, GLint * state_tokens) +{ + switch (*(*inst)++) { + case STATE_MATERIAL_PARSER: + state_tokens[0] = STATE_MATERIAL; + state_tokens[1] = parse_face_type (inst); + switch (*(*inst)++) { + case MATERIAL_AMBIENT: + state_tokens[2] = STATE_AMBIENT; + break; + case MATERIAL_DIFFUSE: + state_tokens[2] = STATE_DIFFUSE; + break; + case MATERIAL_SPECULAR: + state_tokens[2] = STATE_SPECULAR; + break; + case MATERIAL_EMISSION: + state_tokens[2] = STATE_EMISSION; + break; + case MATERIAL_SHININESS: + state_tokens[2] = STATE_SHININESS; + break; + } + break; + + case STATE_LIGHT_PARSER: + state_tokens[0] = STATE_LIGHT; + state_tokens[1] = parse_integer (inst, Program); + + /* Check the value of state_tokens[1] against the # of lights */ + if (state_tokens[1] >= (GLint) ctx->Const.MaxLights) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Light Number"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Light Number: %d", state_tokens[1]); + return 1; + } + + switch (*(*inst)++) { + case LIGHT_AMBIENT: + state_tokens[2] = STATE_AMBIENT; + break; + case LIGHT_DIFFUSE: + state_tokens[2] = STATE_DIFFUSE; + break; + case LIGHT_SPECULAR: + state_tokens[2] = STATE_SPECULAR; + break; + case LIGHT_POSITION: + state_tokens[2] = STATE_POSITION; + break; + case LIGHT_ATTENUATION: + state_tokens[2] = STATE_ATTENUATION; + break; + case LIGHT_HALF: + state_tokens[2] = STATE_HALF; + break; + case LIGHT_SPOT_DIRECTION: + state_tokens[2] = STATE_SPOT_DIRECTION; + break; + } + break; + + case STATE_LIGHT_MODEL: + switch (*(*inst)++) { + case LIGHT_MODEL_AMBIENT: + state_tokens[0] = STATE_LIGHTMODEL_AMBIENT; + break; + case LIGHT_MODEL_SCENECOLOR: + state_tokens[0] = STATE_LIGHTMODEL_SCENECOLOR; + state_tokens[1] = parse_face_type (inst); + break; + } + break; + + case STATE_LIGHT_PROD: + state_tokens[0] = STATE_LIGHTPROD; + state_tokens[1] = parse_integer (inst, Program); + + /* Check the value of state_tokens[1] against the # of lights */ + if (state_tokens[1] >= (GLint) ctx->Const.MaxLights) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Light Number"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Light Number: %d", state_tokens[1]); + return 1; + } + + state_tokens[2] = parse_face_type (inst); + switch (*(*inst)++) { + case LIGHT_PROD_AMBIENT: + state_tokens[3] = STATE_AMBIENT; + break; + case LIGHT_PROD_DIFFUSE: + state_tokens[3] = STATE_DIFFUSE; + break; + case LIGHT_PROD_SPECULAR: + state_tokens[3] = STATE_SPECULAR; + break; + } + break; + + + case STATE_FOG: + switch (*(*inst)++) { + case FOG_COLOR: + state_tokens[0] = STATE_FOG_COLOR; + break; + case FOG_PARAMS: + state_tokens[0] = STATE_FOG_PARAMS; + break; + } + break; + + case STATE_TEX_ENV: + state_tokens[1] = parse_integer (inst, Program); + switch (*(*inst)++) { + case TEX_ENV_COLOR: + state_tokens[0] = STATE_TEXENV_COLOR; + break; + } + break; + + case STATE_TEX_GEN: + { + GLuint type, coord; + + state_tokens[0] = STATE_TEXGEN; + /*state_tokens[1] = parse_integer (inst, Program);*/ /* Texture Unit */ + + if (parse_texcoord_num (ctx, inst, Program, &coord)) + return 1; + state_tokens[1] = coord; + + /* EYE or OBJECT */ + type = *(*inst++); + + /* 0 - s, 1 - t, 2 - r, 3 - q */ + coord = *(*inst++); + + if (type == TEX_GEN_EYE) { + switch (coord) { + case COMPONENT_X: + state_tokens[2] = STATE_TEXGEN_EYE_S; + break; + case COMPONENT_Y: + state_tokens[2] = STATE_TEXGEN_EYE_T; + break; + case COMPONENT_Z: + state_tokens[2] = STATE_TEXGEN_EYE_R; + break; + case COMPONENT_W: + state_tokens[2] = STATE_TEXGEN_EYE_Q; + break; + } + } + else { + switch (coord) { + case COMPONENT_X: + state_tokens[2] = STATE_TEXGEN_OBJECT_S; + break; + case COMPONENT_Y: + state_tokens[2] = STATE_TEXGEN_OBJECT_T; + break; + case COMPONENT_Z: + state_tokens[2] = STATE_TEXGEN_OBJECT_R; + break; + case COMPONENT_W: + state_tokens[2] = STATE_TEXGEN_OBJECT_Q; + break; + } + } + } + break; + + case STATE_DEPTH: + switch (*(*inst)++) { + case DEPTH_RANGE: + state_tokens[0] = STATE_DEPTH_RANGE; + break; + } + break; + + case STATE_CLIP_PLANE: + state_tokens[0] = STATE_CLIPPLANE; + state_tokens[1] = parse_integer (inst, Program); + if (parse_clipplane_num (ctx, inst, Program, &state_tokens[1])) + return 1; + break; + + case STATE_POINT: + switch (*(*inst++)) { + case POINT_SIZE: + state_tokens[0] = STATE_POINT_SIZE; + break; + + case POINT_ATTENUATION: + state_tokens[0] = STATE_POINT_ATTENUATION; + break; + } + break; + + /* XXX: I think this is the correct format for a matrix row */ + case STATE_MATRIX_ROWS: + state_tokens[0] = STATE_MATRIX; + if (parse_matrix + (ctx, inst, Program, &state_tokens[1], &state_tokens[2], + &state_tokens[5])) + return 1; + + state_tokens[3] = parse_integer (inst, Program); /* The first row to grab */ + + if ((**inst) != 0) { /* Either the last row, 0 */ + state_tokens[4] = parse_integer (inst, Program); + if (state_tokens[4] < state_tokens[3]) { + _mesa_set_program_error (ctx, Program->Position, + "Second matrix index less than the first"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Second matrix index (%d) less than the first (%d)", + state_tokens[4], state_tokens[3]); + return 1; + } + } + else { + state_tokens[4] = state_tokens[3]; + (*inst)++; + } + break; + } + + return 0; +} + +/** + * This parses a state string (rather, the binary version of it) into + * a 6-token similar for the state fetching code in program.c + * + * One might ask, why fetch these parameters into just like you fetch + * state when they are already stored in other places? + * + * Because of array offsets -> We can stick env/local parameters in the + * middle of a parameter array and then index someplace into the array + * when we execute. + * + * One optimization might be to only do this for the cases where the + * env/local parameters end up inside of an array, and leave the + * single parameters (or arrays of pure env/local pareameters) in their + * respective register files. + * + * For ENV parameters, the format is: + * state_tokens[0] = STATE_FRAGMENT_PROGRAM / STATE_VERTEX_PROGRAM + * state_tokens[1] = STATE_ENV + * state_tokens[2] = the parameter index + * + * for LOCAL parameters, the format is: + * state_tokens[0] = STATE_FRAGMENT_PROGRAM / STATE_VERTEX_PROGRAM + * state_tokens[1] = STATE_LOCAL + * state_tokens[2] = the parameter index + * + * \param inst - the start in the binary arry to start working from + * \param state_tokens - the storage for the 6-token state description + * \return - 0 on sucess, 1 on failure + */ +static GLuint +parse_program_single_item (GLcontext * ctx, GLubyte ** inst, + struct arb_program *Program, GLint * state_tokens) +{ + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) + state_tokens[0] = STATE_FRAGMENT_PROGRAM; + else + state_tokens[0] = STATE_VERTEX_PROGRAM; + + + switch (*(*inst)++) { + case PROGRAM_PARAM_ENV: + state_tokens[1] = STATE_ENV; + state_tokens[2] = parse_integer (inst, Program); + + /* Check state_tokens[2] against the number of ENV parameters available */ + if (((Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) && + (state_tokens[2] >= (GLint) ctx->Const.MaxFragmentProgramEnvParams)) + || + ((Program->Base.Target == GL_VERTEX_PROGRAM_ARB) && + (state_tokens[2] >= (GLint) ctx->Const.MaxVertexProgramEnvParams))) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Program Env Parameter"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Program Env Parameter: %d", + state_tokens[2]); + return 1; + } + + break; + + case PROGRAM_PARAM_LOCAL: + state_tokens[1] = STATE_LOCAL; + state_tokens[2] = parse_integer (inst, Program); + + /* Check state_tokens[2] against the number of LOCAL parameters available */ + if (((Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) && + (state_tokens[2] >= (GLint) ctx->Const.MaxFragmentProgramLocalParams)) + || + ((Program->Base.Target == GL_VERTEX_PROGRAM_ARB) && + (state_tokens[2] >= (GLint) ctx->Const.MaxVertexProgramLocalParams))) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Program Local Parameter"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Program Local Parameter: %d", + state_tokens[2]); + return 1; + } + break; + } + + return 0; +} + +/** + * For ARB_vertex_program, programs are not allowed to use both an explicit + * vertex attribute and a generic vertex attribute corresponding to the same + * state. See section 2.14.3.1 of the GL_ARB_vertex_program spec. + * + * This will walk our var_cache and make sure that nobody does anything fishy. + * + * \return 0 on sucess, 1 on error + */ +static GLuint +generic_attrib_check(struct var_cache *vc_head) +{ + int a; + struct var_cache *curr; + GLboolean explicitAttrib[MAX_VERTEX_PROGRAM_ATTRIBS], + genericAttrib[MAX_VERTEX_PROGRAM_ATTRIBS]; + + for (a=0; atype == vt_attrib) { + if (curr->attrib_is_generic) + genericAttrib[ curr->attrib_binding_idx ] = GL_TRUE; + else + explicitAttrib[ curr->attrib_binding_idx ] = GL_TRUE; + } + + curr = curr->next; + } + + for (a=0; aBase.Target == GL_FRAGMENT_PROGRAM_ARB) { + switch (*(*inst)++) { + case FRAGMENT_ATTRIB_COLOR: + err = parse_color_type (ctx, inst, Program, &coord); + *binding = FRAG_ATTRIB_COL0 + coord; + *binding_idx = 1 + coord; + break; + + case FRAGMENT_ATTRIB_TEXCOORD: + err = parse_texcoord_num (ctx, inst, Program, &texcoord); + *binding = FRAG_ATTRIB_TEX0 + texcoord; + *binding_idx = 4 + texcoord; + break; + + case FRAGMENT_ATTRIB_FOGCOORD: + *binding = FRAG_ATTRIB_FOGC; + *binding_idx = 3; + break; + + case FRAGMENT_ATTRIB_POSITION: + *binding = FRAG_ATTRIB_WPOS; + *binding_idx = 0; + break; + + default: + err = 1; + break; + } + } + else { + switch (*(*inst)++) { + case VERTEX_ATTRIB_POSITION: + *binding = VERT_ATTRIB_POS; + *binding_idx = 0; + break; + + case VERTEX_ATTRIB_WEIGHT: + { + GLint weight; + + err = parse_weight_num (ctx, inst, Program, &weight); + *binding = VERT_ATTRIB_WEIGHT; + *binding_idx = 1; + } + _mesa_set_program_error (ctx, Program->Position, + "ARB_vertex_blend not supported\n"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "ARB_vertex_blend not supported\n"); + return 1; + break; + + case VERTEX_ATTRIB_NORMAL: + *binding = VERT_ATTRIB_NORMAL; + *binding_idx = 2; + break; + + case VERTEX_ATTRIB_COLOR: + { + GLint color; + + err = parse_color_type (ctx, inst, Program, &color); + if (color) { + *binding = VERT_ATTRIB_COLOR1; + *binding_idx = 4; + } + else { + *binding = VERT_ATTRIB_COLOR0; + *binding_idx = 3; + } + } + break; + + case VERTEX_ATTRIB_FOGCOORD: + *binding = VERT_ATTRIB_FOG; + *binding_idx = 5; + break; + + case VERTEX_ATTRIB_TEXCOORD: + { + GLuint unit; + + err = parse_texcoord_num (ctx, inst, Program, &unit); + *binding = VERT_ATTRIB_TEX0 + unit; + *binding_idx = 8 + unit; + } + break; + + /* It looks like we don't support this at all, atm */ + case VERTEX_ATTRIB_MATRIXINDEX: + parse_integer (inst, Program); + _mesa_set_program_error (ctx, Program->Position, + "ARB_palette_matrix not supported"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "ARB_palette_matrix not supported"); + return 1; + break; + + case VERTEX_ATTRIB_GENERIC: + { + GLuint attrib; + + if (!parse_generic_attrib_num(ctx, inst, Program, &attrib)) { + *is_generic = 1; + switch (attrib) { + case 0: + *binding = VERT_ATTRIB_POS; + break; + case 1: + *binding = VERT_ATTRIB_WEIGHT; + break; + case 2: + *binding = VERT_ATTRIB_NORMAL; + break; + case 3: + *binding = VERT_ATTRIB_COLOR0; + break; + case 4: + *binding = VERT_ATTRIB_COLOR1; + break; + case 5: + *binding = VERT_ATTRIB_FOG; + break; + case 6: + break; + case 7: + break; + default: + *binding = VERT_ATTRIB_TEX0 + (attrib-8); + break; + } + *binding_idx = attrib; + } + } + break; + + default: + err = 1; + break; + } + } + + /* Can this even happen? */ + if (err) { + _mesa_set_program_error (ctx, Program->Position, + "Bad attribute binding"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Bad attribute binding"); + } + + Program->InputsRead |= (1 << *binding_idx); + + return err; +} + +/** + * This translates between a binary token for an output variable type + * and the mesa token for the same thing. + * + * + * XXX: What is the 'name' for vertex program state? -> do we need it? + * I don't think we do; + * + * See nvfragprog.h for definitions + * + * \param inst - The parsed tokens + * \param binding - The name of the state we are binding too + * \param binding_idx - The index into the result register file that this is bound too + * + * See nvfragparse.c for the register file layout for fragment programs + * See nvvertparse.c for the register file layout for vertex programs + */ +static GLuint +parse_result_binding (GLcontext * ctx, GLubyte ** inst, GLuint * binding, + GLuint * binding_idx, struct arb_program *Program) +{ + GLuint b; + + switch (*(*inst)++) { + case FRAGMENT_RESULT_COLOR: + /* for frag programs, this is FRAGMENT_RESULT_COLOR */ + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + *binding = FRAG_OUTPUT_COLR; + *binding_idx = 0; + } + /* for vtx programs, this is VERTEX_RESULT_POSITION */ + else { + *binding_idx = 0; + } + break; + + case FRAGMENT_RESULT_DEPTH: + /* for frag programs, this is FRAGMENT_RESULT_DEPTH */ + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + *binding = FRAG_OUTPUT_DEPR; + *binding_idx = 2; + } + /* for vtx programs, this is VERTEX_RESULT_COLOR */ + else { + GLint color_type; + GLuint face_type = parse_face_type(inst); + GLint color_type_ret = parse_color_type(ctx, inst, Program, &color_type); + + /* back face */ + if (face_type) { + if (color_type_ret) return 1; + + /* secondary color */ + if (color_type) { + *binding_idx = 4; + } + /* primary color */ + else { + *binding_idx = 3; + } + } + /* front face */ + else { + /* secondary color */ + if (color_type) { + *binding_idx = 2; + } + /* primary color */ + else { + *binding_idx = 1; + } + } + } + break; + + case VERTEX_RESULT_FOGCOORD: + *binding_idx = 5; + break; + + case VERTEX_RESULT_POINTSIZE: + *binding_idx = 6; + break; + + case VERTEX_RESULT_TEXCOORD: + if (parse_texcoord_num (ctx, inst, Program, &b)) + return 1; + *binding_idx = 7 + b; + break; + } + + Program->OutputsWritten |= (1 << *binding_idx); + + return 0; +} + +/** + * This handles the declaration of ATTRIB variables + * + * XXX: Still needs + * parse_vert_attrib_binding(), or something like that + * + * \return 0 on sucess, 1 on error + */ +static GLint +parse_attrib (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found; + char *error_msg; + struct var_cache *attrib_var; + + attrib_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + if (found) { + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) attrib_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + attrib_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + attrib_var->type = vt_attrib; + + /* I think this is ok now - karl */ + /* XXX: */ + /*if (Program->type == GL_FRAGMENT_PROGRAM_ARB) */ + { + if (parse_attrib_binding + (ctx, inst, Program, &attrib_var->attrib_binding, + &attrib_var->attrib_binding_idx, &attrib_var->attrib_is_generic)) + return 1; + if (generic_attrib_check(*vc_head)) { + _mesa_set_program_error (ctx, Program->Position, + "Cannot use both a generic vertex attribute and a specific attribute of the same type"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Cannot use both a generic vertex attribute and a specific attribute of the same type"); + return 1; + } + + } + + Program->Base.NumAttributes++; + return 0; +} + +/** + * \param use -- TRUE if we're called when declaring implicit parameters, + * FALSE if we're declaraing variables. This has to do with + * if we get a signed or unsigned float for scalar constants + */ +static GLuint +parse_param_elements (GLcontext * ctx, GLubyte ** inst, + struct var_cache *param_var, + struct arb_program *Program, GLboolean use) +{ + GLint idx; + GLuint err; + GLint state_tokens[6]; + GLfloat const_values[4]; + + err = 0; + + switch (*(*inst)++) { + case PARAM_STATE_ELEMENT: + + if (parse_state_single_item (ctx, inst, Program, state_tokens)) + return 1; + + /* If we adding STATE_MATRIX that has multiple rows, we need to + * unroll it and call _mesa_add_state_reference() for each row + */ + if ((state_tokens[0] == STATE_MATRIX) + && (state_tokens[3] != state_tokens[4])) { + GLint row; + GLint first_row = state_tokens[3]; + GLint last_row = state_tokens[4]; + + for (row = first_row; row <= last_row; row++) { + state_tokens[3] = state_tokens[4] = row; + + idx = + _mesa_add_state_reference (Program->Parameters, + state_tokens); + if (param_var->param_binding_begin == ~0U) + param_var->param_binding_begin = idx; + param_var->param_binding_length++; + Program->Base.NumParameters++; + } + } + else { + idx = + _mesa_add_state_reference (Program->Parameters, state_tokens); + if (param_var->param_binding_begin == ~0U) + param_var->param_binding_begin = idx; + param_var->param_binding_length++; + Program->Base.NumParameters++; + } + break; + + case PARAM_PROGRAM_ELEMENT: + + if (parse_program_single_item (ctx, inst, Program, state_tokens)) + return 1; + idx = _mesa_add_state_reference (Program->Parameters, state_tokens); + if (param_var->param_binding_begin == ~0U) + param_var->param_binding_begin = idx; + param_var->param_binding_length++; + Program->Base.NumParameters++; + + /* Check if there is more: 0 -> we're done, else its an integer */ + if (**inst) { + GLuint out_of_range, new_idx; + GLuint start_idx = state_tokens[2] + 1; + GLuint end_idx = parse_integer (inst, Program); + + out_of_range = 0; + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + if (((state_tokens[1] == STATE_ENV) + && (end_idx >= ctx->Const.MaxFragmentProgramEnvParams)) + || ((state_tokens[1] == STATE_LOCAL) + && (end_idx >= + ctx->Const.MaxFragmentProgramLocalParams))) + out_of_range = 1; + } + else { + if (((state_tokens[1] == STATE_ENV) + && (end_idx >= ctx->Const.MaxVertexProgramEnvParams)) + || ((state_tokens[1] == STATE_LOCAL) + && (end_idx >= + ctx->Const.MaxVertexProgramLocalParams))) + out_of_range = 1; + } + if (out_of_range) { + _mesa_set_program_error (ctx, Program->Position, + "Invalid Program Parameter"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Invalid Program Parameter: %d", end_idx); + return 1; + } + + for (new_idx = start_idx; new_idx <= end_idx; new_idx++) { + state_tokens[2] = new_idx; + idx = + _mesa_add_state_reference (Program->Parameters, + state_tokens); + param_var->param_binding_length++; + Program->Base.NumParameters++; + } + } + else + { + (*inst)++; + } + break; + + case PARAM_CONSTANT: + parse_constant (inst, const_values, Program, use); + idx = + _mesa_add_named_constant (Program->Parameters, + (char *) param_var->name, const_values); + if (param_var->param_binding_begin == ~0U) + param_var->param_binding_begin = idx; + param_var->param_binding_length++; + Program->Base.NumParameters++; + break; + + default: + _mesa_set_program_error (ctx, Program->Position, + "Unexpected token in parse_param_elements()"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Unexpected token in parse_param_elements()"); + return 1; + } + + /* Make sure we haven't blown past our parameter limits */ + if (((Program->Base.Target == GL_VERTEX_PROGRAM_ARB) && + (Program->Base.NumParameters >= + ctx->Const.MaxVertexProgramLocalParams)) + || ((Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) + && (Program->Base.NumParameters >= + ctx->Const.MaxFragmentProgramLocalParams))) { + _mesa_set_program_error (ctx, Program->Position, + "Too many parameter variables"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Too many parameter variables"); + return 1; + } + + return err; +} + +/** + * This picks out PARAM program parameter bindings. + * + * XXX: This needs to be stressed & tested + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_param (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found, err; + GLint specified_length; + char *error_msg; + struct var_cache *param_var; + + err = 0; + param_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + + if (found) { + error_msg = (char *) _mesa_malloc (_mesa_strlen ((char *) param_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + param_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + specified_length = parse_integer (inst, Program); + + if (specified_length < 0) { + _mesa_set_program_error (ctx, Program->Position, + "Negative parameter array length"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Negative parameter array length: %d", specified_length); + return 1; + } + + param_var->type = vt_param; + param_var->param_binding_length = 0; + + /* Right now, everything is shoved into the main state register file. + * + * In the future, it would be nice to leave things ENV/LOCAL params + * in their respective register files, if possible + */ + param_var->param_binding_type = PROGRAM_STATE_VAR; + + /* Remember to: + * * - add each guy to the parameter list + * * - increment the param_var->param_binding_len + * * - store the param_var->param_binding_begin for the first one + * * - compare the actual len to the specified len at the end + */ + while (**inst != PARAM_NULL) { + if (parse_param_elements (ctx, inst, param_var, Program, GL_FALSE)) + return 1; + } + + /* Test array length here! */ + if (specified_length) { + if (specified_length != (int)param_var->param_binding_length) { + _mesa_set_program_error (ctx, Program->Position, + "Declared parameter array lenght does not match parameter list"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Declared parameter array lenght does not match parameter list"); + } + } + + (*inst)++; + + return 0; +} + +/** + * + */ +static GLuint +parse_param_use (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program, struct var_cache **new_var) +{ + struct var_cache *param_var; + + /* First, insert a dummy entry into the var_cache */ + var_cache_create (¶m_var); + param_var->name = (GLubyte *) _mesa_strdup (" "); + param_var->type = vt_param; + + param_var->param_binding_length = 0; + /* Don't fill in binding_begin; We use the default value of -1 + * to tell if its already initialized, elsewhere. + * + * param_var->param_binding_begin = 0; + */ + param_var->param_binding_type = PROGRAM_STATE_VAR; + + var_cache_append (vc_head, param_var); + + /* Then fill it with juicy parameter goodness */ + if (parse_param_elements (ctx, inst, param_var, Program, GL_TRUE)) + return 1; + + *new_var = param_var; + + return 0; +} + + +/** + * This handles the declaration of TEMP variables + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_temp (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found; + struct var_cache *temp_var; + char *error_msg; + + while (**inst != 0) { + temp_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + if (found) { + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) temp_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + temp_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + temp_var->type = vt_temp; + + if (((Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) && + (Program->Base.NumTemporaries >= + ctx->Const.MaxFragmentProgramTemps)) + || ((Program->Base.Target == GL_VERTEX_PROGRAM_ARB) + && (Program->Base.NumTemporaries >= + ctx->Const.MaxVertexProgramTemps))) { + _mesa_set_program_error (ctx, Program->Position, + "Too many TEMP variables declared"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Too many TEMP variables declared"); + return 1; + } + + temp_var->temp_binding = Program->Base.NumTemporaries; + Program->Base.NumTemporaries++; + } + (*inst)++; + + return 0; +} + +/** + * This handles variables of the OUTPUT variety + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_output (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found; + struct var_cache *output_var; + + output_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + if (found) { + char *error_msg; + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) output_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + output_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + output_var->type = vt_output; + return parse_result_binding (ctx, inst, &output_var->output_binding, + &output_var->output_binding_idx, Program); +} + +/** + * This handles variables of the ALIAS kind + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_alias (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found; + struct var_cache *temp_var; + char *error_msg; + + + temp_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + + if (found) { + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) temp_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + temp_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + temp_var->type = vt_alias; + temp_var->alias_binding = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + + if (!found) + { + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) temp_var->name) + 40); + _mesa_sprintf (error_msg, "Alias value %s is not defined", + temp_var->alias_binding->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + return 0; +} + +/** + * This handles variables of the ADDRESS kind + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_address (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLuint found; + struct var_cache *temp_var; + char *error_msg; + + while (**inst != 0) { + temp_var = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + if (found) { + error_msg = (char *) + _mesa_malloc (_mesa_strlen ((char *) temp_var->name) + 40); + _mesa_sprintf (error_msg, "Duplicate Varible Declaration: %s", + temp_var->name); + + _mesa_set_program_error (ctx, Program->Position, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, error_msg); + + _mesa_free (error_msg); + return 1; + } + + temp_var->type = vt_address; + + if (Program->Base.NumAddressRegs >= + ctx->Const.MaxVertexProgramAddressRegs) { + _mesa_set_program_error (ctx, Program->Position, + "Too many ADDRESS variables declared"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Too many ADDRESS variables declared"); + return 1; + } + + temp_var->address_binding = Program->Base.NumAddressRegs; + Program->Base.NumAddressRegs++; + } + (*inst)++; + + return 0; +} + +/** + * Parse a program declaration + * + * \return 0 on sucess, 1 on error + */ +static GLint +parse_declaration (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLint err = 0; + + switch (*(*inst)++) { + case ADDRESS: + err = parse_address (ctx, inst, vc_head, Program); + break; + + case ALIAS: + err = parse_alias (ctx, inst, vc_head, Program); + break; + + case ATTRIB: + err = parse_attrib (ctx, inst, vc_head, Program); + break; + + case OUTPUT: + err = parse_output (ctx, inst, vc_head, Program); + break; + + case PARAM: + err = parse_param (ctx, inst, vc_head, Program); + break; + + case TEMP: + err = parse_temp (ctx, inst, vc_head, Program); + break; + } + + return err; +} + +/** + * Handle the parsing out of a masked destination register + * + * If we are a vertex program, make sure we don't write to + * result.position of we have specified that the program is + * position invariant + * + * \param File - The register file we write to + * \param Index - The register index we write to + * \param WriteMask - The mask controlling which components we write (1->write) + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_masked_dst_reg (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, struct arb_program *Program, + GLint * File, GLint * Index, GLboolean * WriteMask) +{ + GLuint result; + GLubyte mask; + struct var_cache *dst; + + /* We either have a result register specified, or a + * variable that may or may not be writable + */ + switch (*(*inst)++) { + case REGISTER_RESULT: + if (parse_result_binding + (ctx, inst, &result, (GLuint *) Index, Program)) + return 1; + *File = PROGRAM_OUTPUT; + break; + + case REGISTER_ESTABLISHED_NAME: + dst = parse_string (inst, vc_head, Program, &result); + Program->Position = parse_position (inst); + + /* If the name has never been added to our symbol table, we're hosed */ + if (!result) { + _mesa_set_program_error (ctx, Program->Position, + "0: Undefined variable"); + _mesa_error (ctx, GL_INVALID_OPERATION, "0: Undefined variable: %s", + dst->name); + return 1; + } + + switch (dst->type) { + case vt_output: + *File = PROGRAM_OUTPUT; + *Index = dst->output_binding_idx; + break; + + case vt_temp: + *File = PROGRAM_TEMPORARY; + *Index = dst->temp_binding; + break; + + /* If the var type is not vt_output or vt_temp, no go */ + default: + _mesa_set_program_error (ctx, Program->Position, + "Destination register is read only"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Destination register is read only: %s", + dst->name); + return 1; + } + break; + + default: + _mesa_set_program_error (ctx, Program->Position, + "Unexpected opcode in parse_masked_dst_reg()"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Unexpected opcode in parse_masked_dst_reg()"); + return 1; + } + + + /* Position invariance test */ + /* This test is done now in syntax portion - when position invariance OPTION + is specified, "result.position" rule is disabled so there is no way + to write the position + */ + /*if ((Program->HintPositionInvariant) && (*File == PROGRAM_OUTPUT) && + (*Index == 0)) { + _mesa_set_program_error (ctx, Program->Position, + "Vertex program specified position invariance and wrote vertex position"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Vertex program specified position invariance and wrote vertex position"); + }*/ + + /* And then the mask. + * w,a -> bit 0 + * z,b -> bit 1 + * y,g -> bit 2 + * x,r -> bit 3 + */ + mask = *(*inst)++; + + WriteMask[0] = (GLboolean) (mask & (1 << 3)) >> 3; + WriteMask[1] = (GLboolean) (mask & (1 << 2)) >> 2; + WriteMask[2] = (GLboolean) (mask & (1 << 1)) >> 1; + WriteMask[3] = (GLboolean) (mask & (1)); + + return 0; +} + + +/** + * Handle the parsing of a address register + * + * \param Index - The register index we write to + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_address_reg (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, + struct arb_program *Program, GLint * Index) +{ + struct var_cache *dst; + GLuint result; + (void) Index; + + dst = parse_string (inst, vc_head, Program, &result); + Program->Position = parse_position (inst); + + /* If the name has never been added to our symbol table, we're hosed */ + if (!result) { + _mesa_set_program_error (ctx, Program->Position, "Undefined variable"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Undefined variable: %s", + dst->name); + return 1; + } + + if (dst->type != vt_address) { + _mesa_set_program_error (ctx, Program->Position, + "Variable is not of type ADDRESS"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Variable: %s is not of type ADDRESS", dst->name); + return 1; + } + + return 0; +} + +/** + * Handle the parsing out of a masked address register + * + * \param Index - The register index we write to + * \param WriteMask - The mask controlling which components we write (1->write) + * + * \return 0 on sucess, 1 on error + */ +static GLuint +parse_masked_address_reg (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, + struct arb_program *Program, GLint * Index, + GLboolean * WriteMask) +{ + if (parse_address_reg (ctx, inst, vc_head, Program, Index)) + return 1; + + /* This should be 0x8 */ + (*inst)++; + + /* Writemask of .x is implied */ + WriteMask[0] = 1; + WriteMask[1] = WriteMask[2] = WriteMask[3] = 0; + + return 0; +} + + +/** + * Parse out a swizzle mask. + * + * The values in the input stream are: + * COMPONENT_X -> x/r + * COMPONENT_Y -> y/g + * COMPONENT_Z-> z/b + * COMPONENT_W-> w/a + * + * The values in the output mask are: + * 0 -> x/r + * 1 -> y/g + * 2 -> z/b + * 3 -> w/a + * + * The len parameter allows us to grab 4 components for a vector + * swizzle, or just 1 component for a scalar src register selection + */ +static GLuint +parse_swizzle_mask (GLubyte ** inst, GLubyte * mask, GLint len) +{ + GLint a; + + for (a = 0; a < 4; a++) + mask[a] = a; + + for (a = 0; a < len; a++) { + switch (*(*inst)++) { + case COMPONENT_X: + mask[a] = 0; + break; + + case COMPONENT_Y: + mask[a] = 1; + break; + + case COMPONENT_Z: + mask[a] = 2; + break; + + case COMPONENT_W: + mask[a] = 3; + break; + } + } + + return 0; +} + +/** + */ +static GLuint +parse_extended_swizzle_mask (GLubyte ** inst, GLubyte * mask, GLboolean * Negate) +{ + GLint a; + GLubyte swz; + + *Negate = GL_FALSE; + for (a = 0; a < 4; a++) { + if (parse_sign (inst) == -1) + *Negate = GL_TRUE; + + swz = *(*inst)++; + + switch (swz) { + case COMPONENT_0: + mask[a] = SWIZZLE_ZERO; + break; + case COMPONENT_1: + mask[a] = SWIZZLE_ONE; + break; + case COMPONENT_X: + mask[a] = SWIZZLE_X; + break; + case COMPONENT_Y: + mask[a] = SWIZZLE_Y; + break; + case COMPONENT_Z: + mask[a] = SWIZZLE_Z; + break; + case COMPONENT_W: + mask[a] = SWIZZLE_W; + break; + + } +#if 0 + if (swz == 0) + mask[a] = SWIZZLE_ZERO; + else if (swz == 1) + mask[a] = SWIZZLE_ONE; + else + mask[a] = swz - 2; +#endif + + } + + return 0; +} + + +static GLuint +parse_src_reg (GLcontext * ctx, GLubyte ** inst, struct var_cache **vc_head, + struct arb_program *Program, GLint * File, GLint * Index, + GLboolean *IsRelOffset ) +{ + struct var_cache *src; + GLuint binding_state, binding_idx, is_generic, found; + GLint offset; + + /* And the binding for the src */ + switch (*(*inst)++) { + case REGISTER_ATTRIB: + if (parse_attrib_binding + (ctx, inst, Program, &binding_state, &binding_idx, &is_generic)) + return 1; + *File = PROGRAM_INPUT; + *Index = binding_idx; + + /* We need to insert a dummy variable into the var_cache so we can + * catch generic vertex attrib aliasing errors + */ + var_cache_create(&src); + src->type = vt_attrib; + src->name = (GLubyte *)_mesa_strdup("Dummy Attrib Variable"); + src->attrib_binding = binding_state; + src->attrib_binding_idx = binding_idx; + src->attrib_is_generic = is_generic; + var_cache_append(vc_head, src); + if (generic_attrib_check(*vc_head)) { + _mesa_set_program_error (ctx, Program->Position, + "Cannot use both a generic vertex attribute and a specific attribute of the same type"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Cannot use both a generic vertex attribute and a specific attribute of the same type"); + return 1; + } + break; + + case REGISTER_PARAM: + switch (**inst) { + case PARAM_ARRAY_ELEMENT: + (*inst)++; + src = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + + if (!found) { + _mesa_set_program_error (ctx, Program->Position, + "2: Undefined variable"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "2: Undefined variable: %s", src->name); + return 1; + } + + *File = src->param_binding_type; + + switch (*(*inst)++) { + case ARRAY_INDEX_ABSOLUTE: + offset = parse_integer (inst, Program); + + if ((offset < 0) + || (offset >= (int)src->param_binding_length)) { + _mesa_set_program_error (ctx, Program->Position, + "Index out of range"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Index %d out of range for %s", offset, + src->name); + return 1; + } + + *Index = src->param_binding_begin + offset; + break; + + case ARRAY_INDEX_RELATIVE: + { + GLint addr_reg_idx, rel_off; + + /* First, grab the address regiseter */ + if (parse_address_reg (ctx, inst, vc_head, Program, &addr_reg_idx)) + return 1; + + /* And the .x */ + ((*inst)++); + ((*inst)++); + ((*inst)++); + ((*inst)++); + + /* Then the relative offset */ + if (parse_relative_offset(ctx, inst, Program, &rel_off)) return 1; + + /* And store it properly */ + *Index = src->param_binding_begin + rel_off; + *IsRelOffset = 1; + } + break; + } + break; + + default: + + if (parse_param_use (ctx, inst, vc_head, Program, &src)) + return 1; + + *File = src->param_binding_type; + *Index = src->param_binding_begin; + break; + } + break; + + case REGISTER_ESTABLISHED_NAME: + + src = parse_string (inst, vc_head, Program, &found); + Program->Position = parse_position (inst); + + /* If the name has never been added to our symbol table, we're hosed */ + if (!found) { + _mesa_set_program_error (ctx, Program->Position, + "3: Undefined variable"); + _mesa_error (ctx, GL_INVALID_OPERATION, "3: Undefined variable: %s", + src->name); + return 1; + } + + switch (src->type) { + case vt_attrib: + *File = PROGRAM_INPUT; + *Index = src->attrib_binding_idx; + break; + + /* XXX: We have to handle offsets someplace in here! -- or are those above? */ + case vt_param: + *File = src->param_binding_type; + *Index = src->param_binding_begin; + break; + + case vt_temp: + *File = PROGRAM_TEMPORARY; + *Index = src->temp_binding; + break; + + /* If the var type is vt_output no go */ + default: + _mesa_set_program_error (ctx, Program->Position, + "destination register is read only"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "destination register is read only: %s", + src->name); + return 1; + } + break; + + default: + _mesa_set_program_error (ctx, Program->Position, + "Unknown token in parse_src_reg"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Unknown token in parse_src_reg"); + return 1; + } + + return 0; +} + +/** + */ +static GLuint +parse_vector_src_reg (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, struct arb_program *Program, + GLint * File, GLint * Index, GLboolean * Negate, + GLubyte * Swizzle, GLboolean *IsRelOffset) +{ + /* Grab the sign */ + *Negate = (parse_sign (inst) == -1); + + /* And the src reg */ + if (parse_src_reg (ctx, inst, vc_head, Program, File, Index, IsRelOffset)) + return 1; + + /* finally, the swizzle */ + parse_swizzle_mask (inst, Swizzle, 4); + + return 0; +} + +/** + */ +static GLuint +parse_scalar_src_reg (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, struct arb_program *Program, + GLint * File, GLint * Index, GLboolean * Negate, + GLubyte * Swizzle, GLboolean *IsRelOffset) +{ + /* Grab the sign */ + *Negate = (parse_sign (inst) == -1); + + /* And the src reg */ + if (parse_src_reg (ctx, inst, vc_head, Program, File, Index, IsRelOffset)) + return 1; + + /* Now, get the component and shove it into all the swizzle slots */ + parse_swizzle_mask (inst, Swizzle, 1); + + return 0; +} + +/** + * This is a big mother that handles getting opcodes into the instruction + * and handling the src & dst registers for fragment program instructions + */ +static GLuint +parse_fp_instruction (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, struct arb_program *Program, + struct fp_instruction *fp) +{ + GLint a, b; + GLubyte swz[4]; /* FP's swizzle mask is a GLubyte, while VP's is GLuint */ + GLuint texcoord; + GLubyte instClass, type, code; + GLboolean rel; + + /* No condition codes in ARB_fp */ + fp->UpdateCondRegister = 0; + + /* Record the position in the program string for debugging */ + fp->StringPos = Program->Position; + + /* OP_ALU_INST or OP_TEX_INST */ + instClass = *(*inst)++; + + /* OP_ALU_{VECTOR, SCALAR, BINSC, BIN, TRI, SWZ}, + * OP_TEX_{SAMPLE, KIL} + */ + type = *(*inst)++; + + /* The actual opcode name */ + code = *(*inst)++; + + /* Increment the correct count */ + switch (instClass) { + case OP_ALU_INST: + Program->NumAluInstructions++; + break; + case OP_TEX_INST: + Program->NumTexInstructions++; + break; + } + + fp->Saturate = 0; + fp->Precision = FLOAT32; + + fp->DstReg.CondMask = COND_TR; + + switch (type) { + case OP_ALU_VECTOR: + switch (code) { + case OP_ABS_SAT: + fp->Saturate = 1; + case OP_ABS: + fp->Opcode = FP_OPCODE_ABS; + break; + + case OP_FLR_SAT: + fp->Saturate = 1; + case OP_FLR: + fp->Opcode = FP_OPCODE_FLR; + break; + + case OP_FRC_SAT: + fp->Saturate = 1; + case OP_FRC: + fp->Opcode = FP_OPCODE_FRC; + break; + + case OP_LIT_SAT: + fp->Saturate = 1; + case OP_LIT: + fp->Opcode = FP_OPCODE_LIT; + break; + + case OP_MOV_SAT: + fp->Saturate = 1; + case OP_MOV: + fp->Opcode = FP_OPCODE_MOV; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + + fp->SrcReg[0].Abs = GL_FALSE; + fp->SrcReg[0].NegateAbs = GL_FALSE; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[0].File, + &fp->SrcReg[0].Index, &fp->SrcReg[0].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[0].Swizzle[b] = swz[b]; + break; + + case OP_ALU_SCALAR: + switch (code) { + case OP_COS_SAT: + fp->Saturate = 1; + case OP_COS: + fp->Opcode = FP_OPCODE_COS; + break; + + case OP_EX2_SAT: + fp->Saturate = 1; + case OP_EX2: + fp->Opcode = FP_OPCODE_EX2; + break; + + case OP_LG2_SAT: + fp->Saturate = 1; + case OP_LG2: + fp->Opcode = FP_OPCODE_LG2; + break; + + case OP_RCP_SAT: + fp->Saturate = 1; + case OP_RCP: + fp->Opcode = FP_OPCODE_RCP; + break; + + case OP_RSQ_SAT: + fp->Saturate = 1; + case OP_RSQ: + fp->Opcode = FP_OPCODE_RSQ; + break; + + case OP_SIN_SAT: + fp->Saturate = 1; + case OP_SIN: + fp->Opcode = FP_OPCODE_SIN; + break; + + case OP_SCS_SAT: + fp->Saturate = 1; + case OP_SCS: + + fp->Opcode = FP_OPCODE_SCS; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + fp->SrcReg[0].Abs = GL_FALSE; + fp->SrcReg[0].NegateAbs = GL_FALSE; + if (parse_scalar_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[0].File, + &fp->SrcReg[0].Index, &fp->SrcReg[0].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[0].Swizzle[b] = swz[b]; + break; + + case OP_ALU_BINSC: + switch (code) { + case OP_POW_SAT: + fp->Saturate = 1; + case OP_POW: + fp->Opcode = FP_OPCODE_POW; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 2; a++) { + fp->SrcReg[a].Abs = GL_FALSE; + fp->SrcReg[a].NegateAbs = GL_FALSE; + if (parse_scalar_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[a].File, + &fp->SrcReg[a].Index, &fp->SrcReg[a].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[a].Swizzle[b] = swz[b]; + } + break; + + + case OP_ALU_BIN: + switch (code) { + case OP_ADD_SAT: + fp->Saturate = 1; + case OP_ADD: + fp->Opcode = FP_OPCODE_ADD; + break; + + case OP_DP3_SAT: + fp->Saturate = 1; + case OP_DP3: + fp->Opcode = FP_OPCODE_DP3; + break; + + case OP_DP4_SAT: + fp->Saturate = 1; + case OP_DP4: + fp->Opcode = FP_OPCODE_DP4; + break; + + case OP_DPH_SAT: + fp->Saturate = 1; + case OP_DPH: + fp->Opcode = FP_OPCODE_DPH; + break; + + case OP_DST_SAT: + fp->Saturate = 1; + case OP_DST: + fp->Opcode = FP_OPCODE_DST; + break; + + case OP_MAX_SAT: + fp->Saturate = 1; + case OP_MAX: + fp->Opcode = FP_OPCODE_MAX; + break; + + case OP_MIN_SAT: + fp->Saturate = 1; + case OP_MIN: + fp->Opcode = FP_OPCODE_MIN; + break; + + case OP_MUL_SAT: + fp->Saturate = 1; + case OP_MUL: + fp->Opcode = FP_OPCODE_MUL; + break; + + case OP_SGE_SAT: + fp->Saturate = 1; + case OP_SGE: + fp->Opcode = FP_OPCODE_SGE; + break; + + case OP_SLT_SAT: + fp->Saturate = 1; + case OP_SLT: + fp->Opcode = FP_OPCODE_SLT; + break; + + case OP_SUB_SAT: + fp->Saturate = 1; + case OP_SUB: + fp->Opcode = FP_OPCODE_SUB; + break; + + case OP_XPD_SAT: + fp->Saturate = 1; + case OP_XPD: + fp->Opcode = FP_OPCODE_XPD; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 2; a++) { + fp->SrcReg[a].Abs = GL_FALSE; + fp->SrcReg[a].NegateAbs = GL_FALSE; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[a].File, + &fp->SrcReg[a].Index, &fp->SrcReg[a].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[a].Swizzle[b] = swz[b]; + } + break; + + case OP_ALU_TRI: + switch (code) { + case OP_CMP_SAT: + fp->Saturate = 1; + case OP_CMP: + fp->Opcode = FP_OPCODE_CMP; + break; + + case OP_LRP_SAT: + fp->Saturate = 1; + case OP_LRP: + fp->Opcode = FP_OPCODE_LRP; + break; + + case OP_MAD_SAT: + fp->Saturate = 1; + case OP_MAD: + fp->Opcode = FP_OPCODE_MAD; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 3; a++) { + fp->SrcReg[a].Abs = GL_FALSE; + fp->SrcReg[a].NegateAbs = GL_FALSE; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[a].File, + &fp->SrcReg[a].Index, &fp->SrcReg[a].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[a].Swizzle[b] = swz[b]; + } + break; + + case OP_ALU_SWZ: + switch (code) { + case OP_SWZ_SAT: + fp->Saturate = 1; + case OP_SWZ: + fp->Opcode = FP_OPCODE_SWZ; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + + if (parse_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[0].File, + &fp->SrcReg[0].Index, &rel)) + return 1; + parse_extended_swizzle_mask (inst, swz, + &fp->SrcReg[0].NegateBase); + for (b=0; b<4; b++) + fp->SrcReg[0].Swizzle[b] = swz[b]; + break; + + case OP_TEX_SAMPLE: + switch (code) { + case OP_TEX_SAT: + fp->Saturate = 1; + case OP_TEX: + fp->Opcode = FP_OPCODE_TEX; + break; + + case OP_TXP_SAT: + fp->Saturate = 1; + case OP_TXP: + fp->Opcode = FP_OPCODE_TXP; + break; + + case OP_TXB_SAT: + + fp->Saturate = 1; + case OP_TXB: + fp->Opcode = FP_OPCODE_TXB; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->DstReg.File, + &fp->DstReg.Index, fp->DstReg.WriteMask)) + return 1; + fp->SrcReg[0].Abs = GL_FALSE; + fp->SrcReg[0].NegateAbs = GL_FALSE; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[0].File, + &fp->SrcReg[0].Index, &fp->SrcReg[0].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[0].Swizzle[b] = swz[b]; + + /* texImageUnit */ + if (parse_texcoord_num (ctx, inst, Program, &texcoord)) + return 1; + fp->TexSrcUnit = texcoord; + + /* texTarget */ + switch (*(*inst)++) { + case TEXTARGET_1D: + fp->TexSrcBit = TEXTURE_1D_BIT; + break; + case TEXTARGET_2D: + fp->TexSrcBit = TEXTURE_2D_BIT; + break; + case TEXTARGET_3D: + fp->TexSrcBit = TEXTURE_3D_BIT; + break; + case TEXTARGET_RECT: + fp->TexSrcBit = TEXTURE_RECT_BIT; + break; + case TEXTARGET_CUBE: + fp->TexSrcBit = TEXTURE_CUBE_BIT; + break; + case TEXTARGET_SHADOW1D: + case TEXTARGET_SHADOW2D: + case TEXTARGET_SHADOWRECT: + /* TODO ARB_fragment_program_shadow code */ + break; + } + Program->TexturesUsed[texcoord] |= fp->TexSrcBit; + break; + + case OP_TEX_KIL: + fp->Opcode = FP_OPCODE_KIL; + fp->SrcReg[0].Abs = GL_FALSE; + fp->SrcReg[0].NegateAbs = GL_FALSE; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & fp->SrcReg[0].File, + &fp->SrcReg[0].Index, &fp->SrcReg[0].NegateBase, + swz, &rel)) + return 1; + for (b=0; b<4; b++) + fp->SrcReg[0].Swizzle[b] = swz[b]; + break; + } + + return 0; +} + +/** + * This is a big mother that handles getting opcodes into the instruction + * and handling the src & dst registers for vertex program instructions + */ +static GLuint +parse_vp_instruction (GLcontext * ctx, GLubyte ** inst, + struct var_cache **vc_head, struct arb_program *Program, + struct vp_instruction *vp) +{ + GLint a; + GLubyte type, code; + + /* OP_ALU_{ARL, VECTOR, SCALAR, BINSC, BIN, TRI, SWZ} */ + type = *(*inst)++; + + /* The actual opcode name */ + code = *(*inst)++; + + /* Record the position in the program string for debugging */ + vp->StringPos = Program->Position; + + vp->SrcReg[0].RelAddr = vp->SrcReg[1].RelAddr = vp->SrcReg[2].RelAddr = 0; + + for (a = 0; a < 4; a++) { + vp->SrcReg[0].Swizzle[a] = a; + vp->SrcReg[1].Swizzle[a] = a; + vp->SrcReg[2].Swizzle[a] = a; + vp->DstReg.WriteMask[a] = 1; + } + + switch (type) { + /* XXX: */ + case OP_ALU_ARL: + vp->Opcode = VP_OPCODE_ARL; + + /* Remember to set SrcReg.RelAddr; */ + + /* Get the masked address register [dst] */ + if (parse_masked_address_reg + (ctx, inst, vc_head, Program, &vp->DstReg.Index, + vp->DstReg.WriteMask)) + return 1; + vp->DstReg.File = PROGRAM_ADDRESS; + + /* Get a scalar src register */ + if (parse_scalar_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[0].File, + &vp->SrcReg[0].Index, &vp->SrcReg[0].Negate, + vp->SrcReg[0].Swizzle, &vp->SrcReg[0].RelAddr)) + return 1; + + break; + + case OP_ALU_VECTOR: + switch (code) { + case OP_ABS: + vp->Opcode = VP_OPCODE_ABS; + break; + case OP_FLR: + vp->Opcode = VP_OPCODE_FLR; + break; + case OP_FRC: + vp->Opcode = VP_OPCODE_FRC; + break; + case OP_LIT: + vp->Opcode = VP_OPCODE_LIT; + break; + case OP_MOV: + vp->Opcode = VP_OPCODE_MOV; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[0].File, + &vp->SrcReg[0].Index, &vp->SrcReg[0].Negate, + vp->SrcReg[0].Swizzle, &vp->SrcReg[0].RelAddr)) + return 1; + break; + + case OP_ALU_SCALAR: + switch (code) { + case OP_EX2: + vp->Opcode = VP_OPCODE_EX2; + break; + case OP_EXP: + vp->Opcode = VP_OPCODE_EXP; + break; + case OP_LG2: + vp->Opcode = VP_OPCODE_LG2; + break; + case OP_LOG: + vp->Opcode = VP_OPCODE_LOG; + break; + case OP_RCP: + vp->Opcode = VP_OPCODE_RCP; + break; + case OP_RSQ: + vp->Opcode = VP_OPCODE_RSQ; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + if (parse_scalar_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[0].File, + &vp->SrcReg[0].Index, &vp->SrcReg[0].Negate, + vp->SrcReg[0].Swizzle, &vp->SrcReg[0].RelAddr)) + return 1; + break; + + case OP_ALU_BINSC: + switch (code) { + case OP_POW: + vp->Opcode = VP_OPCODE_POW; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 2; a++) { + if (parse_scalar_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[a].File, + &vp->SrcReg[a].Index, &vp->SrcReg[a].Negate, + vp->SrcReg[a].Swizzle, &vp->SrcReg[a].RelAddr)) + return 1; + } + break; + + case OP_ALU_BIN: + switch (code) { + case OP_ADD: + vp->Opcode = VP_OPCODE_ADD; + break; + case OP_DP3: + vp->Opcode = VP_OPCODE_DP3; + break; + case OP_DP4: + vp->Opcode = VP_OPCODE_DP4; + break; + case OP_DPH: + vp->Opcode = VP_OPCODE_DPH; + break; + case OP_DST: + vp->Opcode = VP_OPCODE_DST; + break; + case OP_MAX: + vp->Opcode = VP_OPCODE_MAX; + break; + case OP_MIN: + vp->Opcode = VP_OPCODE_MIN; + break; + case OP_MUL: + vp->Opcode = VP_OPCODE_MUL; + break; + case OP_SGE: + vp->Opcode = VP_OPCODE_SGE; + break; + case OP_SLT: + vp->Opcode = VP_OPCODE_SLT; + break; + case OP_SUB: + vp->Opcode = VP_OPCODE_SUB; + break; + case OP_XPD: + vp->Opcode = VP_OPCODE_XPD; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 2; a++) { + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[a].File, + &vp->SrcReg[a].Index, &vp->SrcReg[a].Negate, + vp->SrcReg[a].Swizzle, &vp->SrcReg[a].RelAddr)) + return 1; + } + break; + + case OP_ALU_TRI: + switch (code) { + case OP_MAD: + vp->Opcode = VP_OPCODE_MAD; + break; + } + + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + for (a = 0; a < 3; a++) { + if (parse_vector_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[a].File, + &vp->SrcReg[a].Index, &vp->SrcReg[a].Negate, + vp->SrcReg[a].Swizzle, &vp->SrcReg[a].RelAddr)) + return 1; + } + break; + + case OP_ALU_SWZ: + switch (code) { + case OP_SWZ: + vp->Opcode = VP_OPCODE_SWZ; + break; + } + if (parse_masked_dst_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->DstReg.File, + &vp->DstReg.Index, vp->DstReg.WriteMask)) + return 1; + + if (parse_src_reg + (ctx, inst, vc_head, Program, (GLint *) & vp->SrcReg[0].File, + &vp->SrcReg[0].Index, &vp->SrcReg[0].RelAddr)) + return 1; + parse_extended_swizzle_mask (inst, vp->SrcReg[0].Swizzle, + &vp->SrcReg[0].Negate); + break; + } + return 0; +} + +#if DEBUG_PARSING + +static GLvoid +print_state_token (GLint token) +{ + switch (token) { + case STATE_MATERIAL: + fprintf (stderr, "STATE_MATERIAL "); + break; + case STATE_LIGHT: + fprintf (stderr, "STATE_LIGHT "); + break; + + case STATE_LIGHTMODEL_AMBIENT: + fprintf (stderr, "STATE_AMBIENT "); + break; + + case STATE_LIGHTMODEL_SCENECOLOR: + fprintf (stderr, "STATE_SCENECOLOR "); + break; + + case STATE_LIGHTPROD: + fprintf (stderr, "STATE_LIGHTPROD "); + break; + + case STATE_TEXGEN: + fprintf (stderr, "STATE_TEXGEN "); + break; + + case STATE_FOG_COLOR: + fprintf (stderr, "STATE_FOG_COLOR "); + break; + + case STATE_FOG_PARAMS: + fprintf (stderr, "STATE_FOG_PARAMS "); + break; + + case STATE_CLIPPLANE: + fprintf (stderr, "STATE_CLIPPLANE "); + break; + + case STATE_POINT_SIZE: + fprintf (stderr, "STATE_POINT_SIZE "); + break; + + case STATE_POINT_ATTENUATION: + fprintf (stderr, "STATE_ATTENUATION "); + break; + + case STATE_MATRIX: + fprintf (stderr, "STATE_MATRIX "); + break; + + case STATE_MODELVIEW: + fprintf (stderr, "STATE_MODELVIEW "); + break; + + case STATE_PROJECTION: + fprintf (stderr, "STATE_PROJECTION "); + break; + + case STATE_MVP: + fprintf (stderr, "STATE_MVP "); + break; + + case STATE_TEXTURE: + fprintf (stderr, "STATE_TEXTURE "); + break; + + case STATE_PROGRAM: + fprintf (stderr, "STATE_PROGRAM "); + break; + + case STATE_MATRIX_INVERSE: + fprintf (stderr, "STATE_INVERSE "); + break; + + case STATE_MATRIX_TRANSPOSE: + fprintf (stderr, "STATE_TRANSPOSE "); + break; + + case STATE_MATRIX_INVTRANS: + fprintf (stderr, "STATE_INVTRANS "); + break; + + case STATE_AMBIENT: + fprintf (stderr, "STATE_AMBIENT "); + break; + + case STATE_DIFFUSE: + fprintf (stderr, "STATE_DIFFUSE "); + break; + + case STATE_SPECULAR: + fprintf (stderr, "STATE_SPECULAR "); + break; + + case STATE_EMISSION: + fprintf (stderr, "STATE_EMISSION "); + break; + + case STATE_SHININESS: + fprintf (stderr, "STATE_SHININESS "); + break; + + case STATE_HALF: + fprintf (stderr, "STATE_HALF "); + break; + + case STATE_POSITION: + fprintf (stderr, "STATE_POSITION "); + break; + + case STATE_ATTENUATION: + fprintf (stderr, "STATE_ATTENUATION "); + break; + + case STATE_SPOT_DIRECTION: + fprintf (stderr, "STATE_DIRECTION "); + break; + + case STATE_TEXGEN_EYE_S: + fprintf (stderr, "STATE_TEXGEN_EYE_S "); + break; + + case STATE_TEXGEN_EYE_T: + fprintf (stderr, "STATE_TEXGEN_EYE_T "); + break; + + case STATE_TEXGEN_EYE_R: + fprintf (stderr, "STATE_TEXGEN_EYE_R "); + break; + + case STATE_TEXGEN_EYE_Q: + fprintf (stderr, "STATE_TEXGEN_EYE_Q "); + break; + + case STATE_TEXGEN_OBJECT_S: + fprintf (stderr, "STATE_TEXGEN_EYE_S "); + break; + + case STATE_TEXGEN_OBJECT_T: + fprintf (stderr, "STATE_TEXGEN_OBJECT_T "); + break; + + case STATE_TEXGEN_OBJECT_R: + fprintf (stderr, "STATE_TEXGEN_OBJECT_R "); + break; + + case STATE_TEXGEN_OBJECT_Q: + fprintf (stderr, "STATE_TEXGEN_OBJECT_Q "); + break; + + case STATE_TEXENV_COLOR: + fprintf (stderr, "STATE_TEXENV_COLOR "); + break; + + case STATE_DEPTH_RANGE: + fprintf (stderr, "STATE_DEPTH_RANGE "); + break; + + case STATE_VERTEX_PROGRAM: + fprintf (stderr, "STATE_VERTEX_PROGRAM "); + break; + + case STATE_FRAGMENT_PROGRAM: + fprintf (stderr, "STATE_FRAGMENT_PROGRAM "); + break; + + case STATE_ENV: + fprintf (stderr, "STATE_ENV "); + break; + + case STATE_LOCAL: + fprintf (stderr, "STATE_LOCAL "); + break; + + } + fprintf (stderr, "[%d] ", token); +} + + +static GLvoid +debug_variables (GLcontext * ctx, struct var_cache *vc_head, + struct arb_program *Program) +{ + struct var_cache *vc; + GLint a, b; + + fprintf (stderr, "debug_variables, vc_head: %x\n", vc_head); + + /* First of all, print out the contents of the var_cache */ + vc = vc_head; + while (vc) { + fprintf (stderr, "[%x]\n", vc); + switch (vc->type) { + case vt_none: + fprintf (stderr, "UNDEFINED %s\n", vc->name); + break; + case vt_attrib: + fprintf (stderr, "ATTRIB %s\n", vc->name); + fprintf (stderr, " binding: 0x%x\n", vc->attrib_binding); + break; + case vt_param: + fprintf (stderr, "PARAM %s begin: %d len: %d\n", vc->name, + vc->param_binding_begin, vc->param_binding_length); + b = vc->param_binding_begin; + for (a = 0; a < vc->param_binding_length; a++) { + fprintf (stderr, "%s\n", + Program->Parameters->Parameters[a + b].Name); + if (Program->Parameters->Parameters[a + b].Type == STATE) { + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[0]); + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[1]); + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[2]); + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[3]); + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[4]); + print_state_token (Program->Parameters->Parameters[a + b]. + StateIndexes[5]); + } + else + fprintf (stderr, "%f %f %f %f\n", + Program->Parameters->Parameters[a + b].Values[0], + Program->Parameters->Parameters[a + b].Values[1], + Program->Parameters->Parameters[a + b].Values[2], + Program->Parameters->Parameters[a + b].Values[3]); + } + break; + case vt_temp: + fprintf (stderr, "TEMP %s\n", vc->name); + fprintf (stderr, " binding: 0x%x\n", vc->temp_binding); + break; + case vt_output: + fprintf (stderr, "OUTPUT %s\n", vc->name); + fprintf (stderr, " binding: 0x%x\n", vc->output_binding); + break; + case vt_alias: + fprintf (stderr, "ALIAS %s\n", vc->name); + fprintf (stderr, " binding: 0x%x (%s)\n", + vc->alias_binding, vc->alias_binding->name); + break; + } + vc = vc->next; + } +} + +#endif + + +/** + * The main loop for parsing a fragment or vertex program + * + * \return 0 on sucess, 1 on error + */ +static GLint +parse_arb_program (GLcontext * ctx, GLubyte * inst, struct var_cache **vc_head, + struct arb_program *Program) +{ + GLint err = 0; + + Program->MajorVersion = (GLuint) * inst++; + Program->MinorVersion = (GLuint) * inst++; + + while (*inst != END) { + switch (*inst++) { + + case OPTION: + switch (*inst++) { + case ARB_PRECISION_HINT_FASTEST: + Program->PrecisionOption = GL_FASTEST; + break; + + case ARB_PRECISION_HINT_NICEST: + Program->PrecisionOption = GL_NICEST; + break; + + case ARB_FOG_EXP: + Program->FogOption = GL_EXP; + break; + + case ARB_FOG_EXP2: + Program->FogOption = GL_EXP2; + break; + + case ARB_FOG_LINEAR: + Program->FogOption = GL_LINEAR; + break; + + case ARB_POSITION_INVARIANT: + if (Program->Base.Target == GL_VERTEX_PROGRAM_ARB) + Program->HintPositionInvariant = 1; + break; + + case ARB_FRAGMENT_PROGRAM_SHADOW: + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + /* TODO ARB_fragment_program_shadow code */ + } + break; + } + break; + + case INSTRUCTION: + Program->Position = parse_position (&inst); + + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + + /* Check the instruction count + * XXX: Does END count as an instruction? + */ + if (Program->Base.NumInstructions+1 == MAX_NV_FRAGMENT_PROGRAM_INSTRUCTIONS) { + _mesa_set_program_error (ctx, Program->Position, + "Max instruction count exceeded!"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Max instruction count exceeded!"); + } + + /* Realloc Program->FPInstructions */ + Program->FPInstructions = + (struct fp_instruction *) _mesa_realloc (Program->FPInstructions, + Program->Base.NumInstructions*sizeof(struct fp_instruction), + (Program->Base.NumInstructions+1)*sizeof (struct fp_instruction)); + + /* parse the current instruction */ + err = parse_fp_instruction (ctx, &inst, vc_head, Program, + &Program->FPInstructions[Program->Base.NumInstructions]); + + } + else { + /* Check the instruction count + * XXX: Does END count as an instruction? + */ + if (Program->Base.NumInstructions+1 == MAX_NV_VERTEX_PROGRAM_INSTRUCTIONS) { + _mesa_set_program_error (ctx, Program->Position, + "Max instruction count exceeded!"); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Max instruction count exceeded!"); + } + + /* Realloc Program->VPInstructions */ + Program->VPInstructions = + (struct vp_instruction *) _mesa_realloc (Program->VPInstructions, + Program->Base.NumInstructions*sizeof(struct vp_instruction), + (Program->Base.NumInstructions +1)*sizeof(struct vp_instruction)); + + /* parse the current instruction */ + err = parse_vp_instruction (ctx, &inst, vc_head, Program, + &Program->VPInstructions[Program->Base.NumInstructions]); + } + + /* increment Program->Base.NumInstructions */ + Program->Base.NumInstructions++; + break; + + case DECLARATION: + err = parse_declaration (ctx, &inst, vc_head, Program); + break; + + default: + break; + } + + if (err) + break; + } + + /* Finally, tag on an OPCODE_END instruction */ + if (Program->Base.Target == GL_FRAGMENT_PROGRAM_ARB) { + Program->FPInstructions = + (struct fp_instruction *) _mesa_realloc (Program->FPInstructions, + Program->Base.NumInstructions*sizeof(struct fp_instruction), + (Program->Base.NumInstructions+1)*sizeof(struct fp_instruction)); + + Program->FPInstructions[Program->Base.NumInstructions].Opcode = FP_OPCODE_END; + /* YYY Wrong Position in program, whatever, at least not random -> crash + Program->Position = parse_position (&inst); + */ + Program->FPInstructions[Program->Base.NumInstructions].StringPos = Program->Position; + } + else { + Program->VPInstructions = + (struct vp_instruction *) _mesa_realloc (Program->VPInstructions, + Program->Base.NumInstructions*sizeof(struct vp_instruction), + (Program->Base.NumInstructions+1)*sizeof(struct vp_instruction)); + + Program->VPInstructions[Program->Base.NumInstructions].Opcode = VP_OPCODE_END; + /* YYY Wrong Position in program, whatever, at least not random -> crash + Program->Position = parse_position (&inst); + */ + Program->VPInstructions[Program->Base.NumInstructions].StringPos = Program->Position; + } + + /* increment Program->Base.NumInstructions */ + Program->Base.NumInstructions++; + + return err; +} + +/* XXX temporary */ +__extension__ static char core_grammar_text[] = +#include "grammar_syn.h" +; + +static int set_reg8 (GLcontext *ctx, grammar id, const byte *name, byte value) +{ + char error_msg[300]; + GLint error_pos; + + if (grammar_set_reg8 (id, name, value)) + return 0; + + grammar_get_last_error ((byte *) error_msg, 300, &error_pos); + _mesa_set_program_error (ctx, error_pos, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, "Grammar Register Error"); + return 1; +} + +static int extension_is_supported (const GLubyte *ext) +{ + const GLubyte *extensions = GL_CALL(GetString)(GL_EXTENSIONS); + const GLubyte *end = extensions + _mesa_strlen ((const char *) extensions); + const GLint ext_len = _mesa_strlen ((const char *) ext); + + while (extensions < end) + { + const GLubyte *name_end = (const GLubyte *) strchr ((const char *) extensions, ' '); + if (name_end == NULL) + name_end = end; + if (name_end - extensions == ext_len && _mesa_strncmp ((const char *) ext, + (const char *) extensions, ext_len) == 0) + return 1; + extensions = name_end + 1; + } + + return 0; +} + +static int enable_ext (GLcontext *ctx, grammar id, const byte *name, const byte *extname) +{ + if (extension_is_supported (extname)) + if (set_reg8 (ctx, id, name, 0x01)) + return 1; + return 0; +} + +/** + * This kicks everything off. + * + * \param ctx - The GL Context + * \param str - The program string + * \param len - The program string length + * \param Program - The arb_program struct to return all the parsed info in + * \return 0 on sucess, 1 on error + */ +GLuint +_mesa_parse_arb_program (GLcontext * ctx, const GLubyte * str, GLsizei len, + struct arb_program * program) +{ + GLint a, err, error_pos; + char error_msg[300]; + GLuint parsed_len; + struct var_cache *vc_head; + grammar arbprogram_syn_id; + GLubyte *parsed, *inst; + GLubyte *strz = NULL; + static int arbprogram_syn_is_ok = 0; /* XXX temporary */ + + /* Reset error state */ + _mesa_set_program_error(ctx, -1, NULL); + +#if DEBUG_PARSING + fprintf (stderr, "Loading grammar text!\n"); +#endif + + /* check if the arb_grammar_text (arbprogram.syn) is syntactically correct */ + if (!arbprogram_syn_is_ok) { + grammar grammar_syn_id; + GLint err; + GLuint parsed_len; + byte *parsed; + + grammar_syn_id = grammar_load_from_text ((byte *) core_grammar_text); + if (grammar_syn_id == 0) { + grammar_get_last_error ((byte *) error_msg, 300, &error_pos); + _mesa_set_program_error (ctx, error_pos, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Error loading grammar rule set"); + return 1; + } + + err = grammar_check (grammar_syn_id, (byte *) arb_grammar_text, &parsed, &parsed_len); + + /* NOTE: we cant destroy grammar_syn_id right here because grammar_destroy() can + reset the last error + */ + + if (err == 0) { + grammar_get_last_error ((byte *) error_msg, 300, &error_pos); + _mesa_set_program_error (ctx, error_pos, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, "Error loading grammar rule set"); + + grammar_destroy (grammar_syn_id); + return 1; + } + + grammar_destroy (grammar_syn_id); + + arbprogram_syn_is_ok = 1; + } + + /* create the grammar object */ + arbprogram_syn_id = grammar_load_from_text ((byte *) arb_grammar_text); + if (arbprogram_syn_id == 0) { + grammar_get_last_error ((GLubyte *) error_msg, 300, &error_pos); + _mesa_set_program_error (ctx, error_pos, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, + "Error loading grammer rule set"); + return 1; + } + + /* Set program_target register value */ + if (set_reg8 (ctx, arbprogram_syn_id, (byte *) "program_target", + program->Base.Target == GL_FRAGMENT_PROGRAM_ARB ? 0x10 : 0x20)) { + grammar_destroy (arbprogram_syn_id); + return 1; + } + + /* Enable all active extensions */ + if (enable_ext (ctx, arbprogram_syn_id, + (byte *) "vertex_blend", (byte *) "GL_ARB_vertex_blend") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "vertex_blend", (byte *) "GL_EXT_vertex_weighting") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "matrix_palette", (byte *) "GL_ARB_matrix_palette") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "point_parameters", (byte *) "GL_ARB_point_parameters") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "point_parameters", (byte *) "GL_EXT_point_parameters") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "secondary_color", (byte *) "GL_EXT_secondary_color") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "fog_coord", (byte *) "GL_EXT_fog_coord") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "texture_rectangle", (byte *) "GL_ARB_texture_rectangle") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "texture_rectangle", (byte *) "GL_EXT_texture_rectangle") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "texture_rectangle", (byte *) "GL_NV_texture_rectangle") || + enable_ext (ctx, arbprogram_syn_id, + (byte *) "fragment_program_shadow", (byte *) "GL_ARB_fragment_program_shadow")) { + grammar_destroy (arbprogram_syn_id); + return 1; + } + + /* check for NULL character occurences */ + { + int i; + for (i = 0; i < len; i++) + if (str[i] == '\0') { + _mesa_set_program_error (ctx, i, "invalid character"); + _mesa_error (ctx, GL_INVALID_OPERATION, "Lexical Error"); + + grammar_destroy (arbprogram_syn_id); + return 1; + } + } + + /* copy the program string to a null-terminated string */ + /* XXX should I check for NULL from malloc()? */ + strz = (GLubyte *) _mesa_malloc (len + 1); + _mesa_memcpy (strz, str, len); + strz[len] = '\0'; + +#if DEBUG_PARSING + printf ("Checking Grammar!\n"); +#endif + err = grammar_check (arbprogram_syn_id, strz, &parsed, &parsed_len); + + /* Syntax parse error */ + if (err == 0) { + _mesa_free (strz); + grammar_get_last_error ((GLubyte *) error_msg, 300, &error_pos); + _mesa_set_program_error (ctx, error_pos, error_msg); + _mesa_error (ctx, GL_INVALID_OPERATION, "glProgramStringARB(syntax error)"); + + /* useful for debugging */ + if (0) { + int line, col; + char *s; + printf("Program: %s\n", (char *) strz); + printf("Error Pos: %d\n", ctx->Program.ErrorPos); + s = (char *) _mesa_find_line_column(strz, strz+ctx->Program.ErrorPos, &line, &col); + printf("line %d col %d: %s\n", line, col, s); + } + + grammar_destroy (arbprogram_syn_id); + return 1; + } + +#if DEBUG_PARSING + printf ("Destroying grammer dict [parse retval: %d]\n", err); +#endif + grammar_destroy (arbprogram_syn_id); + + /* Initialize the arb_program struct */ + program->Base.String = strz; + program->Base.NumInstructions = + program->Base.NumTemporaries = + program->Base.NumParameters = + program->Base.NumAttributes = program->Base.NumAddressRegs = 0; + program->Parameters = _mesa_new_parameter_list (); + program->InputsRead = 0; + program->OutputsWritten = 0; + program->Position = 0; + program->MajorVersion = program->MinorVersion = 0; + program->PrecisionOption = GL_DONT_CARE; + program->FogOption = GL_NONE; + program->HintPositionInvariant = GL_FALSE; + for (a = 0; a < MAX_TEXTURE_IMAGE_UNITS; a++) + program->TexturesUsed[a] = 0; + program->NumAluInstructions = + program->NumTexInstructions = + program->NumTexIndirections = 0; + + program->FPInstructions = NULL; + program->VPInstructions = NULL; + + vc_head = NULL; + err = 0; + + /* Start examining the tokens in the array */ + inst = parsed; + + /* Check the grammer rev */ + if (*inst++ != REVISION) { + _mesa_set_program_error (ctx, 0, "Grammar version mismatch"); + _mesa_error (ctx, GL_INVALID_OPERATION, "glProgramStringARB(Grammar verison mismatch)"); + err = 1; + } + else { + switch (*inst++) { + case FRAGMENT_PROGRAM: + program->Base.Target = GL_FRAGMENT_PROGRAM_ARB; + break; + + case VERTEX_PROGRAM: + program->Base.Target = GL_VERTEX_PROGRAM_ARB; + break; + } + + err = parse_arb_program (ctx, inst, &vc_head, program); +#if DEBUG_PARSING + fprintf (stderr, "Symantic analysis returns %d [1 is bad!]\n", err); +#endif + } + + /*debug_variables(ctx, vc_head, program); */ + + /* We're done with the parsed binary array */ + var_cache_destroy (&vc_head); + + _mesa_free (parsed); +#if DEBUG_PARSING + printf ("_mesa_parse_arb_program() done\n"); +#endif + return err; +} diff --git a/src/mesa/shader/arbprogparse.h b/src/mesa/shader/arbprogparse.h new file mode 100644 index 0000000..a7b97e9 --- /dev/null +++ b/src/mesa/shader/arbprogparse.h @@ -0,0 +1,74 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef ARBPROGPARSE_H +#define ARBPROGPARSE_H + +#include "context.h" +#include "mtypes.h" +#include "nvvertprog.h" +#include "nvfragprog.h" + +/** + * This is basically a union of the vertex_program and fragment_program + * structs that we can use to parse the program into + * + * XXX: this should go into mtypes.h? + */ +struct arb_program +{ + struct program Base; + struct program_parameter_list *Parameters; + GLuint InputsRead; + GLuint OutputsWritten; + + GLuint Position; /* Just used for error reporting while parsing */ + GLuint MajorVersion; + GLuint MinorVersion; + + /* ARB_vertex_program specifics */ + struct vp_instruction *VPInstructions; + + /* Options currently recognized by the parser */ + /* ARB_fp */ + GLenum PrecisionOption; /* GL_DONT_CARE, GL_NICEST or GL_FASTEST */ + GLenum FogOption; /* GL_NONE, GL_LINEAR, GL_EXP or GL_EXP2 */ + + /* ARB_fp & _vp */ + GLboolean HintPositionInvariant; + + /* ARB_fragment_program sepecifics */ + struct fp_instruction *FPInstructions; + GLuint TexturesUsed[MAX_TEXTURE_IMAGE_UNITS]; + GLuint NumAluInstructions; + GLuint NumTexInstructions; + GLuint NumTexIndirections; +}; + +extern GLuint +_mesa_parse_arb_program( GLcontext *ctx, const GLubyte *str, GLsizei len, + struct arb_program *Program ); + +#endif diff --git a/src/mesa/shader/arbprogram.c b/src/mesa/shader/arbprogram.c new file mode 100644 index 0000000..d9b1b1d --- /dev/null +++ b/src/mesa/shader/arbprogram.c @@ -0,0 +1,721 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file arbprogram.c + * ARB_vertex/fragment_program state management functions. + * \author Brian Paul + */ + + +#include "glheader.h" +#include "arbprogram.h" +#include "arbfragparse.h" +#include "arbvertparse.h" +#include "context.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvprogram.h" +#include "nvfragparse.h" +#include "nvfragprog.h" +#include "nvvertparse.h" +#include "nvvertprog.h" + + +void GLAPIENTRY +_mesa_EnableVertexAttribArrayARB(GLuint index) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index >= ctx->Const.MaxVertexProgramAttribs) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glEnableVertexAttribArrayARB(index)"); + return; + } + + FLUSH_VERTICES(ctx, _NEW_ARRAY); + ctx->Array.VertexAttrib[index].Enabled = GL_TRUE; + ctx->Array._Enabled |= _NEW_ARRAY_ATTRIB(index); + ctx->Array.NewState |= _NEW_ARRAY_ATTRIB(index); +} + + +void GLAPIENTRY +_mesa_DisableVertexAttribArrayARB(GLuint index) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index >= ctx->Const.MaxVertexProgramAttribs) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glEnableVertexAttribArrayARB(index)"); + return; + } + + FLUSH_VERTICES(ctx, _NEW_ARRAY); + ctx->Array.VertexAttrib[index].Enabled = GL_FALSE; + ctx->Array._Enabled &= ~_NEW_ARRAY_ATTRIB(index); + ctx->Array.NewState |= _NEW_ARRAY_ATTRIB(index); +} + + +void GLAPIENTRY +_mesa_GetVertexAttribdvARB(GLuint index, GLenum pname, GLdouble *params) +{ + GLfloat fparams[4]; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + _mesa_GetVertexAttribfvARB(index, pname, fparams); + if (ctx->ErrorValue == GL_NO_ERROR) { + if (pname == GL_CURRENT_VERTEX_ATTRIB_ARB) { + COPY_4V(params, fparams); + } + else { + params[0] = fparams[0]; + } + } +} + + +void GLAPIENTRY +_mesa_GetVertexAttribfvARB(GLuint index, GLenum pname, GLfloat *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index == 0 || index >= VERT_ATTRIB_MAX) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribfvARB(index)"); + return; + } + + switch (pname) { + case GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Enabled; + break; + case GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Size; + break; + case GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Stride; + break; + case GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Type; + break; + case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB: + params[0] = ctx->Array.VertexAttrib[index].Normalized; + break; + case GL_CURRENT_VERTEX_ATTRIB_ARB: + FLUSH_CURRENT(ctx, 0); + COPY_4V(params, ctx->Current.Attrib[index]); + break; + case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB: + if (!ctx->Extensions.ARB_vertex_buffer_object) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribfvARB(pname)"); + return; + } + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].BufferObj->Name; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribfvARB(pname)"); + return; + } +} + + +void GLAPIENTRY +_mesa_GetVertexAttribivARB(GLuint index, GLenum pname, GLint *params) +{ + GLfloat fparams[4]; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + _mesa_GetVertexAttribfvARB(index, pname, fparams); + if (ctx->ErrorValue == GL_NO_ERROR) { + if (pname == GL_CURRENT_VERTEX_ATTRIB_ARB) { + COPY_4V_CAST(params, fparams, GLint); /* float to int */ + } + else { + params[0] = (GLint) fparams[0]; + } + } +} + + +void GLAPIENTRY +_mesa_GetVertexAttribPointervARB(GLuint index, GLenum pname, GLvoid **pointer) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index >= ctx->Const.MaxVertexProgramAttribs) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribPointerARB(index)"); + return; + } + + if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribPointerARB(pname)"); + return; + } + + *pointer = (GLvoid *) ctx->Array.VertexAttrib[index].Ptr;; +} + + +void GLAPIENTRY +_mesa_ProgramStringARB(GLenum target, GLenum format, GLsizei len, + const GLvoid *string) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + struct vertex_program *prog = ctx->VertexProgram.Current; + if (format != GL_PROGRAM_FORMAT_ASCII_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramStringARB(format)"); + return; + } + _mesa_parse_arb_vertex_program(ctx, target, (const GLubyte *) string, + len, prog); + + if (ctx->Driver.ProgramStringNotify) + ctx->Driver.ProgramStringNotify( ctx, target, &prog->Base ); + } + else if (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program) { + struct fragment_program *prog = ctx->FragmentProgram.Current; + if (format != GL_PROGRAM_FORMAT_ASCII_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramStringARB(format)"); + return; + } + _mesa_parse_arb_fragment_program(ctx, target, (const GLubyte *) string, + len, prog); + + if (ctx->Driver.ProgramStringNotify) + ctx->Driver.ProgramStringNotify( ctx, target, &prog->Base ); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramStringARB(target)"); + return; + } +} + + +void GLAPIENTRY +_mesa_ProgramEnvParameter4dARB(GLenum target, GLuint index, + GLdouble x, GLdouble y, GLdouble z, GLdouble w) +{ + _mesa_ProgramEnvParameter4fARB(target, index, (GLfloat) x, (GLfloat) y, + (GLfloat) z, (GLfloat) w); +} + + +void GLAPIENTRY +_mesa_ProgramEnvParameter4dvARB(GLenum target, GLuint index, + const GLdouble *params) +{ + _mesa_ProgramEnvParameter4fARB(target, index, (GLfloat) params[0], + (GLfloat) params[1], (GLfloat) params[2], + (GLfloat) params[3]); +} + + +void GLAPIENTRY +_mesa_ProgramEnvParameter4fARB(GLenum target, GLuint index, + GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program) { + if (index >= ctx->Const.MaxFragmentProgramEnvParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramEnvParameter(index)"); + return; + } + ASSIGN_4V(ctx->FragmentProgram.Parameters[index], x, y, z, w); + } + else if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + if (index >= ctx->Const.MaxVertexProgramEnvParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramEnvParameter(index)"); + return; + } + ASSIGN_4V(ctx->VertexProgram.Parameters[index], x, y, z, w); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramEnvParameter(target)"); + return; + } +} + + +void GLAPIENTRY +_mesa_ProgramEnvParameter4fvARB(GLenum target, GLuint index, + const GLfloat *params) +{ + _mesa_ProgramEnvParameter4fARB(target, index, params[0], params[1], + params[2], params[3]); +} + + +void GLAPIENTRY +_mesa_GetProgramEnvParameterdvARB(GLenum target, GLuint index, + GLdouble *params) +{ + GET_CURRENT_CONTEXT(ctx); + GLfloat fparams[4]; + + _mesa_GetProgramEnvParameterfvARB(target, index, fparams); + if (ctx->ErrorValue == GL_NO_ERROR) { + params[0] = fparams[0]; + params[1] = fparams[1]; + params[2] = fparams[2]; + params[3] = fparams[3]; + } +} + + +void GLAPIENTRY +_mesa_GetProgramEnvParameterfvARB(GLenum target, GLuint index, + GLfloat *params) +{ + GET_CURRENT_CONTEXT(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program) { + if (index >= ctx->Const.MaxFragmentProgramEnvParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramEnvParameter(index)"); + return; + } + COPY_4V(params, ctx->FragmentProgram.Parameters[index]); + } + else if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + if (index >= ctx->Const.MaxVertexProgramEnvParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramEnvParameter(index)"); + return; + } + COPY_4V(params, ctx->VertexProgram.Parameters[index]); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramEnvParameter(target)"); + return; + } +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_ProgramLocalParameter4fARB(GLenum target, GLuint index, + GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + GET_CURRENT_CONTEXT(ctx); + struct program *prog; + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if ((target == GL_FRAGMENT_PROGRAM_NV + && ctx->Extensions.NV_fragment_program) || + (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program)) { + if (index >= ctx->Const.MaxFragmentProgramLocalParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramLocalParameterARB"); + return; + } + prog = &(ctx->FragmentProgram.Current->Base); + } + else if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + if (index >= ctx->Const.MaxVertexProgramLocalParams) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramLocalParameterARB"); + return; + } + prog = &(ctx->VertexProgram.Current->Base); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramLocalParameterARB"); + return; + } + + ASSERT(index < MAX_PROGRAM_LOCAL_PARAMS); + prog->LocalParams[index][0] = x; + prog->LocalParams[index][1] = y; + prog->LocalParams[index][2] = z; + prog->LocalParams[index][3] = w; +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_ProgramLocalParameter4fvARB(GLenum target, GLuint index, + const GLfloat *params) +{ + _mesa_ProgramLocalParameter4fARB(target, index, params[0], params[1], + params[2], params[3]); +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_ProgramLocalParameter4dARB(GLenum target, GLuint index, + GLdouble x, GLdouble y, + GLdouble z, GLdouble w) +{ + _mesa_ProgramLocalParameter4fARB(target, index, (GLfloat) x, (GLfloat) y, + (GLfloat) z, (GLfloat) w); +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_ProgramLocalParameter4dvARB(GLenum target, GLuint index, + const GLdouble *params) +{ + _mesa_ProgramLocalParameter4fARB(target, index, + (GLfloat) params[0], (GLfloat) params[1], + (GLfloat) params[2], (GLfloat) params[3]); +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_GetProgramLocalParameterfvARB(GLenum target, GLuint index, + GLfloat *params) +{ + const struct program *prog; + GLuint maxParams; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + prog = &(ctx->VertexProgram.Current->Base); + maxParams = ctx->Const.MaxVertexProgramLocalParams; + } + else if (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program) { + prog = &(ctx->FragmentProgram.Current->Base); + maxParams = ctx->Const.MaxFragmentProgramLocalParams; + } + else if (target == GL_FRAGMENT_PROGRAM_NV + && ctx->Extensions.NV_fragment_program) { + prog = &(ctx->FragmentProgram.Current->Base); + maxParams = MAX_NV_FRAGMENT_PROGRAM_PARAMS; + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, + "glGetProgramLocalParameterARB(target)"); + return; + } + + if (index >= maxParams) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramLocalParameterARB(index)"); + return; + } + + ASSERT(prog); + ASSERT(index < MAX_PROGRAM_LOCAL_PARAMS); + COPY_4V(params, prog->LocalParams[index]); +} + + +/** + * Note, this function is also used by the GL_NV_fragment_program extension. + */ +void GLAPIENTRY +_mesa_GetProgramLocalParameterdvARB(GLenum target, GLuint index, + GLdouble *params) +{ + GET_CURRENT_CONTEXT(ctx); + GLfloat floatParams[4]; + _mesa_GetProgramLocalParameterfvARB(target, index, floatParams); + if (ctx->ErrorValue == GL_NO_ERROR) { + COPY_4V(params, floatParams); + } +} + + +void GLAPIENTRY +_mesa_GetProgramivARB(GLenum target, GLenum pname, GLint *params) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program) { + prog = &(ctx->VertexProgram.Current->Base); + } + else if (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program) { + prog = &(ctx->FragmentProgram.Current->Base); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + + ASSERT(prog); + + switch (pname) { + case GL_PROGRAM_LENGTH_ARB: + *params = prog->String ? _mesa_strlen((char *) prog->String) : 0; + break; + case GL_PROGRAM_FORMAT_ARB: + *params = prog->Format; + break; + case GL_PROGRAM_BINDING_ARB: + *params = prog->Id; + break; + case GL_PROGRAM_INSTRUCTIONS_ARB: + *params = prog->NumInstructions; + break; + case GL_MAX_PROGRAM_INSTRUCTIONS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramInstructions; + else + *params = ctx->Const.MaxFragmentProgramInstructions; + break; + case GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB: + *params = prog->NumInstructions; + break; + case GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramInstructions; + else + *params = ctx->Const.MaxFragmentProgramInstructions; + break; + case GL_PROGRAM_TEMPORARIES_ARB: + *params = prog->NumTemporaries; + break; + case GL_MAX_PROGRAM_TEMPORARIES_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramTemps; + else + *params = ctx->Const.MaxFragmentProgramTemps; + break; + case GL_PROGRAM_NATIVE_TEMPORARIES_ARB: + /* XXX same as GL_PROGRAM_TEMPORARIES_ARB? */ + *params = prog->NumTemporaries; + break; + case GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB: + /* XXX same as GL_MAX_PROGRAM_TEMPORARIES_ARB? */ + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramTemps; + else + *params = ctx->Const.MaxFragmentProgramTemps; + break; + case GL_PROGRAM_PARAMETERS_ARB: + *params = prog->NumParameters; + break; + case GL_MAX_PROGRAM_PARAMETERS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramLocalParams; + else + *params = ctx->Const.MaxFragmentProgramLocalParams; + break; + case GL_PROGRAM_NATIVE_PARAMETERS_ARB: + /* XXX same as GL_MAX_PROGRAM_PARAMETERS_ARB? */ + *params = prog->NumParameters; + break; + case GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB: + /* XXX same as GL_MAX_PROGRAM_PARAMETERS_ARB? */ + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramLocalParams; + else + *params = ctx->Const.MaxFragmentProgramLocalParams; + break; + case GL_PROGRAM_ATTRIBS_ARB: + *params = prog->NumAttributes; + break; + case GL_MAX_PROGRAM_ATTRIBS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramAttribs; + else + *params = ctx->Const.MaxFragmentProgramAttribs; + break; + case GL_PROGRAM_NATIVE_ATTRIBS_ARB: + /* XXX same as GL_PROGRAM_ATTRIBS_ARB? */ + *params = prog->NumAttributes; + break; + case GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB: + /* XXX same as GL_MAX_PROGRAM_ATTRIBS_ARB? */ + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramAttribs; + else + *params = ctx->Const.MaxFragmentProgramAttribs; + break; + case GL_PROGRAM_ADDRESS_REGISTERS_ARB: + *params = prog->NumAddressRegs; + break; + case GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramAddressRegs; + else + *params = ctx->Const.MaxFragmentProgramAddressRegs; + break; + case GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB: + /* XXX same as GL_PROGRAM_ADDRESS_REGISTERS_ARB? */ + *params = prog->NumAddressRegs; + break; + case GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB: + /* XXX same as GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB? */ + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramAddressRegs; + else + *params = ctx->Const.MaxFragmentProgramAddressRegs; + break; + case GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramLocalParams; + else + *params = ctx->Const.MaxFragmentProgramLocalParams; + break; + case GL_MAX_PROGRAM_ENV_PARAMETERS_ARB: + if (target == GL_VERTEX_PROGRAM_ARB) + *params = ctx->Const.MaxVertexProgramEnvParams; + else + *params = ctx->Const.MaxFragmentProgramEnvParams; + break; + case GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB: + if (ctx->Driver.IsProgramNative) + *params = ctx->Driver.IsProgramNative( ctx, target, prog ); + else + *params = GL_TRUE; + break; + + /* + * The following apply to fragment programs only. + */ + case GL_PROGRAM_ALU_INSTRUCTIONS_ARB: + case GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->FragmentProgram.Current->NumAluInstructions; + break; + case GL_PROGRAM_TEX_INSTRUCTIONS_ARB: + case GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->FragmentProgram.Current->NumTexInstructions; + break; + case GL_PROGRAM_TEX_INDIRECTIONS_ARB: + case GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->FragmentProgram.Current->NumTexIndirections; + break; + case GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB: + case GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->Const.MaxFragmentProgramAluInstructions; + break; + case GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB: + case GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->Const.MaxFragmentProgramTexInstructions; + break; + case GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB: + case GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB: + if (target != GL_FRAGMENT_PROGRAM_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(target)"); + return; + } + *params = ctx->Const.MaxFragmentProgramTexIndirections; + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivARB(pname)"); + return; + } +} + + +void GLAPIENTRY +_mesa_GetProgramStringARB(GLenum target, GLenum pname, GLvoid *string) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_ARB) { + prog = &(ctx->VertexProgram.Current->Base); + } + else if (target == GL_FRAGMENT_PROGRAM_ARB) { + prog = &(ctx->FragmentProgram.Current->Base); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramStringARB(target)"); + return; + } + + ASSERT(prog); + + if (pname != GL_PROGRAM_STRING_ARB) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramStringARB(pname)"); + return; + } + + MEMCPY(string, prog->String, _mesa_strlen((char *) prog->String)); +} + diff --git a/src/mesa/shader/arbprogram.h b/src/mesa/shader/arbprogram.h new file mode 100644 index 0000000..e1b99ab --- /dev/null +++ b/src/mesa/shader/arbprogram.h @@ -0,0 +1,128 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +#ifndef ARBPROGRAM_H +#define ARBPROGRAM_H + + +extern void GLAPIENTRY +_mesa_EnableVertexAttribArrayARB(GLuint index); + + +extern void GLAPIENTRY +_mesa_DisableVertexAttribArrayARB(GLuint index); + + +extern void GLAPIENTRY +_mesa_GetVertexAttribdvARB(GLuint index, GLenum pname, GLdouble *params); + + +extern void GLAPIENTRY +_mesa_GetVertexAttribfvARB(GLuint index, GLenum pname, GLfloat *params); + + +extern void GLAPIENTRY +_mesa_GetVertexAttribivARB(GLuint index, GLenum pname, GLint *params); + + +extern void GLAPIENTRY +_mesa_GetVertexAttribPointervARB(GLuint index, GLenum pname, GLvoid **pointer); + + +extern void GLAPIENTRY +_mesa_ProgramStringARB(GLenum target, GLenum format, GLsizei len, + const GLvoid *string); + + +extern void GLAPIENTRY +_mesa_ProgramEnvParameter4dARB(GLenum target, GLuint index, + GLdouble x, GLdouble y, GLdouble z, GLdouble w); + + +extern void GLAPIENTRY +_mesa_ProgramEnvParameter4dvARB(GLenum target, GLuint index, + const GLdouble *params); + + +extern void GLAPIENTRY +_mesa_ProgramEnvParameter4fARB(GLenum target, GLuint index, + GLfloat x, GLfloat y, GLfloat z, GLfloat w); + + +extern void GLAPIENTRY +_mesa_ProgramEnvParameter4fvARB(GLenum target, GLuint index, + const GLfloat *params); + + +extern void GLAPIENTRY +_mesa_ProgramLocalParameter4dARB(GLenum target, GLuint index, + GLdouble x, GLdouble y, + GLdouble z, GLdouble w); + + +extern void GLAPIENTRY +_mesa_ProgramLocalParameter4dvARB(GLenum target, GLuint index, + const GLdouble *params); + + +extern void GLAPIENTRY +_mesa_ProgramLocalParameter4fARB(GLenum target, GLuint index, + GLfloat x, GLfloat y, GLfloat z, GLfloat w); + + +extern void GLAPIENTRY +_mesa_ProgramLocalParameter4fvARB(GLenum target, GLuint index, + const GLfloat *params); + + +extern void GLAPIENTRY +_mesa_GetProgramEnvParameterdvARB(GLenum target, GLuint index, + GLdouble *params); + + +extern void GLAPIENTRY +_mesa_GetProgramEnvParameterfvARB(GLenum target, GLuint index, + GLfloat *params); + + +extern void GLAPIENTRY +_mesa_GetProgramLocalParameterdvARB(GLenum target, GLuint index, + GLdouble *params); + + +extern void GLAPIENTRY +_mesa_GetProgramLocalParameterfvARB(GLenum target, GLuint index, + GLfloat *params); + + +extern void GLAPIENTRY +_mesa_GetProgramivARB(GLenum target, GLenum pname, GLint *params); + + +extern void GLAPIENTRY +_mesa_GetProgramStringARB(GLenum target, GLenum pname, GLvoid *string); + + +#endif diff --git a/src/mesa/shader/arbprogram_syn.h b/src/mesa/shader/arbprogram_syn.h new file mode 100644 index 0000000..71ccd20 --- /dev/null +++ b/src/mesa/shader/arbprogram_syn.h @@ -0,0 +1,1344 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file arbprogram_syn.h + * ARB_fragment_program/ARB_vertex_program syntax + * \author Michal Krol + */ + +".syntax program;\n" +".emtcode REVISION 0x07\n" +".emtcode FRAGMENT_PROGRAM 0x01\n" +".emtcode VERTEX_PROGRAM 0x02\n" +".emtcode OPTION 0x01\n" +".emtcode INSTRUCTION 0x02\n" +".emtcode DECLARATION 0x03\n" +".emtcode END 0x04\n" +".emtcode ARB_PRECISION_HINT_FASTEST 0x01\n" +".emtcode ARB_PRECISION_HINT_NICEST 0x02\n" +".emtcode ARB_FOG_EXP 0x04\n" +".emtcode ARB_FOG_EXP2 0x08\n" +".emtcode ARB_FOG_LINEAR 0x10\n" +".emtcode ARB_POSITION_INVARIANT 0x20\n" +".emtcode ARB_FRAGMENT_PROGRAM_SHADOW 0x40\n" +".emtcode OP_ALU_INST 0x00\n" +".emtcode OP_TEX_INST 0x01\n" +".emtcode OP_ALU_VECTOR 0x00\n" +".emtcode OP_ALU_SCALAR 0x01\n" +".emtcode OP_ALU_BINSC 0x02\n" +".emtcode OP_ALU_BIN 0x03\n" +".emtcode OP_ALU_TRI 0x04\n" +".emtcode OP_ALU_SWZ 0x05\n" +".emtcode OP_TEX_SAMPLE 0x06\n" +".emtcode OP_TEX_KIL 0x07\n" +".emtcode OP_ALU_ARL 0x08\n" +".emtcode OP_ABS 0x00\n" +".emtcode OP_ABS_SAT 0x1B\n" +".emtcode OP_FLR 0x09\n" +".emtcode OP_FLR_SAT 0x26\n" +".emtcode OP_FRC 0x0A\n" +".emtcode OP_FRC_SAT 0x27\n" +".emtcode OP_LIT 0x0C\n" +".emtcode OP_LIT_SAT 0x2A\n" +".emtcode OP_MOV 0x11\n" +".emtcode OP_MOV_SAT 0x30\n" +".emtcode OP_COS 0x1F\n" +".emtcode OP_COS_SAT 0x20\n" +".emtcode OP_EX2 0x07\n" +".emtcode OP_EX2_SAT 0x25\n" +".emtcode OP_LG2 0x0B\n" +".emtcode OP_LG2_SAT 0x29\n" +".emtcode OP_RCP 0x14\n" +".emtcode OP_RCP_SAT 0x33\n" +".emtcode OP_RSQ 0x15\n" +".emtcode OP_RSQ_SAT 0x34\n" +".emtcode OP_SIN 0x38\n" +".emtcode OP_SIN_SAT 0x39\n" +".emtcode OP_SCS 0x35\n" +".emtcode OP_SCS_SAT 0x36\n" +".emtcode OP_POW 0x13\n" +".emtcode OP_POW_SAT 0x32\n" +".emtcode OP_ADD 0x01\n" +".emtcode OP_ADD_SAT 0x1C\n" +".emtcode OP_DP3 0x03\n" +".emtcode OP_DP3_SAT 0x21\n" +".emtcode OP_DP4 0x04\n" +".emtcode OP_DP4_SAT 0x22\n" +".emtcode OP_DPH 0x05\n" +".emtcode OP_DPH_SAT 0x23\n" +".emtcode OP_DST 0x06\n" +".emtcode OP_DST_SAT 0x24\n" +".emtcode OP_MAX 0x0F\n" +".emtcode OP_MAX_SAT 0x2E\n" +".emtcode OP_MIN 0x10\n" +".emtcode OP_MIN_SAT 0x2F\n" +".emtcode OP_MUL 0x12\n" +".emtcode OP_MUL_SAT 0x31\n" +".emtcode OP_SGE 0x16\n" +".emtcode OP_SGE_SAT 0x37\n" +".emtcode OP_SLT 0x17\n" +".emtcode OP_SLT_SAT 0x3A\n" +".emtcode OP_SUB 0x18\n" +".emtcode OP_SUB_SAT 0x3B\n" +".emtcode OP_XPD 0x1A\n" +".emtcode OP_XPD_SAT 0x43\n" +".emtcode OP_CMP 0x1D\n" +".emtcode OP_CMP_SAT 0x1E\n" +".emtcode OP_LRP 0x2B\n" +".emtcode OP_LRP_SAT 0x2C\n" +".emtcode OP_MAD 0x0E\n" +".emtcode OP_MAD_SAT 0x2D\n" +".emtcode OP_SWZ 0x19\n" +".emtcode OP_SWZ_SAT 0x3C\n" +".emtcode OP_TEX 0x3D\n" +".emtcode OP_TEX_SAT 0x3E\n" +".emtcode OP_TXB 0x3F\n" +".emtcode OP_TXB_SAT 0x40\n" +".emtcode OP_TXP 0x41\n" +".emtcode OP_TXP_SAT 0x42\n" +".emtcode OP_KIL 0x28\n" +".emtcode OP_ARL 0x02\n" +".emtcode OP_EXP 0x08\n" +".emtcode OP_LOG 0x0D\n" +".emtcode FRAGMENT_ATTRIB_COLOR 0x01\n" +".emtcode FRAGMENT_ATTRIB_TEXCOORD 0x02\n" +".emtcode FRAGMENT_ATTRIB_FOGCOORD 0x03\n" +".emtcode FRAGMENT_ATTRIB_POSITION 0x04\n" +".emtcode VERTEX_ATTRIB_POSITION 0x01\n" +".emtcode VERTEX_ATTRIB_WEIGHT 0x02\n" +".emtcode VERTEX_ATTRIB_NORMAL 0x03\n" +".emtcode VERTEX_ATTRIB_COLOR 0x04\n" +".emtcode VERTEX_ATTRIB_FOGCOORD 0x05\n" +".emtcode VERTEX_ATTRIB_TEXCOORD 0x06\n" +".emtcode VERTEX_ATTRIB_MATRIXINDEX 0x07\n" +".emtcode VERTEX_ATTRIB_GENERIC 0x08\n" +".emtcode FRAGMENT_RESULT_COLOR 0x01\n" +".emtcode FRAGMENT_RESULT_DEPTH 0x02\n" +".emtcode VERTEX_RESULT_POSITION 0x01\n" +".emtcode VERTEX_RESULT_COLOR 0x02\n" +".emtcode VERTEX_RESULT_FOGCOORD 0x03\n" +".emtcode VERTEX_RESULT_POINTSIZE 0x04\n" +".emtcode VERTEX_RESULT_TEXCOORD 0x05\n" +".emtcode TEXTARGET_1D 0x01\n" +".emtcode TEXTARGET_2D 0x02\n" +".emtcode TEXTARGET_3D 0x03\n" +".emtcode TEXTARGET_RECT 0x04\n" +".emtcode TEXTARGET_CUBE 0x05\n" +".emtcode TEXTARGET_SHADOW1D 0x06\n" +".emtcode TEXTARGET_SHADOW2D 0x07\n" +".emtcode TEXTARGET_SHADOWRECT 0x08\n" +".emtcode FACE_FRONT 0x00\n" +".emtcode FACE_BACK 0x01\n" +".emtcode COLOR_PRIMARY 0x00\n" +".emtcode COLOR_SECONDARY 0x01\n" +".emtcode COMPONENT_X 0x00\n" +".emtcode COMPONENT_Y 0x01\n" +".emtcode COMPONENT_Z 0x02\n" +".emtcode COMPONENT_W 0x03\n" +".emtcode COMPONENT_0 0x04\n" +".emtcode COMPONENT_1 0x05\n" +".emtcode ARRAY_INDEX_ABSOLUTE 0x00\n" +".emtcode ARRAY_INDEX_RELATIVE 0x01\n" +".emtcode MATRIX_MODELVIEW 0x01\n" +".emtcode MATRIX_PROJECTION 0x02\n" +".emtcode MATRIX_MVP 0x03\n" +".emtcode MATRIX_TEXTURE 0x04\n" +".emtcode MATRIX_PALETTE 0x05\n" +".emtcode MATRIX_PROGRAM 0x06\n" +".emtcode MATRIX_MODIFIER_IDENTITY 0x00\n" +".emtcode MATRIX_MODIFIER_INVERSE 0x01\n" +".emtcode MATRIX_MODIFIER_TRANSPOSE 0x02\n" +".emtcode MATRIX_MODIFIER_INVTRANS 0x03\n" +".emtcode CONSTANT_SCALAR 0x01\n" +".emtcode CONSTANT_VECTOR 0x02\n" +".emtcode PROGRAM_PARAM_ENV 0x01\n" +".emtcode PROGRAM_PARAM_LOCAL 0x02\n" +".emtcode REGISTER_ATTRIB 0x01\n" +".emtcode REGISTER_PARAM 0x02\n" +".emtcode REGISTER_RESULT 0x03\n" +".emtcode REGISTER_ESTABLISHED_NAME 0x04\n" +".emtcode PARAM_NULL 0x00\n" +".emtcode PARAM_ARRAY_ELEMENT 0x01\n" +".emtcode PARAM_STATE_ELEMENT 0x02\n" +".emtcode PARAM_PROGRAM_ELEMENT 0x03\n" +".emtcode PARAM_PROGRAM_ELEMENTS 0x04\n" +".emtcode PARAM_CONSTANT 0x05\n" +".emtcode STATE_MATERIAL 0x01\n" +".emtcode STATE_LIGHT 0x02\n" +".emtcode STATE_LIGHT_MODEL 0x03\n" +".emtcode STATE_LIGHT_PROD 0x04\n" +".emtcode STATE_FOG 0x05\n" +".emtcode STATE_MATRIX_ROWS 0x06\n" +".emtcode STATE_TEX_ENV 0x07\n" +".emtcode STATE_DEPTH 0x08\n" +".emtcode STATE_TEX_GEN 0x09\n" +".emtcode STATE_CLIP_PLANE 0x0A\n" +".emtcode STATE_POINT 0x0B\n" +".emtcode MATERIAL_AMBIENT 0x01\n" +".emtcode MATERIAL_DIFFUSE 0x02\n" +".emtcode MATERIAL_SPECULAR 0x03\n" +".emtcode MATERIAL_EMISSION 0x04\n" +".emtcode MATERIAL_SHININESS 0x05\n" +".emtcode LIGHT_AMBIENT 0x01\n" +".emtcode LIGHT_DIFFUSE 0x02\n" +".emtcode LIGHT_SPECULAR 0x03\n" +".emtcode LIGHT_POSITION 0x04\n" +".emtcode LIGHT_ATTENUATION 0x05\n" +".emtcode LIGHT_HALF 0x06\n" +".emtcode LIGHT_SPOT_DIRECTION 0x07\n" +".emtcode LIGHT_MODEL_AMBIENT 0x01\n" +".emtcode LIGHT_MODEL_SCENECOLOR 0x02\n" +".emtcode LIGHT_PROD_AMBIENT 0x01\n" +".emtcode LIGHT_PROD_DIFFUSE 0x02\n" +".emtcode LIGHT_PROD_SPECULAR 0x03\n" +".emtcode TEX_ENV_COLOR 0x01\n" +".emtcode TEX_GEN_EYE 0x01\n" +".emtcode TEX_GEN_OBJECT 0x02\n" +".emtcode FOG_COLOR 0x01\n" +".emtcode FOG_PARAMS 0x02\n" +".emtcode DEPTH_RANGE 0x01\n" +".emtcode POINT_SIZE 0x01\n" +".emtcode POINT_ATTENUATION 0x02\n" +".emtcode ATTRIB 0x01\n" +".emtcode PARAM 0x02\n" +".emtcode TEMP 0x03\n" +".emtcode OUTPUT 0x04\n" +".emtcode ALIAS 0x05\n" +".emtcode ADDRESS 0x06\n" +".errtext UNKNOWN_PROGRAM_SIGNATURE \"1001: '$e_signature$': unknown program signature\"\n" +".errtext MISSING_END_OR_INVALID_STATEMENT \"1002: '$e_statement$': invalid statement\"\n" +".errtext CODE_AFTER_END \"1003: '$e_statement$': code after 'END' keyword\"\n" +".errtext INVALID_PROGRAM_OPTION \"1004: '$e_identifier$': invalid program option\"\n" +".errtext EXT_SWIZ_COMP_EXPECTED \"1005: extended swizzle component expected but '$e_token$' found\"\n" +".errtext TEX_TARGET_EXPECTED \"1006: texture target expected but '$e_token$' found\"\n" +".errtext TEXTURE_EXPECTED \"1007: 'texture' expected but '$e_identifier$' found\"\n" +".errtext SOURCE_REGISTER_EXPECTED \"1008: source register expected but '$e_token$' found\"\n" +".errtext DESTINATION_REGISTER_EXPECTED \"1009: destination register expected but '$e_token$' found\"\n" +".errtext INVALID_ADDRESS_COMPONENT \"1010: '$e_identifier$': invalid address component\"\n" +".errtext INVALID_ADDRESS_WRITEMASK \"1011: '$e_identifier$': invalid address writemask\"\n" +".errtext INVALID_COMPONENT \"1012: '$e_charordigit$': invalid component\"\n" +".errtext INVALID_SUFFIX \"1013: '$e_identifier$': invalid suffix\"\n" +".errtext INVALID_WRITEMASK \"1014: '$e_identifier$': invalid writemask\"\n" +".errtext FRAGMENT_EXPECTED \"1015: 'fragment' expected but '$e_identifier$' found\"\n" +".errtext VERTEX_EXPECTED \"1016: 'vertex' expected but '$e_identifier$' found\"\n" +".errtext INVALID_FRAGMENT_PROPERTY \"1017: '$e_identifier$': invalid fragment property\"\n" +".errtext INVALID_VERTEX_PROPERTY \"1018: '$e_identifier$': invalid vertex property\"\n" +".errtext INVALID_STATE_PROPERTY \"1019: '$e_identifier$': invalid state property\"\n" +".errtext INVALID_MATERIAL_PROPERTY \"1020: '$e_identifier$': invalid material property\"\n" +".errtext INVALID_LIGHT_PROPERTY \"1021: '$e_identifier$': invalid light property\"\n" +".errtext INVALID_SPOT_PROPERTY \"1022: '$e_identifier$': invalid spot property\"\n" +".errtext INVALID_LIGHTMODEL_PROPERTY \"1023: '$e_identifier$': invalid light model property\"\n" +".errtext INVALID_LIGHTPROD_PROPERTY \"1024: '$e_identifier$': invalid light product property\"\n" +".errtext INVALID_TEXENV_PROPERTY \"1025: '$e_identifier$': invalid texture environment property\"\n" +".errtext INVALID_TEXGEN_PROPERTY \"1026: '$e_identifier$': invalid texture generating property\"\n" +".errtext INVALID_TEXGEN_COORD \"1027: '$e_identifier$': invalid texture generating coord\"\n" +".errtext INVALID_FOG_PROPERTY \"1028: '$e_identifier$': invalid fog property\"\n" +".errtext INVALID_DEPTH_PROPERTY \"1029: '$e_identifier$': invalid depth property\"\n" +".errtext INVALID_CLIPPLANE_PROPERTY \"1030: '$e_identifier$': invalid clip plane property\"\n" +".errtext INVALID_POINT_PROPERTY \"1031: '$e_identifier$': invalid point property\"\n" +".errtext MATRIX_ROW_SELECTOR_OR_MODIFIER_EXPECTED \"1032: matrix row selector or modifier expected but '$e_token$' found\"\n" +".errtext INVALID_MATRIX_NAME \"1033: '$e_identifier$': invalid matrix name\"\n" +".errtext INVALID_PROGRAM_PROPERTY \"1034: '$e_identifier$': invalid program property\"\n" +".errtext RESULT_EXPECTED \"1035: 'result' expected but '$e_token$' found\"\n" +".errtext INVALID_RESULT_PROPERTY \"1036: '$e_identifier$': invalid result property\"\n" +".errtext INVALID_FACE_PROPERTY \"1037: '$e_identifier$': invalid face property\"\n" +".errtext INVALID_COLOR_PROPERTY \"1038: '$e_identifier$': invalid color property\"\n" +".errtext IDENTIFIER_EXPECTED \"1039: identifier expected but '$e_token$' found\"\n" +".errtext RESERVED_KEYWORD \"1040: use of reserved keyword as an identifier\"\n" +".errtext INTEGER_EXPECTED \"1041: integer value expected but '$e_token$' found\"\n" +".errtext MISSING_SEMICOLON \"1042: ';' expected but '$e_token$' found\"\n" +".errtext MISSING_COMMA \"1043: ',' expected but '$e_token$' found\"\n" +".errtext MISSING_LBRACKET \"1044: '[' expected but '$e_token$' found\"\n" +".errtext MISSING_RBRACKET \"1045: ']' expected but '$e_token$' found\"\n" +".errtext MISSING_DOT \"1046: '.' expected but '$e_token$' found\"\n" +".errtext MISSING_EQUAL \"1047: '=' expected but '$e_token$' found\"\n" +".errtext MISSING_LBRACE \"1048: '{' expected but '$e_token$' found\"\n" +".errtext MISSING_RBRACE \"1049: '}' expected but '$e_token$' found\"\n" +".errtext MISSING_DOTDOT \"1050: '..' expected but '$e_token$' found\"\n" +".errtext MISSING_FRACTION_OR_EXPONENT \"1051: missing fraction part or exponent\"\n" +".errtext MISSING_DOT_OR_EXPONENT \"1052: missing '.' or exponent\"\n" +".errtext EXPONENT_VALUE_EXPECTED \"1053: exponent value expected\"\n" +".errtext INTEGER_OUT_OF_RANGE \"1054: integer value out of range\"\n" +".errtext OPERATION_NEEDS_DESTINATION_VARIABLE \"1055: operation needs destination variable\"\n" +".errtext OPERATION_NEEDS_SOURCE_VARIABLE \"1056: operation needs source variable\"\n" +".errtext ADDRESS_REGISTER_EXPECTED \"1057: address register expected but '$e_token$' found\"\n" +".errtext ADDRESS_REGISTER_OR_INTEGER_EXPECTED \"1058: address register or integer literal expected but '$e_token$' found\"\n" +".regbyte vertex_blend 0x00\n" +".regbyte matrix_palette 0x00\n" +".regbyte point_parameters 0x00\n" +".regbyte secondary_color 0x00\n" +".regbyte fog_coord 0x00\n" +".regbyte texture_rectangle 0x00\n" +".regbyte fragment_program_shadow 0x00\n" +".regbyte ARB_precision_hint_fastest 0x00\n" +".regbyte ARB_precision_hint_nicest 0x00\n" +".regbyte ARB_fog_exp 0x00\n" +".regbyte ARB_fog_exp2 0x00\n" +".regbyte ARB_fog_linear 0x00\n" +".regbyte ARB_position_invariant 0x00\n" +".regbyte ARB_fragment_program_shadow 0x00\n" +".regbyte program_target 0x00\n" +"program\n" +" programs .error UNKNOWN_PROGRAM_SIGNATURE .emit REVISION;\n" +"programs\n" +" .if (program_target == 0x10) frag_program_1_0 .emit FRAGMENT_PROGRAM .emit 0x01 .emit 0x00 .or\n" +" .if (program_target == 0x20) vert_program_1_0 .emit VERTEX_PROGRAM .emit 0x01 .emit 0x00;\n" +"frag_program_1_0\n" +" '!' .and '!' .and 'A' .and 'R' .and 'B' .and 'f' .and 'p' .and '1' .and '.' .and '0' .and\n" +" optional_space .and fp_optionSequence .and fp_statementSequence .and\n" +" \"END\" .error MISSING_END_OR_INVALID_STATEMENT .emit END .and optional_space .and\n" +" '\\0' .error CODE_AFTER_END;\n" +"vert_program_1_0\n" +" '!' .and '!' .and 'A' .and 'R' .and 'B' .and 'v' .and 'p' .and '1' .and '.' .and '0' .and\n" +" optional_space .and vp_optionSequence .and vp_statementSequence .and\n" +" \"END\" .error MISSING_END_OR_INVALID_STATEMENT .emit END .and optional_space .and\n" +" '\\0' .error CODE_AFTER_END;\n" +"fp_optionSequence\n" +" .loop fp_option;\n" +"vp_optionSequence\n" +" .loop vp_option;\n" +"fp_option\n" +" \"OPTION\" .emit OPTION .and space .error IDENTIFIER_EXPECTED .and\n" +" fp_optionString .error INVALID_PROGRAM_OPTION .and semicolon;\n" +"vp_option\n" +" \"OPTION\" .emit OPTION .and space .error IDENTIFIER_EXPECTED .and\n" +" vp_optionString .error INVALID_PROGRAM_OPTION .and semicolon;\n" +"fp_optionString\n" +" .if (ARB_precision_hint_nicest == 0x00) \"ARB_precision_hint_fastest\"\n" +" .emit ARB_PRECISION_HINT_FASTEST .load ARB_precision_hint_fastest 0x01 .or\n" +" .if (ARB_precision_hint_fastest == 0x00) \"ARB_precision_hint_nicest\"\n" +" .emit ARB_PRECISION_HINT_NICEST .load ARB_precision_hint_nicest 0x01 .or\n" +" fp_ARB_fog_exp .emit ARB_FOG_EXP .load ARB_fog_exp 0x01 .or\n" +" fp_ARB_fog_exp2 .emit ARB_FOG_EXP2 .load ARB_fog_exp2 0x01 .or\n" +" fp_ARB_fog_linear .emit ARB_FOG_LINEAR .load ARB_fog_linear 0x01 .or\n" +" .if (fragment_program_shadow != 0x00) \"ARB_fragment_program_shadow\"\n" +" .emit ARB_FRAGMENT_PROGRAM_SHADOW .load ARB_fragment_program_shadow 0x01;\n" +"vp_optionString\n" +" \"ARB_position_invariant\" .emit ARB_POSITION_INVARIANT .load ARB_position_invariant 0x01;\n" +"fp_ARB_fog_exp\n" +" .if (ARB_fog_exp2 == 0x00) .true .and .if (ARB_fog_linear == 0x00) \"ARB_fog_exp\";\n" +"fp_ARB_fog_exp2\n" +" .if (ARB_fog_exp == 0x00) .true .and .if (ARB_fog_linear == 0x00) \"ARB_fog_exp2\";\n" +"fp_ARB_fog_linear\n" +" .if (ARB_fog_exp == 0x00) .true .and .if (ARB_fog_exp2 == 0x00) \"ARB_fog_linear\";\n" +"fp_statementSequence\n" +" .loop fp_statement;\n" +"vp_statementSequence\n" +" .loop vp_statement;\n" +"fp_statement\n" +" fp_statement_1 .or fp_statement_2;\n" +"vp_statement\n" +" vp_statement_1 .or vp_statement_2;\n" +"fp_statement_1\n" +" fp_instruction .emit INSTRUCTION .emit $ .and semicolon;\n" +"fp_statement_2\n" +" fp_namingStatement .emit DECLARATION .and semicolon;\n" +"vp_statement_1\n" +" vp_instruction .emit INSTRUCTION .emit $ .and semicolon;\n" +"vp_statement_2\n" +" vp_namingStatement .emit DECLARATION .and semicolon;\n" +"fp_instruction\n" +" ALUInstruction .emit OP_ALU_INST .or\n" +" TexInstruction .emit OP_TEX_INST;\n" +"vp_instruction\n" +" ARL_instruction .emit OP_ALU_ARL .or\n" +" vp_VECTORop_instruction .emit OP_ALU_VECTOR .or\n" +" vp_SCALARop_instruction .emit OP_ALU_SCALAR .or\n" +" vp_BINSCop_instruction .emit OP_ALU_BINSC .or\n" +" vp_BINop_instruction .emit OP_ALU_BIN .or\n" +" vp_TRIop_instruction .emit OP_ALU_TRI .or\n" +" vp_SWZ_instruction .emit OP_ALU_SWZ;\n" +"ALUInstruction\n" +" fp_VECTORop_instruction .emit OP_ALU_VECTOR .or\n" +" fp_SCALARop_instruction .emit OP_ALU_SCALAR .or\n" +" fp_BINSCop_instruction .emit OP_ALU_BINSC .or\n" +" fp_BINop_instruction .emit OP_ALU_BIN .or\n" +" fp_TRIop_instruction .emit OP_ALU_TRI .or\n" +" fp_SWZ_instruction .emit OP_ALU_SWZ;\n" +"TexInstruction\n" +" SAMPLE_instruction .emit OP_TEX_SAMPLE .or\n" +" KIL_instruction .emit OP_TEX_KIL;\n" +"ARL_instruction\n" +" \"ARL\" .emit OP_ARL .and space_dst .and maskedAddrReg .and comma .and vp_scalarSrcReg;\n" +"fp_VECTORop_instruction\n" +" fp_VECTORop .and space_dst .and fp_maskedDstReg .and comma .and vectorSrcReg;\n" +"vp_VECTORop_instruction\n" +" vp_VECTORop .and space_dst .and vp_maskedDstReg .and comma .and swizzleSrcReg;\n" +"fp_VECTORop\n" +" \"ABS\" .emit OP_ABS .or \"ABS_SAT\" .emit OP_ABS_SAT .or\n" +" \"FLR\" .emit OP_FLR .or \"FLR_SAT\" .emit OP_FLR_SAT .or\n" +" \"FRC\" .emit OP_FRC .or \"FRC_SAT\" .emit OP_FRC_SAT .or\n" +" \"LIT\" .emit OP_LIT .or \"LIT_SAT\" .emit OP_LIT_SAT .or\n" +" \"MOV\" .emit OP_MOV .or \"MOV_SAT\" .emit OP_MOV_SAT;\n" +"vp_VECTORop\n" +" \"ABS\" .emit OP_ABS .or\n" +" \"FLR\" .emit OP_FLR .or\n" +" \"FRC\" .emit OP_FRC .or\n" +" \"LIT\" .emit OP_LIT .or\n" +" \"MOV\" .emit OP_MOV;\n" +"fp_SCALARop_instruction\n" +" fp_SCALARop .and space_dst .and fp_maskedDstReg .and comma .and fp_scalarSrcReg;\n" +"vp_SCALARop_instruction\n" +" vp_SCALARop .and space_dst .and vp_maskedDstReg .and comma .and vp_scalarSrcReg;\n" +"fp_SCALARop\n" +" \"COS\" .emit OP_COS .or \"COS_SAT\" .emit OP_COS_SAT .or\n" +" \"EX2\" .emit OP_EX2 .or \"EX2_SAT\" .emit OP_EX2_SAT .or\n" +" \"LG2\" .emit OP_LG2 .or \"LG2_SAT\" .emit OP_LG2_SAT .or\n" +" \"RCP\" .emit OP_RCP .or \"RCP_SAT\" .emit OP_RCP_SAT .or\n" +" \"RSQ\" .emit OP_RSQ .or \"RSQ_SAT\" .emit OP_RSQ_SAT .or\n" +" \"SIN\" .emit OP_SIN .or \"SIN_SAT\" .emit OP_SIN_SAT .or\n" +" \"SCS\" .emit OP_SCS .or \"SCS_SAT\" .emit OP_SCS_SAT;\n" +"vp_SCALARop\n" +" \"EX2\" .emit OP_EX2 .or\n" +" \"EXP\" .emit OP_EXP .or\n" +" \"LG2\" .emit OP_LG2 .or\n" +" \"LOG\" .emit OP_LOG .or\n" +" \"RCP\" .emit OP_RCP .or\n" +" \"RSQ\" .emit OP_RSQ;\n" +"fp_BINSCop_instruction\n" +" fp_BINSCop .and space_dst .and fp_maskedDstReg .and comma .and fp_scalarSrcReg .and comma .and\n" +" fp_scalarSrcReg;\n" +"vp_BINSCop_instruction\n" +" vp_BINSCop .and space_dst .and vp_maskedDstReg .and comma .and vp_scalarSrcReg .and comma .and\n" +" vp_scalarSrcReg;\n" +"fp_BINSCop\n" +" \"POW\" .emit OP_POW .or \"POW_SAT\" .emit OP_POW_SAT;\n" +"vp_BINSCop\n" +" \"POW\" .emit OP_POW;\n" +"fp_BINop_instruction\n" +" fp_BINop .and space_dst .and fp_maskedDstReg .and comma .and vectorSrcReg .and comma .and\n" +" vectorSrcReg;\n" +"vp_BINop_instruction\n" +" vp_BINop .and space_dst .and vp_maskedDstReg .and comma .and swizzleSrcReg .and comma .and\n" +" swizzleSrcReg;\n" +"fp_BINop\n" +" \"ADD\" .emit OP_ADD .or \"ADD_SAT\" .emit OP_ADD_SAT .or\n" +" \"DP3\" .emit OP_DP3 .or \"DP3_SAT\" .emit OP_DP3_SAT .or\n" +" \"DP4\" .emit OP_DP4 .or \"DP4_SAT\" .emit OP_DP4_SAT .or\n" +" \"DPH\" .emit OP_DPH .or \"DPH_SAT\" .emit OP_DPH_SAT .or\n" +" \"DST\" .emit OP_DST .or \"DST_SAT\" .emit OP_DST_SAT .or\n" +" \"MAX\" .emit OP_MAX .or \"MAX_SAT\" .emit OP_MAX_SAT .or\n" +" \"MIN\" .emit OP_MIN .or \"MIN_SAT\" .emit OP_MIN_SAT .or\n" +" \"MUL\" .emit OP_MUL .or \"MUL_SAT\" .emit OP_MUL_SAT .or\n" +" \"SGE\" .emit OP_SGE .or \"SGE_SAT\" .emit OP_SGE_SAT .or\n" +" \"SLT\" .emit OP_SLT .or \"SLT_SAT\" .emit OP_SLT_SAT .or\n" +" \"SUB\" .emit OP_SUB .or \"SUB_SAT\" .emit OP_SUB_SAT .or\n" +" \"XPD\" .emit OP_XPD .or \"XPD_SAT\" .emit OP_XPD_SAT;\n" +"vp_BINop\n" +" \"ADD\" .emit OP_ADD .or\n" +" \"DP3\" .emit OP_DP3 .or\n" +" \"DP4\" .emit OP_DP4 .or\n" +" \"DPH\" .emit OP_DPH .or\n" +" \"DST\" .emit OP_DST .or\n" +" \"MAX\" .emit OP_MAX .or\n" +" \"MIN\" .emit OP_MIN .or\n" +" \"MUL\" .emit OP_MUL .or\n" +" \"SGE\" .emit OP_SGE .or\n" +" \"SLT\" .emit OP_SLT .or\n" +" \"SUB\" .emit OP_SUB .or\n" +" \"XPD\" .emit OP_XPD;\n" +"fp_TRIop_instruction\n" +" fp_TRIop .and space_dst .and fp_maskedDstReg .and comma .and vectorSrcReg .and comma .and\n" +" vectorSrcReg .and comma .and vectorSrcReg;\n" +"vp_TRIop_instruction\n" +" vp_TRIop .and space_dst .and vp_maskedDstReg .and comma .and swizzleSrcReg .and comma .and\n" +" swizzleSrcReg .and comma .and swizzleSrcReg;\n" +"fp_TRIop\n" +" \"CMP\" .emit OP_CMP .or \"CMP_SAT\" .emit OP_CMP_SAT .or\n" +" \"LRP\" .emit OP_LRP .or \"LRP_SAT\" .emit OP_LRP_SAT .or\n" +" \"MAD\" .emit OP_MAD .or \"MAD_SAT\" .emit OP_MAD_SAT;\n" +"vp_TRIop\n" +" \"MAD\" .emit OP_MAD;\n" +"fp_SWZ_instruction\n" +" SWZop .and space_dst .and fp_maskedDstReg .and comma .and fp_srcReg .and comma .and\n" +" fp_extendedSwizzle .error EXT_SWIZ_COMP_EXPECTED;\n" +"vp_SWZ_instruction\n" +" \"SWZ\" .emit OP_SWZ .and space_dst .and vp_maskedDstReg .and comma .and vp_srcReg .and comma .and\n" +" vp_extendedSwizzle .error EXT_SWIZ_COMP_EXPECTED;\n" +"SWZop\n" +" \"SWZ\" .emit OP_SWZ .or \"SWZ_SAT\" .emit OP_SWZ_SAT;\n" +"SAMPLE_instruction\n" +" SAMPLEop .and space_dst .and fp_maskedDstReg .and comma .and vectorSrcReg .and comma .and\n" +" texImageUnit .and comma .and texTarget .error TEX_TARGET_EXPECTED;\n" +"SAMPLEop\n" +" \"TEX\" .emit OP_TEX .or \"TEX_SAT\" .emit OP_TEX_SAT .or\n" +" \"TXB\" .emit OP_TXB .or \"TXB_SAT\" .emit OP_TXB_SAT .or\n" +" \"TXP\" .emit OP_TXP .or \"TXP_SAT\" .emit OP_TXP_SAT;\n" +"KIL_instruction\n" +" \"KIL\" .emit OP_KIL .and space_src .and vectorSrcReg;\n" +"texImageUnit\n" +" \"texture\" .error TEXTURE_EXPECTED .and optTexImageUnitNum;\n" +"texTarget\n" +" \"1D\" .emit TEXTARGET_1D .or\n" +" \"2D\" .emit TEXTARGET_2D .or\n" +" \"3D\" .emit TEXTARGET_3D .or\n" +" .if (texture_rectangle != 0x00) \"RECT\" .emit TEXTARGET_RECT .or\n" +" \"CUBE\" .emit TEXTARGET_CUBE .or\n" +" .if (ARB_fragment_program_shadow != 0x00) shadowTarget;\n" +"shadowTarget\n" +" \"SHADOW1D\" .emit TEXTARGET_SHADOW1D .or\n" +" \"SHADOW2D\" .emit TEXTARGET_SHADOW2D .or\n" +" .if (texture_rectangle != 0x00) \"SHADOWRECT\" .emit TEXTARGET_SHADOWRECT;\n" +"optTexImageUnitNum\n" +" optTexImageUnitNum_1 .or .true .emit 0x00;\n" +"optTexImageUnitNum_1\n" +" lbracket_ne .and texImageUnitNum .and rbracket;\n" +"texImageUnitNum\n" +" integer;\n" +"fp_scalarSrcReg\n" +" optionalSign .and fp_srcReg .and fp_scalarSuffix;\n" +"vp_scalarSrcReg\n" +" optionalSign .and vp_srcReg .and vp_scalarSuffix;\n" +"swizzleSrcReg\n" +" optionalSign .and vp_srcReg .and swizzleSuffix;\n" +"vectorSrcReg\n" +" optionalSign .and fp_srcReg .and optionalSuffix;\n" +"fp_maskedDstReg\n" +" fp_dstReg .and fp_optionalMask;\n" +"vp_maskedDstReg\n" +" vp_dstReg .and vp_optionalMask;\n" +"maskedAddrReg\n" +" addrReg .error ADDRESS_REGISTER_EXPECTED .and addrWriteMask;\n" +"fp_extendedSwizzle\n" +" rgbaExtendedSwizzle .or xyzwExtendedSwizzle;\n" +"vp_extendedSwizzle\n" +" extSwizComp .and comma .and\n" +" extSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" extSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" extSwizComp .error EXT_SWIZ_COMP_EXPECTED;\n" +"xyzwExtendedSwizzle\n" +" xyzwExtSwizComp .and comma .and\n" +" xyzwExtSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" xyzwExtSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" xyzwExtSwizComp .error EXT_SWIZ_COMP_EXPECTED;\n" +"rgbaExtendedSwizzle\n" +" rgbaExtendedSwizzle_1 .or rgbaExtendedSwizzle_2 .or rgbaExtendedSwizzle_3 .or\n" +" rgbaExtendedSwizzle_4;\n" +"rgbaExtendedSwizzle_1\n" +" rgbaExtSwizComp_digit .and comma .and rgbaExtSwizComp_digit .and comma .and\n" +" rgbaExtSwizComp_digit .and comma .and rgbaExtSwizComp;\n" +"rgbaExtendedSwizzle_2\n" +" rgbaExtSwizComp_digit .and comma .and rgbaExtSwizComp_digit .and comma .and\n" +" rgbaExtSwizComp_alpha .and comma .and rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED;\n" +"rgbaExtendedSwizzle_3\n" +" rgbaExtSwizComp_digit .and comma .and rgbaExtSwizComp_alpha .and comma .and\n" +" rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED;\n" +"rgbaExtendedSwizzle_4\n" +" rgbaExtSwizComp_alpha .and comma .and \n" +"rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED .and comma .and\n" +" rgbaExtSwizComp .error EXT_SWIZ_COMP_EXPECTED;\n" +"xyzwExtSwizComp\n" +" optionalSign .and xyzwExtSwizSel;\n" +"rgbaExtSwizComp\n" +" optionalSign .and rgbaExtSwizSel;\n" +"rgbaExtSwizComp_digit\n" +" optionalSign .and rgbaExtSwizSel_digit;\n" +"rgbaExtSwizComp_alpha\n" +" optionalSign .and rgbaExtSwizSel_alpha;\n" +"extSwizComp\n" +" optionalSign .and extSwizSel;\n" +"xyzwExtSwizSel\n" +" \"0\" .emit COMPONENT_0 .or \"1\" .emit COMPONENT_1 .or xyzwComponent_single;\n" +"rgbaExtSwizSel\n" +" rgbaExtSwizSel_digit .or rgbaExtSwizSel_alpha;\n" +"rgbaExtSwizSel_digit\n" +" \"0\" .emit COMPONENT_0 .or \"1\" .emit COMPONENT_1;\n" +"rgbaExtSwizSel_alpha\n" +" rgbaComponent_single;\n" +"extSwizSel\n" +" \"0\" .emit COMPONENT_0 .or \"1\" .emit COMPONENT_1 .or vp_component_single;\n" +"fp_srcReg\n" +" fp_srcReg_1 .error SOURCE_REGISTER_EXPECTED;\n" +"vp_srcReg\n" +" vp_srcReg_1 .error SOURCE_REGISTER_EXPECTED;\n" +"fp_srcReg_1\n" +" fragmentAttribReg .emit REGISTER_ATTRIB .or\n" +" fp_progParamReg .emit REGISTER_PARAM .or\n" +" fp_temporaryReg .emit REGISTER_ESTABLISHED_NAME;\n" +"vp_srcReg_1\n" +" vertexAttribReg .emit REGISTER_ATTRIB .or\n" +" vp_progParamReg .emit REGISTER_PARAM .or\n" +" vp_temporaryReg .emit REGISTER_ESTABLISHED_NAME;\n" +"fp_dstReg\n" +" fp_dstReg_1 .error DESTINATION_REGISTER_EXPECTED;\n" +"vp_dstReg\n" +" vp_dstReg_1 .error DESTINATION_REGISTER_EXPECTED;\n" +"fp_dstReg_1\n" +" fragmentResultReg .emit REGISTER_RESULT .or\n" +" fp_temporaryReg .emit REGISTER_ESTABLISHED_NAME;\n" +"vp_dstReg_1\n" +" vertexResultReg .emit REGISTER_RESULT .or\n" +" vp_temporaryReg .emit REGISTER_ESTABLISHED_NAME;\n" +"fragmentAttribReg\n" +" fragAttribBinding;\n" +"vertexAttribReg\n" +" vtxAttribBinding;\n" +"fp_temporaryReg\n" +" fp_establishedName_no_error_on_identifier;\n" +"vp_temporaryReg\n" +" vp_establishedName_no_error_on_identifier;\n" +"fp_progParamReg\n" +" fp_paramSingleItemUse .or fp_progParamReg_1 .or fp_progParamSingle;\n" +"vp_progParamReg\n" +" vp_paramSingleItemUse .or vp_progParamReg_1 .or vp_progParamSingle;\n" +"fp_progParamReg_1\n" +" fp_progParamArray .emit PARAM_ARRAY_ELEMENT .and lbracket_ne .and progParamArrayAbs .and\n" +" rbracket;\n" +"vp_progParamReg_1\n" +" vp_progParamArray .emit PARAM_ARRAY_ELEMENT .and lbracket_ne .and progParamArrayMem .and\n" +" rbracket;\n" +"fp_progParamSingle\n" +" .false;\n" +"vp_progParamSingle\n" +" .false;\n" +"fp_progParamArray\n" +" fp_establishedName_no_error_on_identifier;\n" +"vp_progParamArray\n" +" vp_establishedName_no_error_on_identifier;\n" +"progParamArrayMem\n" +" progParamArrayAbs .or progParamArrayRel;\n" +"progParamArrayAbs\n" +" integer_ne .emit ARRAY_INDEX_ABSOLUTE;\n" +"progParamArrayRel\n" +" addrReg .error ADDRESS_REGISTER_OR_INTEGER_EXPECTED .emit ARRAY_INDEX_RELATIVE .and\n" +" addrComponent .and addrRegRelOffset;\n" +"addrRegRelOffset\n" +" addrRegRelOffset_1 .or addrRegRelOffset_2 .or .true .emit 0x00;\n" +"addrRegRelOffset_1\n" +" plus_ne .and addrRegPosOffset;\n" +"addrRegRelOffset_2\n" +" minus_ne .and addrRegNegOffset;\n" +"addrRegPosOffset\n" +" integer_0_63;\n" +"addrRegNegOffset\n" +" integer_0_64;\n" +"fragmentResultReg\n" +" fp_resultBinding;\n" +"vertexResultReg\n" +" vp_resultBinding;\n" +"addrReg\n" +" vp_establishedName_no_error_on_identifier;\n" +"addrComponent\n" +" dot .and \"x\" .error INVALID_ADDRESS_COMPONENT .emit COMPONENT_X .emit COMPONENT_X\n" +" .emit COMPONENT_X .emit COMPONENT_X;\n" +"addrWriteMask\n" +" dot .and \"x\" .error INVALID_ADDRESS_WRITEMASK .emit 0x08;\n" +"fp_scalarSuffix\n" +" dot .and fp_component_single .error INVALID_COMPONENT;\n" +"vp_scalarSuffix\n" +" dot .and vp_component_single .error INVALID_COMPONENT;\n" +"swizzleSuffix\n" +" swizzleSuffix_1 .or\n" +" .true .emit COMPONENT_X .emit COMPONENT_Y .emit COMPONENT_Z .emit COMPONENT_W;\n" +"swizzleSuffix_1\n" +" dot_ne .and swizzleSuffix_2 .error INVALID_SUFFIX;\n" +"swizzleSuffix_2\n" +" swizzleSuffix_3 .or swizzleSuffix_4;\n" +"swizzleSuffix_3\n" +" vp_component_multi .and vp_component_multi .and vp_component_multi .error INVALID_COMPONENT .and\n" +" vp_component_multi .error INVALID_COMPONENT;\n" +"swizzleSuffix_4\n" +" \"x\" .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .or\n" +" \"y\" .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .or\n" +" \"z\" .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .or\n" +" \"w\" .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W;\n" +"optionalSuffix\n" +" optionalSuffix_1 .or\n" +" .true .emit COMPONENT_X .emit COMPONENT_Y .emit COMPONENT_Z .emit COMPONENT_W;\n" +"optionalSuffix_1\n" +" dot_ne .and optionalSuffix_2 .error INVALID_SUFFIX;\n" +"optionalSuffix_2\n" +" optionalSuffix_3 .or optionalSuffix_4 .or optionalSuffix_5;\n" +"optionalSuffix_3\n" +" xyzwComponent_multi .and xyzwComponent_multi .and\n" +" xyzwComponent_multi .error INVALID_COMPONENT .and xyzwComponent_multi .error INVALID_COMPONENT;\n" +"optionalSuffix_4\n" +" rgbaComponent_multi .and rgbaComponent_multi .and\n" +" rgbaComponent_multi .error INVALID_COMPONENT .and rgbaComponent_multi .error INVALID_COMPONENT;\n" +"optionalSuffix_5\n" +" \"x\" .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .or\n" +" \"y\" .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .or\n" +" \"z\" .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .or\n" +" \"w\" .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W .or\n" +" \"r\" .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .emit COMPONENT_X .or\n" +" \"g\" .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .emit COMPONENT_Y .or\n" +" \"b\" .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .emit COMPONENT_Z .or\n" +" \"a\" .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W .emit COMPONENT_W;\n" +"fp_component_single\n" +" xyzwComponent_single .or rgbaComponent_single;\n" +"vp_component_multi\n" +" 'x' .emit COMPONENT_X .or 'y' .emit COMPONENT_Y .or 'z' .emit COMPONENT_Z .or\n" +" 'w' .emit COMPONENT_W;\n" +"vp_component_single\n" +" \"x\" .emit COMPONENT_X .or \"y\" .emit COMPONENT_Y .or \"z\" .emit COMPONENT_Z .or\n" +" \"w\" .emit COMPONENT_W;\n" +"xyzwComponent_multi\n" +" 'x' .emit COMPONENT_X .or 'y' .emit COMPONENT_Y .or 'z' .emit COMPONENT_Z .or\n" +" 'w' .emit COMPONENT_W;\n" +"xyzwComponent_single\n" +" \"x\" .emit COMPONENT_X .or \"y\" .emit COMPONENT_Y .or \"z\" .emit COMPONENT_Z .or\n" +" \"w\" .emit COMPONENT_W;\n" +"rgbaComponent_multi\n" +" 'r' .emit COMPONENT_X .or 'g' .emit COMPONENT_Y .or 'b' .emit COMPONENT_Z .or\n" +" 'a' .emit COMPONENT_W;\n" +"rgbaComponent_single\n" +" \"r\" .emit COMPONENT_X .or \"g\" .emit COMPONENT_Y .or \"b\" .emit COMPONENT_Z .or\n" +" \"a\" .emit COMPONENT_W;\n" +"fp_optionalMask\n" +" rgbaMask .or xyzwMask .or .true .emit 0x0F;\n" +"vp_optionalMask\n" +" xyzwMask .or .true .emit 0x0F;\n" +"xyzwMask\n" +" dot_ne .and xyzwMask_1 .error INVALID_WRITEMASK;\n" +"xyzwMask_1\n" +" \"xyzw\" .emit 0x0F .or \"xyz\" .emit 0x0E .or \"xyw\" .emit 0x0D .or \"xy\" .emit 0x0C .or\n" +" \"xzw\" .emit 0x0B .or \"xz\" .emit 0x0A .or \"xw\" .emit 0x09 .or \"x\" .emit 0x08 .or\n" +" \"yzw\" .emit 0x07 .or \"yz\" .emit 0x06 .or \"yw\" .emit 0x05 .or \"y\" .emit 0x04 .or\n" +" \"zw\" .emit 0x03 .or \"z\" .emit 0x02 .or \"w\" .emit 0x01;\n" +"rgbaMask\n" +" dot_ne .and rgbaMask_1;\n" +"rgbaMask_1\n" +" \"rgba\" .emit 0x0F .or \"rgb\" .emit 0x0E .or \"rga\" .emit 0x0D .or \"rg\" .emit 0x0C .or\n" +" \"rba\" .emit 0x0B .or \"rb\" .emit 0x0A .or \"ra\" .emit 0x09 .or \"r\" .emit 0x08 .or\n" +" \"gba\" .emit 0x07 .or \"gb\" .emit 0x06 .or \"ga\" .emit 0x05 .or \"g\" .emit 0x04 .or\n" +" \"ba\" .emit 0x03 .or \"b\" .emit 0x02 .or \"a\" .emit 0x01;\n" +"fp_namingStatement\n" +" fp_ATTRIB_statement .emit ATTRIB .or\n" +" fp_PARAM_statement .emit PARAM .or\n" +" fp_TEMP_statement .emit TEMP .or\n" +" fp_OUTPUT_statement .emit OUTPUT .or\n" +" fp_ALIAS_statement .emit ALIAS;\n" +"vp_namingStatement\n" +" vp_ATTRIB_statement .emit ATTRIB .or\n" +" vp_PARAM_statement .emit PARAM .or\n" +" vp_TEMP_statement .emit TEMP .or\n" +" ADDRESS_statement .emit ADDRESS .or\n" +" vp_OUTPUT_statement .emit OUTPUT .or\n" +" vp_ALIAS_statement .emit ALIAS;\n" +"fp_ATTRIB_statement\n" +" \"ATTRIB\" .and space .and fp_establishName .and equal .and\n" +" fragAttribBinding .error FRAGMENT_EXPECTED;\n" +"vp_ATTRIB_statement\n" +" \"ATTRIB\" .and space .and vp_establishName .and equal .and\n" +" vtxAttribBinding .error VERTEX_EXPECTED;\n" +"fragAttribBinding\n" +" \"fragment\" .and dot .and fragAttribItem .error INVALID_FRAGMENT_PROPERTY;\n" +"vtxAttribBinding\n" +" \"vertex\" .and dot .and vtxAttribItem .error INVALID_VERTEX_PROPERTY;\n" +"fragAttribItem\n" +" fragAttribItem_1 .emit FRAGMENT_ATTRIB_COLOR .or\n" +" fragAttribItem_2 .emit FRAGMENT_ATTRIB_TEXCOORD .or\n" +" .if (fog_coord != 0x00) \"fogcoord\" .emit FRAGMENT_ATTRIB_FOGCOORD .or\n" +" \"position\" .emit FRAGMENT_ATTRIB_POSITION;\n" +"fragAttribItem_1\n" +" \"color\" .and optColorType;\n" +"fragAttribItem_2\n" +" \"texcoord\" .and optTexCoordNum;\n" +"vtxAttribItem\n" +" \"position\" .emit VERTEX_ATTRIB_POSITION .or\n" +" .if (vertex_blend != 0x00) vtxAttribItem_1 .emit VERTEX_ATTRIB_WEIGHT .or\n" +" \"normal\" .emit VERTEX_ATTRIB_NORMAL .or\n" +" vtxAttribItem_2 .emit VERTEX_ATTRIB_COLOR .or\n" +" \"fogcoord\" .emit VERTEX_ATTRIB_FOGCOORD .or\n" +" vtxAttribItem_3 .emit VERTEX_ATTRIB_TEXCOORD .or\n" +" .if (matrix_palette != 0x00) vtxAttribItem_4 .emit VERTEX_ATTRIB_MATRIXINDEX .or\n" +" vtxAttribItem_5 .emit VERTEX_ATTRIB_GENERIC;\n" +"vtxAttribItem_1\n" +" \"weight\" .and vtxOptWeightNum;\n" +"vtxAttribItem_2\n" +" \"color\" .and optColorType;\n" +"vtxAttribItem_3\n" +" \"texcoord\" .and optTexCoordNum;\n" +"vtxAttribItem_4\n" +" \"matrixindex\" .and lbracket .and vtxWeightNum .and rbracket;\n" +"vtxAttribItem_5\n" +" \"attrib\" .and lbracket .and vtxAttribNum .and rbracket;\n" +"vtxAttribNum\n" +" integer;\n" +"vtxOptWeightNum\n" +" vtxOptWeightNum_1 .or .true .emit 0x00;\n" +"vtxOptWeightNum_1\n" +" lbracket_ne .and vtxWeightNum .and rbracket;\n" +"vtxWeightNum\n" +" integer;\n" +"fp_PARAM_statement\n" +" fp_PARAM_multipleStmt .or fp_PARAM_singleStmt;\n" +"vp_PARAM_statement\n" +" vp_PARAM_multipleStmt .or vp_PARAM_singleStmt;\n" +"fp_PARAM_singleStmt\n" +" \"PARAM\" .and space .and fp_establishName .and .true .emit 0x00 .and fp_paramSingleInit .and\n" +" .true .emit PARAM_NULL;\n" +"vp_PARAM_singleStmt\n" +" \"PARAM\" .and space .and vp_establishName .and .true .emit 0x00 .and vp_paramSingleInit .and\n" +" .true .emit PARAM_NULL;\n" +"fp_PARAM_multipleStmt\n" +" \"PARAM\" .and space .and fp_establishName .and lbracket_ne .and optArraySize .and rbracket .and\n" +" fp_paramMultipleInit .and .true .emit PARAM_NULL;\n" +"vp_PARAM_multipleStmt\n" +" \"PARAM\" .and space .and vp_establishName .and lbracket_ne .and optArraySize .and rbracket .and\n" +" vp_paramMultipleInit .and .true .emit PARAM_NULL;\n" +"optArraySize\n" +" optional_integer;\n" +"fp_paramSingleInit\n" +" equal .and fp_paramSingleItemDecl;\n" +"vp_paramSingleInit\n" +" equal .and vp_paramSingleItemDecl;\n" +"fp_paramMultipleInit\n" +" equal .and lbrace .and fp_paramMultInitList .and rbrace;\n" +"vp_paramMultipleInit\n" +" equal .and lbrace .and vp_paramMultInitList .and rbrace;\n" +"fp_paramMultInitList\n" +" fp_paramMultInitList_1 .or fp_paramMultipleItem;\n" +"vp_paramMultInitList\n" +" vp_paramMultInitList_1 .or vp_paramMultipleItem;\n" +"fp_paramMultInitList_1\n" +" fp_paramMultipleItem .and comma_ne .and fp_paramMultInitList;\n" +"vp_paramMultInitList_1\n" +" vp_paramMultipleItem .and comma_ne .and vp_paramMultInitList;\n" +"fp_paramSingleItemDecl\n" +" fp_stateSingleItem .emit PARAM_STATE_ELEMENT .or\n" +" programSingleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstDecl .emit PARAM_CONSTANT;\n" +"vp_paramSingleItemDecl\n" +" vp_stateSingleItem .emit PARAM_STATE_ELEMENT .or\n" +" programSingleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstDecl .emit PARAM_CONSTANT;\n" +"fp_paramSingleItemUse\n" +" fp_stateSingleItem .emit PARAM_STATE_ELEMENT .or\n" +" programSingleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstUse .emit PARAM_CONSTANT;\n" +"vp_paramSingleItemUse\n" +" vp_stateSingleItem .emit PARAM_STATE_ELEMENT .or\n" +" programSingleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstUse .emit PARAM_CONSTANT;\n" +"fp_paramMultipleItem\n" +" fp_stateMultipleItem .emit PARAM_STATE_ELEMENT .or\n" +" programMultipleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstDecl .emit PARAM_CONSTANT;\n" +"vp_paramMultipleItem\n" +" vp_stateMultipleItem .emit PARAM_STATE_ELEMENT .or\n" +" programMultipleItem .emit PARAM_PROGRAM_ELEMENT .or\n" +" paramConstDecl .emit PARAM_CONSTANT;\n" +"fp_stateMultipleItem\n" +" stateMultipleItem_1 .or fp_stateSingleItem;\n" +"vp_stateMultipleItem\n" +" stateMultipleItem_1 .or vp_stateSingleItem;\n" +"stateMultipleItem_1\n" +" \"state\" .and dot .and stateMatrixRows .emit STATE_MATRIX_ROWS;\n" +"fp_stateSingleItem\n" +" \"state\" .and dot .and fp_stateSingleItem_1 .error INVALID_STATE_PROPERTY;\n" +"vp_stateSingleItem\n" +" \"state\" .and dot .and vp_stateSingleItem_1 .error INVALID_STATE_PROPERTY;\n" +"fp_stateSingleItem_1\n" +" stateSingleItem_1 .or stateSingleItem_2 .or stateSingleItem_3 .or stateSingleItem_4 .or\n" +" stateSingleItem_5 .or stateSingleItem_7 .or stateSingleItem_8 .or stateSingleItem_11;\n" +"vp_stateSingleItem_1\n" +" stateSingleItem_1 .or stateSingleItem_2 .or stateSingleItem_3 .or stateSingleItem_4 .or\n" +" stateSingleItem_6 .or stateSingleItem_7 .or stateSingleItem_9 .or stateSingleItem_10 .or\n" +" stateSingleItem_11;\n" +"stateSingleItem_1\n" +" stateMaterialItem .emit STATE_MATERIAL;\n" +"stateSingleItem_2\n" +" stateLightItem .emit STATE_LIGHT;\n" +"stateSingleItem_3\n" +" stateLightModelItem .emit STATE_LIGHT_MODEL;\n" +"stateSingleItem_4\n" +" stateLightProdItem .emit STATE_LIGHT_PROD;\n" +"stateSingleItem_5\n" +" stateTexEnvItem .emit STATE_TEX_ENV;\n" +"stateSingleItem_6\n" +" stateTexGenItem .emit STATE_TEX_GEN;\n" +"stateSingleItem_7\n" +" stateFogItem .emit STATE_FOG;\n" +"stateSingleItem_8\n" +" stateDepthItem .emit STATE_DEPTH;\n" +"stateSingleItem_9\n" +" stateClipPlaneItem .emit STATE_CLIP_PLANE;\n" +"stateSingleItem_10\n" +" statePointItem .emit STATE_POINT;\n" +"stateSingleItem_11\n" +" stateMatrixRow .emit STATE_MATRIX_ROWS;\n" +"stateMaterialItem\n" +" \"material\" .and optFaceType .and dot .and stateMatProperty .error INVALID_MATERIAL_PROPERTY;\n" +"stateMatProperty\n" +" \"ambient\" .emit MATERIAL_AMBIENT .or\n" +" \"diffuse\" .emit MATERIAL_DIFFUSE .or\n" +" \"specular\" .emit MATERIAL_SPECULAR .or\n" +" \"emission\" .emit MATERIAL_EMISSION .or\n" +" \"shininess\" .emit MATERIAL_SHININESS;\n" +"stateLightItem\n" +" \"light\" .and lbracket .and stateLightNumber .and rbracket .and dot .and\n" +" stateLightProperty .error INVALID_LIGHT_PROPERTY;\n" +"stateLightProperty\n" +" \"ambient\" .emit LIGHT_AMBIENT .or\n" +" \"diffuse\" .emit LIGHT_DIFFUSE .or\n" +" \"specular\" .emit LIGHT_SPECULAR .or\n" +" \"position\" .emit LIGHT_POSITION .or\n" +" \"attenuation\" .emit LIGHT_ATTENUATION .or\n" +" stateLightProperty_1 .emit LIGHT_SPOT_DIRECTION .or\n" +" \"half\" .emit LIGHT_HALF;\n" +"stateLightProperty_1\n" +" \"spot\" .and dot .and stateSpotProperty .error INVALID_SPOT_PROPERTY;\n" +"stateSpotProperty\n" +" \"direction\";\n" +"stateLightModelItem\n" +" \"lightmodel\" .and stateLModProperty .error INVALID_LIGHTMODEL_PROPERTY;\n" +"stateLModProperty\n" +" stateLModProperty_1 .or stateLModProperty_2;\n" +"stateLModProperty_1\n" +" dot .and \"ambient\" .emit LIGHT_MODEL_AMBIENT;\n" +"stateLModProperty_2\n" +" stateLModProperty_3 .emit LIGHT_MODEL_SCENECOLOR;\n" +"stateLModProperty_3\n" +" optFaceType .and dot .and \"scenecolor\";\n" +"stateLightProdItem\n" +" \"lightprod\" .and lbracket .and stateLightNumber .and rbracket .and optFaceType .and dot .and\n" +" stateLProdProperty .error INVALID_LIGHTPROD_PROPERTY;\n" +"stateLProdProperty\n" +" \"ambient\" .emit LIGHT_PROD_AMBIENT .or\n" +" \"diffuse\" .emit LIGHT_PROD_DIFFUSE .or\n" +" \"specular\" .emit LIGHT_PROD_SPECULAR;\n" +"stateLightNumber\n" +" integer;\n" +"stateTexEnvItem\n" +" \"texenv\" .and optLegacyTexUnitNum .and dot .and\n" +" stateTexEnvProperty .error INVALID_TEXENV_PROPERTY;\n" +"stateTexEnvProperty\n" +" \"color\" .emit TEX_ENV_COLOR;\n" +"optLegacyTexUnitNum\n" +" lbracket_ne .and legacyTexUnitNum .and rbracket;\n" +"legacyTexUnitNum\n" +" integer;\n" +"stateTexGenItem\n" +" \"texgen\" .and optTexCoordNum .and dot .and stateTexGenType .error INVALID_TEXGEN_PROPERTY .and\n" +" dot .and stateTexGenCoord .error INVALID_TEXGEN_COORD;\n" +"stateTexGenType\n" +" \"eye\" .emit TEX_GEN_EYE .or\n" +" \"object\" .emit TEX_GEN_OBJECT;\n" +"stateTexGenCoord\n" +" \"s\" .emit COMPONENT_X .or\n" +" \"t\" .emit COMPONENT_Y .or\n" +" \"r\" .emit COMPONENT_Z .or\n" +" \"q\" .emit COMPONENT_W;\n" +"stateFogItem\n" +" \"fog\" .and dot .and stateFogProperty .error INVALID_FOG_PROPERTY;\n" +"stateFogProperty\n" +" \"color\" .emit FOG_COLOR .or\n" +" \"params\" .emit FOG_PARAMS;\n" +"stateDepthItem\n" +" \"depth\" .and dot .and stateDepthProperty .error INVALID_DEPTH_PROPERTY;\n" +"stateDepthProperty\n" +" \"range\" .emit DEPTH_RANGE;\n" +"stateClipPlaneItem\n" +" \"clip\" .and lbracket .and stateClipPlaneNum .and rbracket .and dot .and\n" +" \"plane\" .error INVALID_CLIPPLANE_PROPERTY;\n" +"stateClipPlaneNum\n" +" integer;\n" +"statePointItem\n" +" \"point\" .and dot .and statePointProperty .error INVALID_POINT_PROPERTY;\n" +"statePointProperty\n" +" \"size\" .emit POINT_SIZE .or\n" +" .if (point_parameters != 0x00) \"attenuation\" .emit POINT_ATTENUATION;\n" +"stateMatrixRow\n" +" stateMatrixItem .and dot .and \"row\" .error MATRIX_ROW_SELECTOR_OR_MODIFIER_EXPECTED .and\n" +" lbracket .and stateMatrixRowNum .and rbracket .emit 0x0;\n" +"stateMatrixRows\n" +" stateMatrixItem .and optMatrixRows;\n" +"optMatrixRows\n" +" optMatrixRows_1 .or .true .emit 0x0 .emit '3' .emit 0x0 .emit $;\n" +"optMatrixRows_1\n" +" dot_ne .and \"row\" .error MATRIX_ROW_SELECTOR_OR_MODIFIER_EXPECTED .and lbracket .and\n" +" stateMatrixRowNum .and dotdot .and stateMatrixRowNum .and rbracket;\n" +"stateMatrixItem\n" +" \"matrix\" .and dot .and stateMatrixName .error INVALID_MATRIX_NAME .and stateOptMatModifier;\n" +"stateOptMatModifier\n" +" stateOptMatModifier_1 .or .true .emit MATRIX_MODIFIER_IDENTITY;\n" +"stateOptMatModifier_1\n" +" dot_ne .and stateMatModifier;\n" +"stateMatModifier\n" +" \"inverse\" .emit MATRIX_MODIFIER_INVERSE .or\n" +" \"transpose\" .emit MATRIX_MODIFIER_TRANSPOSE .or\n" +" \"invtrans\" .emit MATRIX_MODIFIER_INVTRANS;\n" +"stateMatrixRowNum\n" +" integer_0_3;\n" +"stateMatrixName\n" +" stateMatrixName_1_1 .emit MATRIX_MODELVIEW .or\n" +" \"projection\" .emit MATRIX_PROJECTION .or\n" +" \"mvp\" .emit MATRIX_MVP .or\n" +" stateMatrixName_1_2 .emit MATRIX_TEXTURE .or\n" +" .if (matrix_palette != 0x00) stateMatrixName_1_3 .emit MATRIX_PALETTE .or\n" +" stateMatrixName_1_4 .emit MATRIX_PROGRAM;\n" +"stateMatrixName_1_1\n" +" \"modelview\" .and stateOptModMatNum;\n" +"stateMatrixName_1_2\n" +" \"texture\" .and optTexCoordNum;\n" +"stateMatrixName_1_3\n" +" \"palette\" .and lbracket .and statePaletteMatNum .and rbracket;\n" +"stateMatrixName_1_4\n" +" \"program\" .and lbracket .and stateProgramMatNum .and rbracket;\n" +"stateOptModMatNum\n" +" .if (vertex_blend != 0x00) stateOptModMatNum_1 .or\n" +" .true .emit 0x00;\n" +"stateOptModMatNum_1\n" +" lbracket_ne .and stateModMatNum .and rbracket;\n" +"stateModMatNum\n" +" integer;\n" +"optTexCoordNum\n" +" optTexCoordNum_1 .or .true .emit 0x00;\n" +"optTexCoordNum_1\n" +" lbracket_ne .and texCoordNum .and rbracket;\n" +"texCoordNum\n" +" integer;\n" +"statePaletteMatNum\n" +" integer;\n" +"stateProgramMatNum\n" +" integer;\n" +"programSingleItem\n" +" \"program\" .and dot .and programSingleItem_1 .error INVALID_PROGRAM_PROPERTY;\n" +"programSingleItem_1\n" +" progEnvParam .or progLocalParam;\n" +"programMultipleItem\n" +" \"program\" .and dot .and programMultipleItem_1 .error INVALID_PROGRAM_PROPERTY;\n" +"programMultipleItem_1\n" +" progEnvParams .or progLocalParams;\n" +"progEnvParams\n" +" \"env\" .emit PROGRAM_PARAM_ENV .and lbracket .and progEnvParamNums .and rbracket;\n" +"progEnvParamNums\n" +" progEnvParamNums_1 .or progEnvParamNums_2;\n" +"progEnvParamNums_1\n" +" progEnvParamNum .and dotdot_ne .and progEnvParamNum;\n" +"progEnvParamNums_2\n" +" progEnvParamNum .and .true .emit 0x00;\n" +"progEnvParam\n" +" \"env\" .emit PROGRAM_PARAM_ENV .and lbracket .and progEnvParamNum .and rbracket .emit 0x00;\n" +"progLocalParams\n" +" \"local\" .emit PROGRAM_PARAM_LOCAL .and lbracket .and progLocalParamNums .and rbracket;\n" +"progLocalParamNums\n" +" progLocalParamNums_1 .or progLocalParamNums_2;\n" +"progLocalParamNums_1\n" +" progLocalParamNum .and dotdot_ne .and progLocalParamNum;\n" +"progLocalParamNums_2\n" +" progLocalParamNum .and .true .emit 0x00;\n" +"progLocalParam\n" +" \"local\" .emit PROGRAM_PARAM_LOCAL .and lbracket .and progLocalParamNum .and rbracket .emit 0x00;\n" +"progEnvParamNum\n" +" integer;\n" +"progLocalParamNum\n" +" integer;\n" +"paramConstDecl\n" +" paramConstScalarDecl .emit CONSTANT_SCALAR .or paramConstVector .emit CONSTANT_VECTOR;\n" +"paramConstUse\n" +" paramConstScalarUse .emit CONSTANT_SCALAR .or paramConstVector .emit CONSTANT_VECTOR;\n" +"paramConstScalarDecl\n" +" signedFloatConstant;\n" +"paramConstScalarUse\n" +" floatConstant;\n" +"paramConstVector\n" +" paramConstVector_4 .emit 0x04 .or paramConstVector_3 .emit 0x03 .or\n" +" paramConstVector_2 .emit 0x02 .or paramConstVector_1 .emit 0x01;\n" +"paramConstVector_1\n" +" lbrace_ne .and signedFloatConstant .and rbrace;\n" +"paramConstVector_2\n" +" lbrace_ne .and signedFloatConstant .and comma_ne .and signedFloatConstant .and rbrace;\n" +"paramConstVector_3\n" +" lbrace_ne .and signedFloatConstant .and comma_ne .and signedFloatConstant .and comma_ne .and\n" +" signedFloatConstant .and rbrace;\n" +"paramConstVector_4\n" +" lbrace_ne .and signedFloatConstant .and comma_ne .and signedFloatConstant .and comma_ne .and\n" +" signedFloatConstant .and comma_ne .and signedFloatConstant .and rbrace;\n" +"signedFloatConstant\n" +" optionalSign .and floatConstant;\n" +"floatConstant\n" +" float;\n" +"optionalSign\n" +" optional_sign_ne;\n" +"fp_TEMP_statement\n" +" \"TEMP\" .and space .and fp_varNameList .and .true .emit 0x00;\n" +"vp_TEMP_statement\n" +" \"TEMP\" .and space .and vp_varNameList .and .true .emit 0x00;\n" +"ADDRESS_statement\n" +" \"ADDRESS\" .and space .and vp_varNameList .and .true .emit 0x00;\n" +"fp_varNameList\n" +" fp_varNameList_1 .or fp_establishName;\n" +"vp_varNameList\n" +" vp_varNameList_1 .or vp_establishName;\n" +"fp_varNameList_1\n" +" fp_establishName .and comma_ne .and fp_varNameList;\n" +"vp_varNameList_1\n" +" vp_establishName .and comma_ne .and vp_varNameList;\n" +"fp_OUTPUT_statement\n" +" \"OUTPUT\" .and space .and fp_establishName .and equal .and\n" +" fp_resultBinding .error RESULT_EXPECTED;\n" +"vp_OUTPUT_statement\n" +" \"OUTPUT\" .and space .and vp_establishName .and equal .and\n" +" vp_resultBinding .error RESULT_EXPECTED;\n" +"fp_resultBinding\n" +" \"result\" .and dot .and fp_resultBinding_1 .error INVALID_RESULT_PROPERTY;\n" +"vp_resultBinding\n" +" \"result\" .and dot .and vp_resultBinding_1 .error INVALID_RESULT_PROPERTY;\n" +"fp_resultBinding_1\n" +" \"color\" .emit FRAGMENT_RESULT_COLOR .or\n" +" \"depth\" .emit FRAGMENT_RESULT_DEPTH;\n" +"vp_resultBinding_1\n" +" .if (ARB_position_invariant == 0x00) \"position\" .emit VERTEX_RESULT_POSITION .or\n" +" resultColBinding .emit VERTEX_RESULT_COLOR .or\n" +" \"fogcoord\" .emit VERTEX_RESULT_FOGCOORD .or\n" +" \"pointsize\" .emit VERTEX_RESULT_POINTSIZE .or\n" +" vp_resultBinding_2 .emit VERTEX_RESULT_TEXCOORD;\n" +"vp_resultBinding_2\n" +" \"texcoord\" .and optTexCoordNum;\n" +"resultColBinding\n" +" \"color\" .and optFaceType .and optColorType;\n" +"optFaceType\n" +" FaceType .or .true .emit FACE_FRONT;\n" +"FaceType\n" +" dot_ne .and FaceProperty;\n" +"FaceProperty\n" +" \"front\" .emit FACE_FRONT .or \"back\" .emit FACE_BACK;\n" +"optColorType\n" +" ColorType .or .true .emit COLOR_PRIMARY;\n" +"ColorType\n" +" dot_ne .and ColorProperty;\n" +"ColorProperty\n" +" \"primary\" .emit COLOR_PRIMARY .or\n" +" .if (secondary_color != 0x00) \"secondary\" .emit COLOR_SECONDARY;\n" +"fp_ALIAS_statement\n" +" \"ALIAS\" .and fp_ALIAS_statement_1 .error IDENTIFIER_EXPECTED .and equal .and fp_establishedName;\n" +"vp_ALIAS_statement\n" +" \"ALIAS\" .and vp_ALIAS_statement_1 .error IDENTIFIER_EXPECTED .and equal .and vp_establishedName;\n" +"fp_ALIAS_statement_1\n" +" space .and fp_establishName;\n" +"vp_ALIAS_statement_1\n" +" space .and vp_establishName;\n" +"fp_establishName\n" +" fp_identifier;\n" +"vp_establishName\n" +" vp_identifier;\n" +"fp_establishedName\n" +" fp_identifier;\n" +"vp_establishedName\n" +" vp_identifier;\n" +"fp_establishedName_no_error_on_identifier\n" +" fp_identifier_ne;\n" +"vp_establishedName_no_error_on_identifier\n" +" vp_identifier_ne;\n" +"fp_identifier\n" +" fp_identifier_ne .error IDENTIFIER_EXPECTED;\n" +"vp_identifier\n" +" vp_identifier_ne .error IDENTIFIER_EXPECTED;\n" +"fp_identifier_ne\n" +" fp_not_reserved_identifier .and identifier_ne;\n" +"vp_identifier_ne\n" +" vp_not_reserved_identifier .and identifier_ne;\n" +"fp_not_reserved_identifier\n" +" fp_not_reserved_identifier_1 .or .true;\n" +"fp_not_reserved_identifier_1\n" +" fp_reserved_identifier .and .false .error RESERVED_KEYWORD;\n" +"vp_not_reserved_identifier\n" +" vp_not_reserved_identifier_1 .or .true;\n" +"vp_not_reserved_identifier_1\n" +" vp_reserved_identifier .and .false .error RESERVED_KEYWORD;\n" +"fp_reserved_identifier\n" +" \"ABS\" .or \"ABS_SAT\" .or \"ADD\" .or \"ADD_SAT\" .or \"ALIAS\" .or \"ATTRIB\" .or \"CMP\" .or \"CMP_SAT\" .or\n" +" \"COS\" .or \"COS_SAT\" .or \"DP3\" .or \"DP3_SAT\" .or \"DP4\" .or \"DP4_SAT\" .or \"DPH\" .or \"DPH_SAT\" .or\n" +" \"DST\" .or \"DST_SAT\" .or \"END\" .or \"EX2\" .or \"EX2_SAT\" .or \"FLR\" .or \"FLR_SAT\" .or \"FRC\" .or\n" +" \"FRC_SAT\" .or \"KIL\" .or \"LG2\" .or \"LG2_SAT\" .or \"LIT\" .or \"LIT_SAT\" .or \"LRP\" .or \"LRP_SAT\" .or\n" +" \"MAD\" .or \"MAD_SAT\" .or \"MAX\" .or \"MAX_SAT\" .or \"MIN\" .or \"MIN_SAT\" .or \"MOV\" .or \"MOV_SAT\" .or\n" +" \"MUL\" .or \"MUL_SAT\" .or \"OPTION\" .or \"OUTPUT\" .or \"PARAM\" .or \"POW\" .or \"POW_SAT\" .or \"RCP\" .or\n" +" \"RCP_SAT\" .or \"RSQ\" .or \"RSQ_SAT\" .or \"SIN\" .or \"SIN_SAT\" .or \"SCS\" .or \"SCS_SAT\" .or \"SGE\" .or\n" +" \"SGE_SAT\" .or \"SLT\" .or \"SLT_SAT\" .or \"SUB\" .or \"SUB_SAT\" .or \"SWZ\" .or \"SWZ_SAT\" .or \"TEMP\" .or\n" +" \"TEX\" .or \"TEX_SAT\" .or \"TXB\" .or \"TXB_SAT\" .or \"TXP\" .or \"TXP_SAT\" .or \"XPD\" .or \"XPD_SAT\" .or\n" +" \"fragment\" .or \"program\" .or \"result\" .or \"state\" .or \"texture\";\n" +"vp_reserved_identifier\n" +" \"ABS\" .or \"ADD\" .or \"ADDRESS\" .or \"ALIAS\" .or \"ARL\" .or \"ATTRIB\" .or \"DP3\" .or \"DP4\" .or\n" +" \"DPH\" .or \"DST\" .or \"END\" .or \"EX2\" .or \"EXP\" .or \"FLR\" .or \"FRC\" .or \"LG2\" .or \"LIT\" .or\n" +" \"LOG\" .or \"MAD\" .or \"MAX\" .or \"MIN\" .or \"MOV\" .or \"MUL\" .or \"OPTION\" .or \"OUTPUT\" .or\n" +" \"PARAM\" .or \"POW\" .or \"RCP\" .or \"RSQ\" .or \"SGE\" .or \"SLT\" .or \"SUB\" .or \"SWZ\" .or \"TEMP\" .or\n" +" \"XPD\" .or \"program\" .or \"result\" .or \"state\" .or \"vertex\";\n" +"integer\n" +" integer_ne .error INTEGER_EXPECTED;\n" +"zero\n" +" '0';\n" +"leading_zeroes\n" +" .loop zero;\n" +"no_digit\n" +" no_digit_1 .or .true;\n" +"no_digit_1\n" +" digit10 .and .false .error INTEGER_OUT_OF_RANGE;\n" +"all_zeroes\n" +" all_zeroes_1 .or no_digit_1;\n" +"all_zeroes_1\n" +" '0' .and .loop zero .and no_digit;\n" +"integer_0_3\n" +" integer_0_3_1 .error INTEGER_EXPECTED .and .true .emit 0x00 .emit $;\n" +"integer_0_3_1\n" +" integer_0_3_2 .or all_zeroes .emit '0';\n" +"integer_0_3_2 \n" +" leading_zeroes .and '1'-'3' .emit * .and no_digit;\n" +"integer_0_63\n" +" integer_0_63_1 .error INTEGER_EXPECTED .and .true .emit 0x00 .emit $;\n" +"integer_0_63_1\n" +" integer_0_63_2 .or integer_0_63_3 .or integer_0_63_4 .or integer_0_63_5 .or\n" +" all_zeroes .emit '0';\n" +"integer_0_63_2 \n" +" leading_zeroes .and '7'-'9' .emit * .and no_digit;\n" +"integer_0_63_3 \n" +" leading_zeroes .and '1'-'5' .emit * .and '0'-'9' .emit * .and no_digit;\n" +"integer_0_63_4 \n" +" leading_zeroes .and '6' .emit * .and '0'-'3' .emit * .and no_digit;\n" +"integer_0_63_5 \n" +" leading_zeroes .and '1'-'6' .emit * .and no_digit;\n" +"integer_0_64\n" +" integer_0_64_1 .error INTEGER_EXPECTED .and .true .emit 0x00 .emit $;\n" +"integer_0_64_1\n" +" integer_0_64_2 .or integer_0_64_3 .or integer_0_64_4 .or integer_0_64_5 .or\n" +" all_zeroes .emit '0';\n" +"integer_0_64_2 \n" +" leading_zeroes .and '7'-'9' .emit * .and no_digit;\n" +"integer_0_64_3 \n" +" leading_zeroes .and '1'-'5' .emit * .and '0'-'9' .emit * .and no_digit;\n" +"integer_0_64_4 \n" +" leading_zeroes .and '6' .emit * .and '0'-'4' .emit * .and no_digit;\n" +"integer_0_64_5 \n" +" leading_zeroes .and '1'-'6' .emit * .and no_digit;\n" +"optional_space\n" +" space .or .true;\n" +"space_dst\n" +" space .error OPERATION_NEEDS_DESTINATION_VARIABLE;\n" +"space_src\n" +" space .error OPERATION_NEEDS_SOURCE_VARIABLE;\n" +"space\n" +" single_space .and .loop single_space;\n" +"single_space\n" +" white_char .or comment_block;\n" +"white_char\n" +" ' ' .or '\\t' .or '\\n' .or '\\r';\n" +"comment_block\n" +" '#' .and .loop comment_char .and new_line;\n" +"comment_char\n" +" '\\x0E'-'\\xFF' .or '\\x01'-'\\x09' .or '\\x0B'-'\\x0C';\n" +"new_line\n" +" '\\n' .or crlf .or '\\0';\n" +"crlf\n" +" '\\r' .and '\\n';\n" +"semicolon\n" +" optional_space .and ';' .error MISSING_SEMICOLON .and optional_space;\n" +"comma\n" +" optional_space .and ',' .error MISSING_COMMA .and optional_space;\n" +"comma_ne\n" +" optional_space .and ',' .and optional_space;\n" +"lbracket\n" +" optional_space .and '[' .error MISSING_LBRACKET .and optional_space;\n" +"lbracket_ne\n" +" optional_space .and '[' .and optional_space;\n" +"rbracket\n" +" optional_space .and ']' .error MISSING_RBRACKET .and optional_space;\n" +"dot\n" +" optional_space .and '.' .error MISSING_DOT .and optional_space;\n" +"dot_ne\n" +" optional_space .and '.' .and optional_space;\n" +"equal\n" +" optional_space .and '=' .error MISSING_EQUAL .and optional_space;\n" +"lbrace\n" +" optional_space .and '{' .error MISSING_LBRACE .and optional_space;\n" +"lbrace_ne\n" +" optional_space .and '{' .and optional_space;\n" +"rbrace\n" +" optional_space .and '}' .error MISSING_RBRACE .and optional_space;\n" +"dotdot\n" +" optional_space .and '.' .and '.' .error MISSING_DOTDOT .and optional_space;\n" +"dotdot_ne\n" +" optional_space .and '.' .and '.' .and optional_space;\n" +"float\n" +" float_1 .or float_2 .or float_legacy;\n" +"float_1\n" +" '.' .emit 0x00 .and integer_ne .error MISSING_FRACTION_OR_EXPONENT .and optional_exponent;\n" +"float_2\n" +" integer_ne .and float_3;\n" +"float_3\n" +" float_4 .or float_5;\n" +"float_4\n" +" '.' .and optional_integer .and optional_exponent;\n" +"float_5\n" +" exponent .emit 0x00;\n" +"float_legacy\n" +" integer_ne .and .true .emit 0x00 .emit 0x00;\n" +"integer_ne\n" +" integer_ne_1 .and .true .emit 0x00 .emit $;\n" +"integer_ne_1\n" +" digit10 .emit * .and .loop digit10 .emit *;\n" +"optional_integer\n" +" integer_ne .or .true .emit 0x00;\n" +"optional_exponent\n" +" exponent .or .true .emit 0x00;\n" +"exponent\n" +" exponent_1 .and optional_sign_ne .and integer_ne .error EXPONENT_VALUE_EXPECTED;\n" +"exponent_1\n" +" 'e' .or 'E';\n" +"optional_sign_ne\n" +" minus_ne .or plus_ne .or .true;\n" +"plus_ne\n" +" optional_space .and '+' .and optional_space;\n" +"minus_ne\n" +" optional_space .and '-' .emit '-' .and optional_space;\n" +"identifier_ne\n" +" first_idchar .emit * .and .loop follow_idchar .emit * .and .true .emit 0x00 .emit $;\n" +"follow_idchar\n" +" first_idchar .or digit10;\n" +"first_idchar\n" +" 'a'-'z' .or 'A'-'Z' .or '_' .or '$';\n" +"digit10\n" +" '0'-'9';\n" +".string __string_filter;\n" +"__string_filter\n" +" .loop __identifier_char;\n" +"__identifier_char\n" +" 'a'-'z' .or 'A'-'Z' .or '_' .or '$' .or '0'-'9';\n" +"e_signature\n" +" e_signature_char .and .loop e_signature_char;\n" +"e_signature_char\n" +" '!' .or '.' .or 'A'-'Z' .or 'a'-'z' .or '0'-'9';\n" +"e_statement\n" +" .loop e_statement_not_term;\n" +"e_statement_not_term\n" +" '\\x3C'-'\\xFF' .or '\\x0E'-'\\x3A' .or '\\x01'-'\\x09' .or '\\x0B'-'\\x0C';\n" +"e_identifier\n" +" e_identifier_first .and .loop e_identifier_next;\n" +"e_identifier_first\n" +" 'a'-'z' .or 'A'-'Z' .or '_' .or '$';\n" +"e_identifier_next\n" +" e_identifier_first .or '0'-'9';\n" +"e_token\n" +" e_identifier .or e_token_number .or '[' .or ']' .or '.' .or '{' .or '}' .or '=' .or '+' .or\n" +" '-' .or ',' .or ';';\n" +"e_token_number\n" +" e_token_digit .and .loop e_token_digit;\n" +"e_token_digit\n" +" '0'-'9';\n" +"e_charordigit\n" +" 'A'-'Z' .or 'a'-'z' .or '0'-'9';\n" +"" diff --git a/src/mesa/shader/arbvertparse.c b/src/mesa/shader/arbvertparse.c new file mode 100644 index 0000000..5b50497 --- /dev/null +++ b/src/mesa/shader/arbvertparse.c @@ -0,0 +1,234 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#define DEBUG_VP 0 + +/** + * \file arbvertparse.c + * ARB_vertex_program parser. + * \author Karl Rasche + */ + +#include "glheader.h" +#include "context.h" +#include "arbvertparse.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvprogram.h" +#include "nvvertparse.h" +#include "nvvertprog.h" + +#include "arbprogparse.h" + + +#if DEBUG_VP +static GLvoid +debug_vp_inst(GLint num, struct vp_instruction *vp) +{ + GLint a; + + for (a=0; aInstructions = (struct vp_instruction *) _mesa_malloc ( + sizeof(struct vp_instruction) ); + program->Instructions[0].Opcode = VP_OPCODE_END; + return; + } + + /* copy the relvant contents of the arb_program struct into the + * fragment_program struct + */ + program->Base.String = ap.Base.String; + program->Base.NumInstructions = ap.Base.NumInstructions; + program->Base.NumTemporaries = ap.Base.NumTemporaries; + program->Base.NumParameters = ap.Base.NumParameters; + program->Base.NumAttributes = ap.Base.NumAttributes; + program->Base.NumAddressRegs = ap.Base.NumAddressRegs; + + program->IsPositionInvariant = ap.HintPositionInvariant; + program->InputsRead = ap.InputsRead; + program->OutputsWritten = ap.OutputsWritten; + program->Parameters = ap.Parameters; + + /* Eh.. we parsed something that wasn't a vertex program. doh! */ + /* this wont happen any more */ +/* + if (ap.Base.Target != GL_VERTEX_PROGRAM_ARB) + { + program->Instructions = (struct vp_instruction *) _mesa_malloc ( + sizeof(struct vp_instruction) ); + program->Instructions[0].Opcode = VP_OPCODE_END; + + _mesa_error (ctx, GL_INVALID_OPERATION, "Parsed a non-vertex program as a vertex program"); + return; + } +*/ + + program->Instructions = ap.VPInstructions; + +#if DEBUG_VP + debug_vp_inst(ap.Base.NumInstructions, ap.VPInstructions); +/* +#else + (void) debug_vp_inst; +*/ +#endif + +} diff --git a/src/mesa/shader/arbvertparse.h b/src/mesa/shader/arbvertparse.h new file mode 100644 index 0000000..3e4490b --- /dev/null +++ b/src/mesa/shader/arbvertparse.h @@ -0,0 +1,33 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef ARBVERTPARSE_H +#define ARBVERTPARSE_H + +extern void +_mesa_parse_arb_vertex_program(GLcontext * ctx, GLenum target, + const GLubyte * str, GLsizei len, + struct vertex_program *program); + +#endif diff --git a/src/mesa/shader/descrip.mms b/src/mesa/shader/descrip.mms new file mode 100644 index 0000000..6f737db --- /dev/null +++ b/src/mesa/shader/descrip.mms @@ -0,0 +1,69 @@ +# Makefile for core library for VMS +# contributed by Jouk Jansen joukj@hrem.stm.tudelft.nl +# Last revision : 23 March 2004 + +.first + define gl [---.include.gl] + define math [-.math] + define swrast [-.swrast] + define array_cache [-.array_cache] + +.include [---]mms-config. + +##### MACROS ##### + +VPATH = RCS + +INCDIR = [---.include],[-.main],[-.glapi] +LIBDIR = [---.lib] +CFLAGS = /include=($(INCDIR),[])/define=(PTHREADS=1)/name=(as_is,short) + +SOURCES = \ + arbfragparse.c \ + arbprogparse.c \ + arbprogram.c \ + arbvertparse.c \ + grammar_mesa.c \ + nvfragparse.c \ + nvprogram.c \ + nvvertexec.c \ + nvvertparse.c \ + program.c + +OBJECTS = \ + arbfragparse.obj,\ + arbprogparse.obj,\ + arbprogram.obj,\ + arbvertparse.obj,\ + grammar_mesa.obj,\ + nvfragparse.obj,\ + nvprogram.obj,\ + nvvertexec.obj,\ + nvvertparse.obj,\ + program.obj + + +##### RULES ##### + +VERSION=Mesa V3.4 + +##### TARGETS ##### +# Make the library +$(LIBDIR)$(GL_LIB) : $(OBJECTS) + @ library $(LIBDIR)$(GL_LIB) $(OBJECTS) + +clean : + purge + delete *.obj;* + + +arbfragparse.obj : arbfragparse.c +arbprogparse.obj : arbprogparse.c +arbprogram.obj : arbprogram.c +arbvertparse.obj : arbvertparse.c +grammar_mesa.obj : grammar_mesa.c +nvfragparse.obj : nvfragparse.c +nvprogram.obj : nvprogram.c +nvvertexec.obj : nvvertexec.c +nvvertparse.obj : nvvertparse.c +program.obj : program.c diff --git a/src/mesa/shader/grammar.c b/src/mesa/shader/grammar.c new file mode 100644 index 0000000..6757c7a --- /dev/null +++ b/src/mesa/shader/grammar.c @@ -0,0 +1,2802 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file grammar.c + * syntax parsing engine + * \author Michal Krol + */ + +#ifndef GRAMMAR_PORT_BUILD +#error Do not build this file directly, build your grammar_XXX.c instead, which includes this file +#endif + +/* + Last Modified: 2004-II-8 +*/ + +/* + INTRODUCTION + ------------ + + The task is to check the syntax of an input string. Input string is a stream of ASCII + characters terminated with a null-character ('\0'). Checking it using C language is + difficult and hard to implement without bugs. It is hard to maintain and make changes when + the syntax changes. + + This is because of a high redundancy of the C code. Large blocks of code are duplicated with + only small changes. Even use of macros does not solve the problem because macros cannot + erase the complexity of the problem. + + The resolution is to create a new language that will be highly oriented to our task. Once + we describe a particular syntax, we are done. We can then focus on the code that implements + the language. The size and complexity of it is relatively small than the code that directly + checks the syntax. + + First, we must implement our new language. Here, the language is implemented in C, but it + could also be implemented in any other language. The code is listed below. We must take + a good care that it is bug free. This is simple because the code is simple and clean. + + Next, we must describe the syntax of our new language in itself. Once created and checked + manually that it is correct, we can use it to check another scripts. + + Note that our new language loading code does not have to check the syntax. It is because we + assume that the script describing itself is correct, and other scripts can be syntactically + checked by the former script. The loading code must only do semantic checking which leads us to + simple resolving references. + + THE LANGUAGE + ------------ + + Here I will describe the syntax of the new language (further called "Synek"). It is mainly a + sequence of declarations terminated by a semicolon. The declaration consists of a symbol, + which is an identifier, and its definition. A definition is in turn a sequence of specifiers + connected with ".and" or ".or" operator. These operators cannot be mixed together in a one + definition. Specifier can be a symbol, string, character, character range or a special + keyword ".true" or ".false". + + On the very beginning of the script there is a declaration of a root symbol and is in the form: + .syntax ; + The must be on of the symbols in declaration sequence. The syntax is correct if + the root symbol evaluates to true. A symbol evaluates to true if the definition associated with + the symbol evaluates to true. Definition evaluation depends on the operator used to connect + specifiers in the definition. If ".and" operator is used, definition evaluates to true if and + only if all the specifiers evaluate to true. If ".or" operator is used, definition evalutes to + true if any of the specifiers evaluates to true. If definition contains only one specifier, + it is evaluated as if it was connected with ".true" keyword by ".and" operator. + + If specifier is a ".true" keyword, it always evaluates to true. + + If specifier is a ".false" keyword, it always evaluates to false. Specifier evaluates to false + when it does not evaluate to true. + + Character range specifier is in the form: + '' - '' + If specifier is a character range, it evaluates to true if character in the stream is greater + or equal to and less or equal to . In that situation + the stream pointer is advanced to point to next character in the stream. All C-style escape + sequences are supported although trigraph sequences are not. The comparisions are performed + on 8-bit unsigned integers. + + Character specifier is in the form: + '' + It evaluates to true if the following character range specifier evaluates to true: + '' - '' + + String specifier is in the form: + "" + Let N be the number of characters in . Let [i] designate i-th character in + . Then the string specifier evaluates to true if and only if for i in the range [0, N) + the following character specifier evaluates to true: + '[i]' + If [i] is a quotation mark, '[i]' is replaced with '\[i]'. + + Symbol specifier can be optionally preceded by a ".loop" keyword in the form: + .loop (1) + where is defined as follows: + ; (2) + Construction (1) is replaced by the following code: + + and declaration (2) is replaced by the following: + .or .true; + .and ; + ; + + Synek supports also a register mechanizm. User can, in its SYN file, declare a number of + registers that can be accessed in the syn body. Each reg has its name and a default value. + The register is one byte wide. The C code can change the default value by calling + grammar_set_reg8() with grammar id, register name and a new value. As we know, each rule is + a sequence of specifiers joined with .and or .or operator. And now each specifier can be + prefixed with a condition expression in a form ".if ( )" + where can be == or !=. If the condition evaluates to false, the specifier + evaluates to .false. Otherwise it evalutes to the specifier. + + ESCAPE SEQUENCES + ---------------- + + Synek supports all escape sequences in character specifiers. The mapping table is listed below. + All occurences of the characters in the first column are replaced with the corresponding + character in the second column. + + Escape sequence Represents + ------------------------------------------------------------------------------------------------ + \a Bell (alert) + \b Backspace + \f Formfeed + \n New line + \r Carriage return + \t Horizontal tab + \v Vertical tab + \' Single quotation mark + \" Double quotation mark + \\ Backslash + \? Literal question mark + \ooo ASCII character in octal notation + \xhhh ASCII character in hexadecimal notation + ------------------------------------------------------------------------------------------------ + + RAISING ERRORS + -------------- + + Any specifier can be followed by a special construction that is executed when the specifier + evaluates to false. The construction is in the form: + .error + is an identifier declared earlier by error text declaration. The declaration is + in the form: + .errtext "" + When specifier evaluates to false and this construction is present, parsing is stopped + immediately and is returned as a result of parsing. The error position is also + returned and it is meant as an offset from the beggining of the stream to the character that + was valid so far. Example: + + (**** syntax script ****) + + .syntax program; + .errtext MISSING_SEMICOLON "missing ';'" + program declaration .and .loop space .and ';' .error MISSING_SEMICOLON .and + .loop space .and '\0'; + declaration "declare" .and .loop space .and identifier; + space ' '; + + (**** sample code ****) + + declare foo , + + In the example above checking the sample code will result in error message "missing ';'" and + error position 12. The sample code is not correct. Note the presence of '\0' specifier to + assure that there is no code after semicolon - only spaces. + can optionally contain identifier surrounded by dollar signs $. In such a case, + the identifier and dollar signs are replaced by a string retrieved by invoking symbol with + the identifier name. The starting position is the error position. The lenght of the resulting + string is the position after invoking the symbol. + + PRODUCTION + ---------- + + Synek not only checks the syntax but it can also produce (emit) bytes associated with specifiers + that evaluate to true. That is, every specifier and optional error construction can be followed + by a number of emit constructions that are in the form: + .emit + can be a HEX number, identifier, a star * or a dollar $. HEX number is preceded by + 0x or 0X. If is an identifier, it must be earlier declared by emit code declaration + in the form: + .emtcode + + When given specifier evaluates to true, all emits associated with the specifier are output + in order they were declared. A star means that last-read character should be output instead + of constant value. Example: + + (**** syntax script ****) + + .syntax foobar; + .emtcode WORD_FOO 0x01 + .emtcode WORD_BAR 0x02 + foobar FOO .emit WORD_FOO .or BAR .emit WORD_BAR .or .true .emit 0x00; + FOO "foo" .and SPACE; + BAR "bar" .and SPACE; + SPACE ' ' .or '\0'; + + (**** sample text 1 ****) + + foo + + (**** sample text 2 ****) + + foobar + + For both samples the result will be one-element array. For first sample text it will be + value 1, for second - 0. Note that every text will be accepted because of presence of + .true as an alternative. + + Another example: + + (**** syntax script ****) + + .syntax declaration; + .emtcode VARIABLE 0x01 + declaration "declare" .and .loop space .and + identifier .emit VARIABLE .and (1) + .true .emit 0x00 .and (2) + .loop space .and ';'; + space ' ' .or '\t'; + identifier .loop id_char .emit *; (3) + id_char 'a'-'z' .or 'A'-'Z' .or '_'; + + (**** sample code ****) + + declare fubar; + + In specifier (1) symbol is followed by .emit VARIABLE. If it evaluates to + true, VARIABLE constant and then production of the symbol is output. Specifier (2) is used + to terminate the string with null to signal when the string ends. Specifier (3) outputs + all characters that make declared identifier. The result of sample code will be the + following array: + { 1, 'f', 'u', 'b', 'a', 'r', 0 } + + If .emit is followed by dollar $, it means that current position should be output. Current + position is a 32-bit unsigned integer distance from the very beginning of the parsed string to + first character consumed by the specifier associated with the .emit instruction. Current + position is stored in the output buffer in Little-Endian convention (the lowest byte comes + first). +*/ + +static void mem_free (void **); + +/* + internal error messages +*/ +static const byte *OUT_OF_MEMORY = (byte *) "internal error 1001: out of physical memory"; +static const byte *UNRESOLVED_REFERENCE = (byte *) "internal error 1002: unresolved reference '$'"; +static const byte *INVALID_GRAMMAR_ID = (byte *) "internal error 1003: invalid grammar object"; +static const byte *INVALID_REGISTER_NAME = (byte *) "internal error 1004: invalid register name: '$'"; + +static const byte *error_message = NULL; +static byte *error_param = NULL; /* this is inserted into error_message in place of $ */ +static int error_position = -1; + +static byte *unknown = (byte *) "???"; + +static void clear_last_error (void) +{ + /* reset error message */ + error_message = NULL; + + /* free error parameter - if error_param is a "???" don't free it - it's static */ + if (error_param != unknown) + mem_free ((void **) (void *) &error_param); + else + error_param = NULL; + + /* reset error position */ + error_position = -1; +} + +static void set_last_error (const byte *msg, byte *param, int pos) +{ + /* error message can only be set only once */ + if (error_message != NULL) + { + mem_free ((void **) (void *) ¶m); + return; + } + + error_message = msg; + + if (param != NULL) + error_param = param; + else + error_param = unknown; + + error_position = pos; +} + +/* + memory management routines +*/ +static void *mem_alloc (size_t size) +{ + void *ptr = grammar_alloc_malloc (size); + if (ptr == NULL) + set_last_error (OUT_OF_MEMORY, NULL, -1); + return ptr; +} + +static void *mem_copy (void *dst, const void *src, size_t size) +{ + return grammar_memory_copy (dst, src, size); +} + +static void mem_free (void **ptr) +{ + grammar_alloc_free (*ptr); + *ptr = NULL; +} + +static void *mem_realloc (void *ptr, size_t old_size, size_t new_size) +{ + void *ptr2 = grammar_alloc_realloc (ptr, old_size, new_size); + if (ptr2 == NULL) + set_last_error (OUT_OF_MEMORY, NULL, -1); + return ptr2; +} + +static byte *str_copy_n (byte *dst, const byte *src, size_t max_len) +{ + return grammar_string_copy_n (dst, src, max_len); +} + +static byte *str_duplicate (const byte *str) +{ + byte *new_str = grammar_string_duplicate (str); + if (new_str == NULL) + set_last_error (OUT_OF_MEMORY, NULL, -1); + return new_str; +} + +static int str_equal (const byte *str1, const byte *str2) +{ + return grammar_string_compare (str1, str2) == 0; +} + +static int str_equal_n (const byte *str1, const byte *str2, unsigned int n) +{ + return grammar_string_compare_n (str1, str2, n) == 0; +} + +static unsigned int str_length (const byte *str) +{ + return grammar_string_length (str); +} + +/* + string to byte map typedef +*/ +typedef struct map_byte_ +{ + byte *key; + byte data; + struct map_byte_ *next; +} map_byte; + +static void map_byte_create (map_byte **ma) +{ + *ma = (map_byte *) mem_alloc (sizeof (map_byte)); + if (*ma) + { + (**ma).key = NULL; + (**ma).data = '\0'; + (**ma).next = NULL; + } +} + +/* XXX unfold the recursion */ +static void map_byte_destroy (map_byte **ma) +{ + if (*ma) + { + map_byte_destroy (&(**ma).next); + mem_free ((void **) &(**ma).key); + mem_free ((void **) ma); + } +} + +static void map_byte_append (map_byte **ma, map_byte **nm) +{ + while (*ma) + ma = &(**ma).next; + *ma = *nm; +} + +/* + searches the map for the specified key, + returns pointer to the element with the specified key if it exists + returns NULL otherwise +*/ +static map_byte *map_byte_locate (map_byte **ma, const byte *key) +{ + while (*ma) + { + if (str_equal ((**ma).key, key)) + return *ma; + + ma = &(**ma).next; + } + + set_last_error (UNRESOLVED_REFERENCE, str_duplicate (key), -1); + return NULL; +} + +/* + searches the map for specified key, + if the key is matched, *data is filled with data associated with the key, + returns 0 if the key is matched, + returns 1 otherwise +*/ +static int map_byte_find (map_byte **ma, const byte *key, byte *data) +{ + map_byte *found = map_byte_locate (ma, key); + if (found != NULL) + { + *data = found->data; + + return 0; + } + + return 1; +} + +/* + regbyte context typedef + + Each regbyte consists of its name and a default value. These are static and created at + grammar script compile-time, for example the following line: + .regbyte vertex_blend 0x00 + adds a new regbyte named "vertex_blend" to the static list and initializes it to 0. + When the script is executed, this regbyte can be accessed by name for read and write. When a + particular regbyte is written, a new regbyte_ctx entry is added to the top of the regbyte_ctx + stack. The new entry contains information abot which regbyte it references and its new value. + When a given regbyte is accessed for read, the stack is searched top-down to find an + entry that references the regbyte. The first matching entry is used to return the current + value it holds. If no entry is found, the default value is returned. +*/ +typedef struct regbyte_ctx_ +{ + map_byte *m_regbyte; + byte m_current_value; + struct regbyte_ctx_ *m_prev; +} regbyte_ctx; + +static void regbyte_ctx_create (regbyte_ctx **re) +{ + *re = (regbyte_ctx *) mem_alloc (sizeof (regbyte_ctx)); + if (*re) + { + (**re).m_regbyte = NULL; + (**re).m_prev = NULL; + } +} + +static void regbyte_ctx_destroy (regbyte_ctx **re) +{ + if (*re) + { + mem_free ((void **) re); + } +} + +static byte regbyte_ctx_extract (regbyte_ctx **re, map_byte *reg) +{ + /* first lookup in the register stack */ + while (*re != NULL) + { + if ((**re).m_regbyte == reg) + return (**re).m_current_value; + + re = &(**re).m_prev; + } + + /* if not found - return the default value */ + return reg->data; +} + +/* + emit type typedef +*/ +typedef enum emit_type_ +{ + et_byte, /* explicit number */ + et_stream, /* eaten character */ + et_position /* current position */ +} emit_type; + +/* + emit destination typedef +*/ +typedef enum emit_dest_ +{ + ed_output, /* write to the output buffer */ + ed_regbyte /* write a particular regbyte */ +} emit_dest; + +/* + emit typedef +*/ +typedef struct emit_ +{ + emit_dest m_emit_dest; + emit_type m_emit_type; /* ed_output */ + byte m_byte; /* et_byte */ + map_byte *m_regbyte; /* ed_regbyte */ + byte *m_regname; /* ed_regbyte - temporary */ + struct emit_ *m_next; +} emit; + +static void emit_create (emit **em) +{ + *em = (emit *) mem_alloc (sizeof (emit)); + if (*em) + { + (**em).m_emit_dest = ed_output; + (**em).m_emit_type = et_byte; + (**em).m_byte = '\0'; + (**em).m_regbyte = NULL; + (**em).m_regname = NULL; + (**em).m_next = NULL; + } +} + +static void emit_destroy (emit **em) +{ + if (*em) + { + emit_destroy (&(**em).m_next); + mem_free ((void **) &(**em).m_regname); + mem_free ((void **) em); + } +} + +/* + error typedef +*/ +typedef struct error_ +{ + byte *m_text; + byte *m_token_name; + struct rule_ *m_token; +} error; + +static void error_create (error **er) +{ + *er = (error *) mem_alloc (sizeof (error)); + if (*er) + { + (**er).m_text = NULL; + (**er).m_token_name = NULL; + (**er).m_token = NULL; + } +} + +static void error_destroy (error **er) +{ + if (*er) + { + mem_free ((void **) &(**er).m_text); + mem_free ((void **) &(**er).m_token_name); + mem_free ((void **) er); + } +} + +struct dict_; +static byte *error_get_token (error *, struct dict_ *, const byte *, unsigned int); + +/* + condition operand type typedef +*/ +typedef enum cond_oper_type_ +{ + cot_byte, /* constant 8-bit unsigned integer */ + cot_regbyte /* pointer to byte register containing the current value */ +} cond_oper_type; + +/* + condition operand typedef +*/ +typedef struct cond_oper_ +{ + cond_oper_type m_type; + byte m_byte; /* cot_byte */ + map_byte *m_regbyte; /* cot_regbyte */ + byte *m_regname; /* cot_regbyte - temporary */ +} cond_oper; + +/* + condition type typedef +*/ +typedef enum cond_type_ +{ + ct_equal, + ct_not_equal +} cond_type; + +/* + condition typedef +*/ +typedef struct cond_ +{ + cond_type m_type; + cond_oper m_operands[2]; +} cond; + +static void cond_create (cond **co) +{ + *co = (cond *) mem_alloc (sizeof (cond)); + if (*co) + { + (**co).m_operands[0].m_regname = NULL; + (**co).m_operands[1].m_regname = NULL; + } +} + +static void cond_destroy (cond **co) +{ + if (*co) + { + mem_free ((void **) &(**co).m_operands[0].m_regname); + mem_free ((void **) &(**co).m_operands[1].m_regname); + mem_free ((void **) co); + } +} + +/* + specifier type typedef +*/ +typedef enum spec_type_ +{ + st_false, + st_true, + st_byte, + st_byte_range, + st_string, + st_identifier, + st_identifier_loop, + st_debug +} spec_type; + +/* + specifier typedef +*/ +typedef struct spec_ +{ + spec_type m_spec_type; + byte m_byte[2]; /* st_byte, st_byte_range */ + byte *m_string; /* st_string */ + struct rule_ *m_rule; /* st_identifier, st_identifier_loop */ + emit *m_emits; + error *m_errtext; + cond *m_cond; + struct spec_ *m_next; +} spec; + +static void spec_create (spec **sp) +{ + *sp = (spec *) mem_alloc (sizeof (spec)); + if (*sp) + { + (**sp).m_spec_type = st_false; + (**sp).m_byte[0] = '\0'; + (**sp).m_byte[1] = '\0'; + (**sp).m_string = NULL; + (**sp).m_rule = NULL; + (**sp).m_emits = NULL; + (**sp).m_errtext = NULL; + (**sp).m_cond = NULL; + (**sp).m_next = NULL; + } +} + +static void spec_destroy (spec **sp) +{ + if (*sp) + { + spec_destroy (&(**sp).m_next); + emit_destroy (&(**sp).m_emits); + error_destroy (&(**sp).m_errtext); + mem_free ((void **) &(**sp).m_string); + cond_destroy (&(**sp).m_cond); + mem_free ((void **) sp); + } +} + +static void spec_append (spec **sp, spec **ns) +{ + while (*sp) + sp = &(**sp).m_next; + *sp = *ns; +} + +/* + operator typedef +*/ +typedef enum oper_ +{ + op_none, + op_and, + op_or +} oper; + +/* + rule typedef +*/ +typedef struct rule_ +{ + oper m_oper; + spec *m_specs; + struct rule_ *m_next; +/* int m_referenced; */ /* for debugging purposes */ +} rule; + +static void rule_create (rule **ru) +{ + *ru = (rule *) mem_alloc (sizeof (rule)); + if (*ru) + { + (**ru).m_oper = op_none; + (**ru).m_specs = NULL; + (**ru).m_next = NULL; +/* (**ru).m_referenced = 0; */ + } +} + +static void rule_destroy (rule **ru) +{ + if (*ru) + { + rule_destroy (&(**ru).m_next); + spec_destroy (&(**ru).m_specs); + mem_free ((void **) ru); + } +} + +static void rule_append (rule **ru, rule **nr) +{ + while (*ru) + ru = &(**ru).m_next; + *ru = *nr; +} + +/* + returns unique grammar id +*/ +static grammar next_valid_grammar_id (void) +{ + static grammar id = 0; + + return ++id; +} + +/* + dictionary typedef +*/ +typedef struct dict_ +{ + rule *m_rulez; + rule *m_syntax; + rule *m_string; + map_byte *m_regbytes; + grammar m_id; + struct dict_ *m_next; +} dict; + +static void dict_create (dict **di) +{ + *di = (dict *) mem_alloc (sizeof (dict)); + if (*di) + { + (**di).m_rulez = NULL; + (**di).m_syntax = NULL; + (**di).m_string = NULL; + (**di).m_regbytes = NULL; + (**di).m_id = next_valid_grammar_id (); + (**di).m_next = NULL; + } +} + +static void dict_destroy (dict **di) +{ + if (*di) + { + rule_destroy (&(**di).m_rulez); + map_byte_destroy (&(**di).m_regbytes); + mem_free ((void **) di); + } +} + +static void dict_append (dict **di, dict **nd) +{ + while (*di) + di = &(**di).m_next; + *di = *nd; +} + +static void dict_find (dict **di, grammar key, dict **data) +{ + while (*di) + { + if ((**di).m_id == key) + { + *data = *di; + return; + } + + di = &(**di).m_next; + } + + *data = NULL; +} + +static dict *g_dicts = NULL; + +/* + byte array typedef + + XXX this class is going to be replaced by a faster one, soon +*/ +typedef struct barray_ +{ + byte *data; + unsigned int len; +} barray; + +static void barray_create (barray **ba) +{ + *ba = (barray *) mem_alloc (sizeof (barray)); + if (*ba) + { + (**ba).data = NULL; + (**ba).len = 0; + } +} + +static void barray_destroy (barray **ba) +{ + if (*ba) + { + mem_free ((void **) &(**ba).data); + mem_free ((void **) ba); + } +} + +/* + reallocates byte array to requested size, + returns 0 on success, + returns 1 otherwise +*/ +static int barray_resize (barray **ba, unsigned int nlen) +{ + byte *new_pointer; + + if (nlen == 0) + { + mem_free ((void **) &(**ba).data); + (**ba).data = NULL; + (**ba).len = 0; + + return 0; + } + else + { + new_pointer = (byte *) mem_realloc ((**ba).data, (**ba).len * sizeof (byte), nlen * sizeof (byte)); + if (new_pointer) + { + (**ba).data = new_pointer; + (**ba).len = nlen; + + return 0; + } + } + + return 1; +} + +/* + adds byte array pointed by *nb to the end of array pointed by *ba, + returns 0 on success, + returns 1 otherwise +*/ +static int barray_append (barray **ba, barray **nb) +{ + const unsigned int len = (**ba).len; + + if (barray_resize (ba, (**ba).len + (**nb).len)) + return 1; + + mem_copy ((**ba).data + len, (**nb).data, (**nb).len); + + return 0; +} + +/* + adds emit chain pointed by em to the end of array pointed by *ba, + returns 0 on success, + returns 1 otherwise +*/ +static int barray_push (barray **ba, emit *em, byte c, unsigned int pos, regbyte_ctx **rbc) +{ + emit *temp = em; + unsigned int count = 0; + + while (temp) + { + if (temp->m_emit_dest == ed_output) { + if (temp->m_emit_type == et_position) + count += 4; /* position is a 32-bit unsigned integer */ + else + count++; + } + temp = temp->m_next; + } + + if (barray_resize (ba, (**ba).len + count)) + return 1; + + while (em) + { + if (em->m_emit_dest == ed_output) + { + if (em->m_emit_type == et_byte) + (**ba).data[(**ba).len - count--] = em->m_byte; + else if (em->m_emit_type == et_stream) + (**ba).data[(**ba).len - count--] = c; + else /* em->type == et_position */ + (**ba).data[(**ba).len - count--] = (byte) pos, + (**ba).data[(**ba).len - count--] = (byte) (pos >> 8), + (**ba).data[(**ba).len - count--] = (byte) (pos >> 16), + (**ba).data[(**ba).len - count--] = (byte) (pos >> 24); + } + else + { + regbyte_ctx *new_rbc; + regbyte_ctx_create (&new_rbc); + if (new_rbc == NULL) + return 1; + + new_rbc->m_prev = *rbc; + new_rbc->m_regbyte = em->m_regbyte; + *rbc = new_rbc; + + if (em->m_emit_type == et_byte) + new_rbc->m_current_value = em->m_byte; + else if (em->m_emit_type == et_stream) + new_rbc->m_current_value = c; + } + + em = em->m_next; + } + + return 0; +} + +/* + string to string map typedef +*/ +typedef struct map_str_ +{ + byte *key; + byte *data; + struct map_str_ *next; +} map_str; + +static void map_str_create (map_str **ma) +{ + *ma = (map_str *) mem_alloc (sizeof (map_str)); + if (*ma) + { + (**ma).key = NULL; + (**ma).data = NULL; + (**ma).next = NULL; + } +} + +static void map_str_destroy (map_str **ma) +{ + if (*ma) + { + map_str_destroy (&(**ma).next); + mem_free ((void **) &(**ma).key); + mem_free ((void **) &(**ma).data); + mem_free ((void **) ma); + } +} + +static void map_str_append (map_str **ma, map_str **nm) +{ + while (*ma) + ma = &(**ma).next; + *ma = *nm; +} + +/* + searches the map for specified key, + if the key is matched, *data is filled with data associated with the key, + returns 0 if the key is matched, + returns 1 otherwise +*/ +static int map_str_find (map_str **ma, const byte *key, byte **data) +{ + while (*ma) + { + if (str_equal ((**ma).key, key)) + { + *data = str_duplicate ((**ma).data); + if (*data == NULL) + return 1; + + return 0; + } + + ma = &(**ma).next; + } + + set_last_error (UNRESOLVED_REFERENCE, str_duplicate (key), -1); + return 1; +} + +/* + string to rule map typedef +*/ +typedef struct map_rule_ +{ + byte *key; + rule *data; + struct map_rule_ *next; +} map_rule; + +static void map_rule_create (map_rule **ma) +{ + *ma = (map_rule *) mem_alloc (sizeof (map_rule)); + if (*ma) + { + (**ma).key = NULL; + (**ma).data = NULL; + (**ma).next = NULL; + } +} + +static void map_rule_destroy (map_rule **ma) +{ + if (*ma) + { + map_rule_destroy (&(**ma).next); + mem_free ((void **) &(**ma).key); + mem_free ((void **) ma); + } +} + +static void map_rule_append (map_rule **ma, map_rule **nm) +{ + while (*ma) + ma = &(**ma).next; + *ma = *nm; +} + +/* + searches the map for specified key, + if the key is matched, *data is filled with data associated with the key, + returns 0 if the is matched, + returns 1 otherwise +*/ +static int map_rule_find (map_rule **ma, const byte *key, rule **data) +{ + while (*ma) + { + if (str_equal ((**ma).key, key)) + { + *data = (**ma).data; + + return 0; + } + + ma = &(**ma).next; + } + + set_last_error (UNRESOLVED_REFERENCE, str_duplicate (key), -1); + return 1; +} + +/* + returns 1 if given character is a white space, + returns 0 otherwise +*/ +static int is_space (byte c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; +} + +/* + advances text pointer by 1 if character pointed by *text is a space, + returns 1 if a space has been eaten, + returns 0 otherwise +*/ +static int eat_space (const byte **text) +{ + if (is_space (**text)) + { + (*text)++; + + return 1; + } + + return 0; +} + +/* + returns 1 if text points to C-style comment start string, + returns 0 otherwise +*/ +static int is_comment_start (const byte *text) +{ + return text[0] == '/' && text[1] == '*'; +} + +/* + advances text pointer to first character after C-style comment block - if any, + returns 1 if C-style comment block has been encountered and eaten, + returns 0 otherwise +*/ +static int eat_comment (const byte **text) +{ + if (is_comment_start (*text)) + { + /* *text points to comment block - skip two characters to enter comment body */ + *text += 2; + /* skip any character except consecutive '*' and '/' */ + while (!((*text)[0] == '*' && (*text)[1] == '/')) + (*text)++; + /* skip those two terminating characters */ + *text += 2; + + return 1; + } + + return 0; +} + +/* + advances text pointer to first character that is neither space nor C-style comment block +*/ +static void eat_spaces (const byte **text) +{ + while (eat_space (text) || eat_comment (text)) + ; +} + +/* + resizes string pointed by *ptr to successfully add character c to the end of the string, + returns 0 on success, + returns 1 otherwise +*/ +static int string_grow (byte **ptr, unsigned int *len, byte c) +{ + /* reallocate the string in 16-byte increments */ + if ((*len & 0x0F) == 0x0F || *ptr == NULL) + { + byte *tmp = (byte *) mem_realloc (*ptr, ((*len + 1) & ~0x0F) * sizeof (byte), + ((*len + 1 + 0x10) & ~0x0F) * sizeof (byte)); + if (tmp == NULL) + return 1; + + *ptr = tmp; + } + + if (c) + { + /* append given character */ + (*ptr)[*len] = c; + (*len)++; + } + (*ptr)[*len] = '\0'; + + return 0; +} + +/* + returns 1 if given character is a valid identifier character a-z, A-Z, 0-9 or _ + returns 0 otherwise +*/ +static int is_identifier (byte c) +{ + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; +} + +/* + copies characters from *text to *id until non-identifier character is encountered, + assumes that *id points to NULL object - caller is responsible for later freeing the string, + text pointer is advanced to point past the copied identifier, + returns 0 if identifier was successfully copied, + returns 1 otherwise +*/ +static int get_identifier (const byte **text, byte **id) +{ + const byte *t = *text; + byte *p = NULL; + unsigned int len = 0; + + if (string_grow (&p, &len, '\0')) + return 1; + + /* loop while next character in buffer is valid for identifiers */ + while (is_identifier (*t)) + { + if (string_grow (&p, &len, *t++)) + { + mem_free ((void **) (void *) &p); + return 1; + } + } + + *text = t; + *id = p; + + return 0; +} + +/* + returns 1 if given character is HEX digit 0-9, A-F or a-f, + returns 0 otherwise +*/ +static int is_hex (byte c) +{ + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); +} + +/* + returns value of passed character as if it was HEX digit +*/ +static unsigned int hex2dec (byte c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'F') + return c - 'A' + 10; + return c - 'a' + 10; +} + +/* + converts sequence of HEX digits pointed by *text until non-HEX digit is encountered, + advances text pointer past the converted sequence, + returns the converted value +*/ +static unsigned int hex_convert (const byte **text) +{ + unsigned int value = 0; + + while (is_hex (**text)) + { + value = value * 0x10 + hex2dec (**text); + (*text)++; + } + + return value; +} + +/* + returns 1 if given character is OCT digit 0-7, + returns 0 otherwise +*/ +static int is_oct (byte c) +{ + return c >= '0' && c <= '7'; +} + +/* + returns value of passed character as if it was OCT digit +*/ +static int oct2dec (byte c) +{ + return c - '0'; +} + +static byte get_escape_sequence (const byte **text) +{ + int value = 0; + + /* skip '\' character */ + (*text)++; + + switch (*(*text)++) + { + case '\'': + return '\''; + case '"': + return '\"'; + case '?': + return '\?'; + case '\\': + return '\\'; + case 'a': + return '\a'; + case 'b': + return '\b'; + case 'f': + return '\f'; + case 'n': + return '\n'; + case 'r': + return '\r'; + case 't': + return '\t'; + case 'v': + return '\v'; + case 'x': + return (byte) hex_convert (text); + } + + (*text)--; + if (is_oct (**text)) + { + value = oct2dec (*(*text)++); + if (is_oct (**text)) + { + value = value * 010 + oct2dec (*(*text)++); + if (is_oct (**text)) + value = value * 010 + oct2dec (*(*text)++); + } + } + + return (byte) value; +} + +/* + copies characters from *text to *str until " or ' character is encountered, + assumes that *str points to NULL object - caller is responsible for later freeing the string, + assumes that *text points to " or ' character that starts the string, + text pointer is advanced to point past the " or ' character, + returns 0 if string was successfully copied, + returns 1 otherwise +*/ +static int get_string (const byte **text, byte **str) +{ + const byte *t = *text; + byte *p = NULL; + unsigned int len = 0; + byte term_char; + + if (string_grow (&p, &len, '\0')) + return 1; + + /* read " or ' character that starts the string */ + term_char = *t++; + /* while next character is not the terminating character */ + while (*t && *t != term_char) + { + byte c; + + if (*t == '\\') + c = get_escape_sequence (&t); + else + c = *t++; + + if (string_grow (&p, &len, c)) + { + mem_free ((void **) (void *) &p); + return 1; + } + } + /* skip " or ' character that ends the string */ + t++; + + *text = t; + *str = p; + return 0; +} + +/* + gets emit code, the syntax is: ".emtcode" " " " " ("0x" | "0X") + assumes that *text already points to , + returns 0 if emit code is successfully read, + returns 1 otherwise +*/ +static int get_emtcode (const byte **text, map_byte **ma) +{ + const byte *t = *text; + map_byte *m = NULL; + + map_byte_create (&m); + if (m == NULL) + return 1; + + if (get_identifier (&t, &m->key)) + { + map_byte_destroy (&m); + return 1; + } + eat_spaces (&t); + + if (*t == '\'') + { + byte *c; + + if (get_string (&t, &c)) + { + map_byte_destroy (&m); + return 1; + } + + m->data = (byte) c[0]; + mem_free ((void **) (void *) &c); + } + else + { + /* skip HEX "0x" or "0X" prefix */ + t += 2; + m->data = (byte) hex_convert (&t); + } + + eat_spaces (&t); + + *text = t; + *ma = m; + return 0; +} + +/* + gets regbyte declaration, the syntax is: ".regbyte" " " " " ("0x" | "0X") + assumes that *text already points to , + returns 0 if regbyte is successfully read, + returns 1 otherwise +*/ +static int get_regbyte (const byte **text, map_byte **ma) +{ + return get_emtcode (text, ma); +} + +/* + returns 0 on success, + returns 1 otherwise +*/ +static int get_errtext (const byte **text, map_str **ma) +{ + const byte *t = *text; + map_str *m = NULL; + + map_str_create (&m); + if (m == NULL) + return 1; + + if (get_identifier (&t, &m->key)) + { + map_str_destroy (&m); + return 1; + } + eat_spaces (&t); + + if (get_string (&t, &m->data)) + { + map_str_destroy (&m); + return 1; + } + eat_spaces (&t); + + *text = t; + *ma = m; + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int get_error (const byte **text, error **er, map_str *maps) +{ + const byte *t = *text; + byte *temp = NULL; + + if (*t != '.') + return 0; + + t++; + if (get_identifier (&t, &temp)) + return 1; + eat_spaces (&t); + + if (!str_equal ((byte *) "error", temp)) + { + mem_free ((void **) (void *) &temp); + return 0; + } + + mem_free ((void **) (void *) &temp); + + error_create (er); + if (*er == NULL) + return 1; + + if (*t == '\"') + { + if (get_string (&t, &(**er).m_text)) + { + error_destroy (er); + return 1; + } + eat_spaces (&t); + } + else + { + if (get_identifier (&t, &temp)) + { + error_destroy (er); + return 1; + } + eat_spaces (&t); + + if (map_str_find (&maps, temp, &(**er).m_text)) + { + mem_free ((void **) (void *) &temp); + error_destroy (er); + return 1; + } + + mem_free ((void **) (void *) &temp); + } + + /* try to extract "token" from "...$token$..." */ + { + byte *processed = NULL; + unsigned int len = 0, i = 0; + + if (string_grow (&processed, &len, '\0')) + { + error_destroy (er); + return 1; + } + + while (i < str_length ((**er).m_text)) + { + /* check if the dollar sign is repeated - if so skip it */ + if ((**er).m_text[i] == '$' && (**er).m_text[i + 1] == '$') + { + if (string_grow (&processed, &len, '$')) + { + mem_free ((void **) (void *) &processed); + error_destroy (er); + return 1; + } + + i += 2; + } + else if ((**er).m_text[i] != '$') + { + if (string_grow (&processed, &len, (**er).m_text[i])) + { + mem_free ((void **) (void *) &processed); + error_destroy (er); + return 1; + } + + i++; + } + else + { + if (string_grow (&processed, &len, '$')) + { + mem_free ((void **) (void *) &processed); + error_destroy (er); + return 1; + } + + { + /* length of token being extracted */ + unsigned int tlen = 0; + + if (string_grow (&(**er).m_token_name, &tlen, '\0')) + { + mem_free ((void **) (void *) &processed); + error_destroy (er); + return 1; + } + + /* skip the dollar sign */ + i++; + + while ((**er).m_text[i] != '$') + { + if (string_grow (&(**er).m_token_name, &tlen, (**er).m_text[i])) + { + mem_free ((void **) (void *) &processed); + error_destroy (er); + return 1; + } + + i++; + } + + /* skip the dollar sign */ + i++; + } + } + } + + mem_free ((void **) &(**er).m_text); + (**er).m_text = processed; + } + + *text = t; + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int get_emits (const byte **text, emit **em, map_byte *mapb) +{ + const byte *t = *text; + byte *temp = NULL; + emit *e = NULL; + emit_dest dest; + + if (*t != '.') + return 0; + + t++; + if (get_identifier (&t, &temp)) + return 1; + eat_spaces (&t); + + /* .emit */ + if (str_equal ((byte *) "emit", temp)) + dest = ed_output; + /* .load */ + else if (str_equal ((byte *) "load", temp)) + dest = ed_regbyte; + else + { + mem_free ((void **) (void *) &temp); + return 0; + } + + mem_free ((void **) (void *) &temp); + + emit_create (&e); + if (e == NULL) + return 1; + + e->m_emit_dest = dest; + + if (dest == ed_regbyte) + { + if (get_identifier (&t, &e->m_regname)) + { + emit_destroy (&e); + return 1; + } + eat_spaces (&t); + } + + /* 0xNN */ + if (*t == '0') + { + t += 2; + e->m_byte = (byte) hex_convert (&t); + + e->m_emit_type = et_byte; + } + /* * */ + else if (*t == '*') + { + t++; + + e->m_emit_type = et_stream; + } + /* $ */ + else if (*t == '$') + { + t++; + + e->m_emit_type = et_position; + } + /* 'c' */ + else if (*t == '\'') + { + if (get_string (&t, &temp)) + { + emit_destroy (&e); + return 1; + } + e->m_byte = (byte) temp[0]; + + mem_free ((void **) (void *) &temp); + + e->m_emit_type = et_byte; + } + else + { + if (get_identifier (&t, &temp)) + { + emit_destroy (&e); + return 1; + } + + if (map_byte_find (&mapb, temp, &e->m_byte)) + { + mem_free ((void **) (void *) &temp); + emit_destroy (&e); + return 1; + } + + mem_free ((void **) (void *) &temp); + + e->m_emit_type = et_byte; + } + + eat_spaces (&t); + + if (get_emits (&t, &e->m_next, mapb)) + { + emit_destroy (&e); + return 1; + } + + *text = t; + *em = e; + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int get_spec (const byte **text, spec **sp, map_str *maps, map_byte *mapb) +{ + const byte *t = *text; + spec *s = NULL; + + spec_create (&s); + if (s == NULL) + return 1; + + /* first - read optional .if statement */ + if (*t == '.') + { + const byte *u = t; + byte *keyword = NULL; + + /* skip the dot */ + u++; + + if (get_identifier (&u, &keyword)) + { + spec_destroy (&s); + return 1; + } + + /* .if */ + if (str_equal ((byte *) "if", keyword)) + { + cond_create (&s->m_cond); + if (s->m_cond == NULL) + { + spec_destroy (&s); + return 1; + } + + /* skip the left paren */ + eat_spaces (&u); + u++; + + /* get the left operand */ + eat_spaces (&u); + if (get_identifier (&u, &s->m_cond->m_operands[0].m_regname)) + { + spec_destroy (&s); + return 1; + } + s->m_cond->m_operands[0].m_type = cot_regbyte; + + /* get the operator (!= or ==) */ + eat_spaces (&u); + if (*u == '!') + s->m_cond->m_type = ct_not_equal; + else + s->m_cond->m_type = ct_equal; + u += 2; + + /* skip the 0x prefix */ + eat_spaces (&u); + u += 2; + + /* get the right operand */ + s->m_cond->m_operands[1].m_byte = hex_convert (&u); + s->m_cond->m_operands[1].m_type = cot_byte; + + /* skip the right paren */ + eat_spaces (&u); + u++; + + eat_spaces (&u); + + t = u; + } + + mem_free ((void **) (void *) &keyword); + } + + if (*t == '\'') + { + byte *temp = NULL; + + if (get_string (&t, &temp)) + { + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + if (*t == '-') + { + byte *temp2 = NULL; + + /* skip the '-' character */ + t++; + eat_spaces (&t); + + if (get_string (&t, &temp2)) + { + mem_free ((void **) (void *) &temp); + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + s->m_spec_type = st_byte_range; + s->m_byte[0] = *temp; + s->m_byte[1] = *temp2; + + mem_free ((void **) (void *) &temp2); + } + else + { + s->m_spec_type = st_byte; + *s->m_byte = *temp; + } + + mem_free ((void **) (void *) &temp); + } + else if (*t == '"') + { + if (get_string (&t, &s->m_string)) + { + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + s->m_spec_type = st_string; + } + else if (*t == '.') + { + byte *keyword = NULL; + + /* skip the dot */ + t++; + + if (get_identifier (&t, &keyword)) + { + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + /* .true */ + if (str_equal ((byte *) "true", keyword)) + { + s->m_spec_type = st_true; + } + /* .false */ + else if (str_equal ((byte *) "false", keyword)) + { + s->m_spec_type = st_false; + } + /* .debug */ + else if (str_equal ((byte *) "debug", keyword)) + { + s->m_spec_type = st_debug; + } + /* .loop */ + else if (str_equal ((byte *) "loop", keyword)) + { + if (get_identifier (&t, &s->m_string)) + { + mem_free ((void **) (void *) &keyword); + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + s->m_spec_type = st_identifier_loop; + } + + mem_free ((void **) (void *) &keyword); + } + else + { + if (get_identifier (&t, &s->m_string)) + { + spec_destroy (&s); + return 1; + } + eat_spaces (&t); + + s->m_spec_type = st_identifier; + } + + if (get_error (&t, &s->m_errtext, maps)) + { + spec_destroy (&s); + return 1; + } + + if (get_emits (&t, &s->m_emits, mapb)) + { + spec_destroy (&s); + return 1; + } + + *text = t; + *sp = s; + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int get_rule (const byte **text, rule **ru, map_str *maps, map_byte *mapb) +{ + const byte *t = *text; + rule *r = NULL; + + rule_create (&r); + if (r == NULL) + return 1; + + if (get_spec (&t, &r->m_specs, maps, mapb)) + { + rule_destroy (&r); + return 1; + } + + while (*t != ';') + { + byte *op = NULL; + spec *sp = NULL; + + /* skip the dot that precedes "and" or "or" */ + t++; + + /* read "and" or "or" keyword */ + if (get_identifier (&t, &op)) + { + rule_destroy (&r); + return 1; + } + eat_spaces (&t); + + if (r->m_oper == op_none) + { + /* .and */ + if (str_equal ((byte *) "and", op)) + r->m_oper = op_and; + /* .or */ + else + r->m_oper = op_or; + } + + mem_free ((void **) (void *) &op); + + if (get_spec (&t, &sp, maps, mapb)) + { + rule_destroy (&r); + return 1; + } + + spec_append (&r->m_specs, &sp); + } + + /* skip the semicolon */ + t++; + eat_spaces (&t); + + *text = t; + *ru = r; + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int update_dependency (map_rule *mapr, byte *symbol, rule **ru) +{ + if (map_rule_find (&mapr, symbol, ru)) + return 1; + +/* (**ru).m_referenced = 1; */ + + return 0; +} + +/* + returns 0 on success, + returns 1 otherwise, +*/ +static int update_dependencies (dict *di, map_rule *mapr, byte **syntax_symbol, + byte **string_symbol, map_byte *regbytes) +{ + rule *rulez = di->m_rulez; + + /* update dependecies for the root and lexer symbols */ + if (update_dependency (mapr, *syntax_symbol, &di->m_syntax) || + (*string_symbol != NULL && update_dependency (mapr, *string_symbol, &di->m_string))) + return 1; + + mem_free ((void **) syntax_symbol); + mem_free ((void **) string_symbol); + + /* update dependecies for the rest of the rules */ + while (rulez) + { + spec *sp = rulez->m_specs; + + /* iterate through all the specifiers */ + while (sp) + { + /* update dependency for identifier */ + if (sp->m_spec_type == st_identifier || sp->m_spec_type == st_identifier_loop) + { + if (update_dependency (mapr, sp->m_string, &sp->m_rule)) + return 1; + + mem_free ((void **) &sp->m_string); + } + + /* some errtexts reference to a rule */ + if (sp->m_errtext && sp->m_errtext->m_token_name) + { + if (update_dependency (mapr, sp->m_errtext->m_token_name, &sp->m_errtext->m_token)) + return 1; + + mem_free ((void **) &sp->m_errtext->m_token_name); + } + + /* update dependency for condition */ + if (sp->m_cond) + { + int i; + for (i = 0; i < 2; i++) + if (sp->m_cond->m_operands[i].m_type == cot_regbyte) + { + sp->m_cond->m_operands[i].m_regbyte = map_byte_locate (®bytes, + sp->m_cond->m_operands[i].m_regname); + + if (sp->m_cond->m_operands[i].m_regbyte == NULL) + return 1; + + mem_free ((void **) &sp->m_cond->m_operands[i].m_regname); + } + } + + /* update dependency for all .load instructions */ + if (sp->m_emits) + { + emit *em = sp->m_emits; + while (em != NULL) + { + if (em->m_emit_dest == ed_regbyte) + { + em->m_regbyte = map_byte_locate (®bytes, em->m_regname); + + if (em->m_regbyte == NULL) + return 1; + + mem_free ((void **) &em->m_regname); + } + + em = em->m_next; + } + } + + sp = sp->m_next; + } + + rulez = rulez->m_next; + } + +/* check for unreferenced symbols */ +/* de = di->m_defntns; + while (de) + { + if (!de->m_referenced) + { + map_def *ma = mapd; + while (ma) + { + if (ma->data == de) + { + assert (0); + break; + } + ma = ma->next; + } + } + de = de->m_next; + } +*/ + return 0; +} + +static int satisfies_condition (cond *co, regbyte_ctx *ctx) +{ + byte values[2]; + int i; + + if (co == NULL) + return 1; + + for (i = 0; i < 2; i++) + switch (co->m_operands[i].m_type) + { + case cot_byte: + values[i] = co->m_operands[i].m_byte; + break; + case cot_regbyte: + values[i] = regbyte_ctx_extract (&ctx, co->m_operands[i].m_regbyte); + break; + } + + switch (co->m_type) + { + case ct_equal: + return values[0] == values[1]; + case ct_not_equal: + return values[0] != values[1]; + } + + return 0; +} + +static void free_regbyte_ctx_stack (regbyte_ctx *top, regbyte_ctx *limit) +{ + while (top != limit) + { + regbyte_ctx *rbc = top->m_prev; + regbyte_ctx_destroy (&top); + top = rbc; + } +} + +typedef enum match_result_ +{ + mr_not_matched, /* the examined string does not match */ + mr_matched, /* the examined string matches */ + mr_error_raised, /* mr_not_matched + error has been raised */ + mr_dont_emit, /* used by identifier loops only */ + mr_internal_error /* an internal error has occured such as out of memory */ +} match_result; + +/* + This function does the main job. It parses the text and generates output data. + + XXX optimize it - the barray seems to be the bottleneck +*/ +static match_result match (dict *di, const byte *text, unsigned int *index, rule *ru, barray **ba, + int filtering_string, regbyte_ctx **rbc) +{ + unsigned int ind = *index; + match_result status = mr_not_matched; + spec *sp = ru->m_specs; + regbyte_ctx *ctx = *rbc; + + /* for every specifier in the rule */ + while (sp) + { + unsigned int i, len, save_ind = ind; + barray *array = NULL; + + if (satisfies_condition (sp->m_cond, ctx)) + { + switch (sp->m_spec_type) + { + case st_identifier: + barray_create (&array); + if (array == NULL) + { + free_regbyte_ctx_stack (ctx, *rbc); + return mr_internal_error; + } + + status = match (di, text, &ind, sp->m_rule, &array, filtering_string, &ctx); + if (status == mr_internal_error) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + return mr_internal_error; + } + break; + case st_string: + len = str_length (sp->m_string); + + /* prefilter the stream */ + if (!filtering_string && di->m_string) + { + barray *ba; + unsigned int filter_index = 0; + match_result result; + regbyte_ctx *null_ctx = NULL; + + barray_create (&ba); + if (ba == NULL) + { + free_regbyte_ctx_stack (ctx, *rbc); + return mr_internal_error; + } + + result = match (di, text + ind, &filter_index, di->m_string, &ba, 1, &null_ctx); + + if (result == mr_internal_error) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&ba); + return mr_internal_error; + } + + if (result != mr_matched) + { + barray_destroy (&ba); + status = mr_not_matched; + break; + } + + barray_destroy (&ba); + + if (filter_index != len || !str_equal_n (sp->m_string, text + ind, len)) + { + status = mr_not_matched; + break; + } + + status = mr_matched; + ind += len; + } + else + { + status = mr_matched; + for (i = 0; status == mr_matched && i < len; i++) + if (text[ind + i] != sp->m_string[i]) + status = mr_not_matched; + if (status == mr_matched) + ind += len; + } + break; + case st_byte: + status = text[ind] == *sp->m_byte ? mr_matched : mr_not_matched; + if (status == mr_matched) + ind++; + break; + case st_byte_range: + status = (text[ind] >= sp->m_byte[0] && text[ind] <= sp->m_byte[1]) ? + mr_matched : mr_not_matched; + if (status == mr_matched) + ind++; + break; + case st_true: + status = mr_matched; + break; + case st_false: + status = mr_not_matched; + break; + case st_debug: + status = ru->m_oper == op_and ? mr_matched : mr_not_matched; + break; + case st_identifier_loop: + barray_create (&array); + if (array == NULL) + { + free_regbyte_ctx_stack (ctx, *rbc); + return mr_internal_error; + } + + status = mr_dont_emit; + for (;;) + { + match_result result; + + save_ind = ind; + result = match (di, text, &ind, sp->m_rule, &array, filtering_string, &ctx); + + if (result == mr_error_raised) + { + status = result; + break; + } + else if (result == mr_matched) + { + if (barray_push (ba, sp->m_emits, text[ind - 1], save_ind, &ctx) || + barray_append (ba, &array)) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + return mr_internal_error; + } + barray_destroy (&array); + barray_create (&array); + if (array == NULL) + { + free_regbyte_ctx_stack (ctx, *rbc); + return mr_internal_error; + } + } + else if (result == mr_internal_error) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + return mr_internal_error; + } + else + break; + } + break; + } + } + else + { + status = mr_not_matched; + } + + if (status == mr_error_raised) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + + return mr_error_raised; + } + + if (ru->m_oper == op_and && status != mr_matched && status != mr_dont_emit) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + + if (sp->m_errtext) + { + set_last_error (sp->m_errtext->m_text, error_get_token (sp->m_errtext, di, text, + ind), ind); + + return mr_error_raised; + } + + return mr_not_matched; + } + + if (status == mr_matched) + { + if (sp->m_emits) + if (barray_push (ba, sp->m_emits, text[ind - 1], save_ind, &ctx)) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + return mr_internal_error; + } + + if (array) + if (barray_append (ba, &array)) + { + free_regbyte_ctx_stack (ctx, *rbc); + barray_destroy (&array); + return mr_internal_error; + } + } + + barray_destroy (&array); + + /* if the rule operator is a logical or, we pick up the first matching specifier */ + if (ru->m_oper == op_or && (status == mr_matched || status == mr_dont_emit)) + { + *index = ind; + *rbc = ctx; + return mr_matched; + } + + sp = sp->m_next; + } + + /* everything went fine - all specifiers match up */ + if (ru->m_oper == op_and && (status == mr_matched || status == mr_dont_emit)) + { + *index = ind; + *rbc = ctx; + return mr_matched; + } + + free_regbyte_ctx_stack (ctx, *rbc); + return mr_not_matched; +} + +static byte *error_get_token (error *er, dict *di, const byte *text, unsigned int ind) +{ + byte *str = NULL; + + if (er->m_token) + { + barray *ba; + unsigned int filter_index = 0; + regbyte_ctx *ctx = NULL; + + barray_create (&ba); + if (ba != NULL) + { + if (match (di, text + ind, &filter_index, er->m_token, &ba, 0, &ctx) == mr_matched && + filter_index) + { + str = (byte *) mem_alloc (filter_index + 1); + if (str != NULL) + { + str_copy_n (str, text + ind, filter_index); + str[filter_index] = '\0'; + } + } + barray_destroy (&ba); + } + } + + return str; +} + +typedef struct grammar_load_state_ +{ + dict *di; + byte *syntax_symbol; + byte *string_symbol; + map_str *maps; + map_byte *mapb; + map_rule *mapr; +} grammar_load_state; + +static void grammar_load_state_create (grammar_load_state **gr) +{ + *gr = (grammar_load_state *) mem_alloc (sizeof (grammar_load_state)); + if (*gr) + { + (**gr).di = NULL; + (**gr).syntax_symbol = NULL; + (**gr).string_symbol = NULL; + (**gr).maps = NULL; + (**gr).mapb = NULL; + (**gr).mapr = NULL; + } +} + +static void grammar_load_state_destroy (grammar_load_state **gr) +{ + if (*gr) + { + dict_destroy (&(**gr).di); + mem_free ((void **) &(**gr).syntax_symbol); + mem_free ((void **) &(**gr).string_symbol); + map_str_destroy (&(**gr).maps); + map_byte_destroy (&(**gr).mapb); + map_rule_destroy (&(**gr).mapr); + mem_free ((void **) gr); + } +} + +/* + the API +*/ + +grammar grammar_load_from_text (const byte *text) +{ + grammar_load_state *g = NULL; + grammar id = 0; + + clear_last_error (); + + grammar_load_state_create (&g); + if (g == NULL) + return 0; + + dict_create (&g->di); + if (g->di == NULL) + { + grammar_load_state_destroy (&g); + return 0; + } + + eat_spaces (&text); + + /* skip ".syntax" keyword */ + text += 7; + eat_spaces (&text); + + /* retrieve root symbol */ + if (get_identifier (&text, &g->syntax_symbol)) + { + grammar_load_state_destroy (&g); + return 0; + } + eat_spaces (&text); + + /* skip semicolon */ + text++; + eat_spaces (&text); + + while (*text) + { + byte *symbol = NULL; + int is_dot = *text == '.'; + + if (is_dot) + text++; + + if (get_identifier (&text, &symbol)) + { + grammar_load_state_destroy (&g); + return 0; + } + eat_spaces (&text); + + /* .emtcode */ + if (is_dot && str_equal (symbol, (byte *) "emtcode")) + { + map_byte *ma = NULL; + + mem_free ((void **) (void *) &symbol); + + if (get_emtcode (&text, &ma)) + { + grammar_load_state_destroy (&g); + return 0; + } + + map_byte_append (&g->mapb, &ma); + } + /* .regbyte */ + else if (is_dot && str_equal (symbol, (byte *) "regbyte")) + { + map_byte *ma = NULL; + + mem_free ((void **) (void *) &symbol); + + if (get_regbyte (&text, &ma)) + { + grammar_load_state_destroy (&g); + return 0; + } + + map_byte_append (&g->di->m_regbytes, &ma); + } + /* .errtext */ + else if (is_dot && str_equal (symbol, (byte *) "errtext")) + { + map_str *ma = NULL; + + mem_free ((void **) (void *) &symbol); + + if (get_errtext (&text, &ma)) + { + grammar_load_state_destroy (&g); + return 0; + } + + map_str_append (&g->maps, &ma); + } + /* .string */ + else if (is_dot && str_equal (symbol, (byte *) "string")) + { + mem_free ((void **) (void *) &symbol); + + if (g->di->m_string != NULL) + { + grammar_load_state_destroy (&g); + return 0; + } + + if (get_identifier (&text, &g->string_symbol)) + { + grammar_load_state_destroy (&g); + return 0; + } + + /* skip semicolon */ + eat_spaces (&text); + text++; + eat_spaces (&text); + } + else + { + rule *ru = NULL; + map_rule *ma = NULL; + + if (get_rule (&text, &ru, g->maps, g->mapb)) + { + grammar_load_state_destroy (&g); + return 0; + } + + rule_append (&g->di->m_rulez, &ru); + + /* if a rule consist of only one specifier, give it an ".and" operator */ + if (ru->m_oper == op_none) + ru->m_oper = op_and; + + map_rule_create (&ma); + if (ma == NULL) + { + grammar_load_state_destroy (&g); + return 0; + } + + ma->key = symbol; + ma->data = ru; + map_rule_append (&g->mapr, &ma); + } + } + + if (update_dependencies (g->di, g->mapr, &g->syntax_symbol, &g->string_symbol, + g->di->m_regbytes)) + { + grammar_load_state_destroy (&g); + return 0; + } + + dict_append (&g_dicts, &g->di); + id = g->di->m_id; + g->di = NULL; + + grammar_load_state_destroy (&g); + + return id; +} + +int grammar_set_reg8 (grammar id, const byte *name, byte value) +{ + dict *di = NULL; + map_byte *reg = NULL; + + clear_last_error (); + + dict_find (&g_dicts, id, &di); + if (di == NULL) + { + set_last_error (INVALID_GRAMMAR_ID, NULL, -1); + return 0; + } + + reg = map_byte_locate (&di->m_regbytes, name); + if (reg == NULL) + { + set_last_error (INVALID_REGISTER_NAME, str_duplicate (name), -1); + return 0; + } + + reg->data = value; + return 1; +} + +int grammar_check (grammar id, const byte *text, byte **prod, unsigned int *size) +{ + dict *di = NULL; + barray *ba = NULL; + unsigned int index = 0; + regbyte_ctx *rbc = NULL; + + clear_last_error (); + + dict_find (&g_dicts, id, &di); + if (di == NULL) + { + set_last_error (INVALID_GRAMMAR_ID, NULL, -1); + return 0; + } + + barray_create (&ba); + if (ba == NULL) + return 0; + + *prod = NULL; + *size = 0; + + if (match (di, text, &index, di->m_syntax, &ba, 0, &rbc) != mr_matched) + { + barray_destroy (&ba); + free_regbyte_ctx_stack (rbc, NULL); + return 0; + } + + free_regbyte_ctx_stack (rbc, NULL); + + *prod = (byte *) mem_alloc (ba->len * sizeof (byte)); + if (*prod == NULL) + { + barray_destroy (&ba); + return 0; + } + + mem_copy (*prod, ba->data, ba->len * sizeof (byte)); + *size = ba->len; + barray_destroy (&ba); + + return 1; +} + +int grammar_destroy (grammar id) +{ + dict **di = &g_dicts; + + clear_last_error (); + + while (*di != NULL) + { + if ((**di).m_id == id) + { + dict *tmp = *di; + *di = (**di).m_next; + dict_destroy (&tmp); + return 1; + } + + di = &(**di).m_next; + } + + set_last_error (INVALID_GRAMMAR_ID, NULL, -1); + return 0; +} + +void grammar_get_last_error (byte *text, unsigned int size, int *pos) +{ + int len = 0, dots_made = 0; + const byte *p = error_message; + + *text = '\0'; + +#define APPEND_CHARACTER(x) if (dots_made == 0) {\ + if (len < (int)size - 1) {\ + text[len++] = (x); text[len] = '\0';\ + } else {\ + int i;\ + for (i = 0; i < 3; i++)\ + if (--len >= 0)\ + text[len] = '.';\ + dots_made = 1;\ + }\ + } + + if (p) + { + while (*p) + { + if (*p == '$') + { + const byte *r = error_param; + + while (*r) + { + APPEND_CHARACTER(*r) + r++; + } + + p++; + } + else + { + APPEND_CHARACTER(*p) + p++; + } + } + } + *pos = error_position; + +#undef APPEND_CHARACTER + +} + diff --git a/src/mesa/shader/grammar.h b/src/mesa/shader/grammar.h new file mode 100644 index 0000000..41a484e --- /dev/null +++ b/src/mesa/shader/grammar.h @@ -0,0 +1,92 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef GRAMMAR_H +#define GRAMMAR_H + + +#ifndef GRAMMAR_PORT_INCLUDE +#error Do not include this file directly, include your grammar_XXX.h instead +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + +void grammar_alloc_free (void *); +void *grammar_alloc_malloc (unsigned int); +void *grammar_alloc_realloc (void *, unsigned int, unsigned int); +void *grammar_memory_copy (void *, const void *, unsigned int); +int grammar_string_compare (const byte *, const byte *); +int grammar_string_compare_n (const byte *, const byte *, unsigned int); +byte *grammar_string_copy (byte *, const byte *); +byte *grammar_string_copy_n (byte *, const byte *, unsigned int); +byte *grammar_string_duplicate (const byte *); +unsigned int grammar_string_length (const byte *); + +/* + loads grammar script from null-terminated ASCII + returns unique grammar id to grammar object + returns 0 if an error occurs (call grammar_get_last_error to retrieve the error text) +*/ +grammar grammar_load_from_text (const byte *text); + +/* + sets a new to a register for grammar + returns 0 on error (call grammar_get_last_error to retrieve the error text) + returns 1 on success +*/ +int grammar_set_reg8 (grammar id, const byte *name, byte value); + +/* + checks if a null-terminated matches given grammar + returns 0 on error (call grammar_get_last_error to retrieve the error text) + returns 1 on success, the points to newly allocated buffer with production and + is filled with the production size + call grammar_alloc_free to free the memory block pointed by +*/ +int grammar_check (grammar id, const byte *text, byte **prod, unsigned int *size); + +/* + destroys grammar object identified by + returns 0 on error (call grammar_get_last_error to retrieve the error text) + returns 1 on success +*/ +int grammar_destroy (grammar id); + +/* + retrieves last grammar error reported either by grammar_load_from_text, grammar_check + or grammar_destroy + the user allocated buffer receives error description, points to error position, + is the size of the text buffer to fill in - it must be at least 4 bytes long, +*/ +void grammar_get_last_error (byte *text, unsigned int size, int *pos); + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/src/mesa/shader/grammar_mesa.c b/src/mesa/shader/grammar_mesa.c new file mode 100644 index 0000000..0aadac5 --- /dev/null +++ b/src/mesa/shader/grammar_mesa.c @@ -0,0 +1,87 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file grammar_mesa.c + * mesa3d port to syntax parsing engine + * \author Michal Krol + */ + +#include "grammar_mesa.h" + +#define GRAMMAR_PORT_BUILD 1 +#include "grammar.c" +#undef GRAMMAR_PORT_BUILD + + +void grammar_alloc_free (void *ptr) +{ + _mesa_free (ptr); +} + +void *grammar_alloc_malloc (unsigned int size) +{ + return _mesa_malloc (size); +} + +void *grammar_alloc_realloc (void *ptr, unsigned int old_size, unsigned int size) +{ + return _mesa_realloc (ptr, old_size, size); +} + +void *grammar_memory_copy (void *dst, const void * src, unsigned int size) +{ + return _mesa_memcpy (dst, src, size); +} + +int grammar_string_compare (const byte *str1, const byte *str2) +{ + return _mesa_strcmp ((const char *) str1, (const char *) str2); +} + +int grammar_string_compare_n (const byte *str1, const byte *str2, unsigned int n) +{ + return _mesa_strncmp ((const char *) str1, (const char *) str2, n); +} + +byte *grammar_string_copy (byte *dst, const byte *src) +{ + return (byte *) _mesa_strcpy ((char *) dst, (const char *) src); +} + +byte *grammar_string_copy_n (byte *dst, const byte *src, unsigned int n) +{ + return (byte *) _mesa_strncpy ((char *) dst, (const char *) src, n); +} + +byte *grammar_string_duplicate (const byte *src) +{ + return (byte *) _mesa_strdup ((const char *) src); +} + +unsigned int grammar_string_length (const byte *str) +{ + return _mesa_strlen ((const char *) str); +} + diff --git a/src/mesa/shader/grammar_mesa.h b/src/mesa/shader/grammar_mesa.h new file mode 100644 index 0000000..c14033a --- /dev/null +++ b/src/mesa/shader/grammar_mesa.h @@ -0,0 +1,43 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef GRAMMAR_MESA_H +#define GRAMMAR_MESA_H + + +#include "imports.h" +/* NOTE: include Mesa 3-D specific headers here */ + + +typedef GLuint grammar; +typedef GLubyte byte; + + +#define GRAMMAR_PORT_INCLUDE 1 +#include "grammar.h" +#undef GRAMMAR_PORT_INCLUDE + + +#endif + diff --git a/src/mesa/shader/grammar_syn.h b/src/mesa/shader/grammar_syn.h new file mode 100644 index 0000000..9c3419e --- /dev/null +++ b/src/mesa/shader/grammar_syn.h @@ -0,0 +1,226 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file grammar_syn.h + * syntax parsing engine language syntax + * \author Michal Krol + */ + +".syntax grammar;\n" +".emtcode DECLARATION_END 0x00\n" +".emtcode DECLARATION_EMITCODE 0x01\n" +".emtcode DECLARATION_ERRORTEXT 0x02\n" +".emtcode DECLARATION_REGBYTE 0x03\n" +".emtcode DECLARATION_LEXER 0x04\n" +".emtcode DECLARATION_RULE 0x05\n" +".emtcode SPECIFIER_END 0x00\n" +".emtcode SPECIFIER_AND_TAG 0x01\n" +".emtcode SPECIFIER_OR_TAG 0x02\n" +".emtcode SPECIFIER_CHARACTER_RANGE 0x03\n" +".emtcode SPECIFIER_CHARACTER 0x04\n" +".emtcode SPECIFIER_STRING 0x05\n" +".emtcode SPECIFIER_IDENTIFIER 0x06\n" +".emtcode SPECIFIER_TRUE 0x07\n" +".emtcode SPECIFIER_FALSE 0x08\n" +".emtcode SPECIFIER_DEBUG 0x09\n" +".emtcode IDENTIFIER_NO_LOOP 0x00\n" +".emtcode IDENTIFIER_LOOP 0x01\n" +".emtcode ERROR_NOT_PRESENT 0x00\n" +".emtcode ERROR_PRESENT 0x01\n" +".emtcode EMIT_NULL 0x00\n" +".emtcode EMIT_INTEGER 0x01\n" +".emtcode EMIT_IDENTIFIER 0x02\n" +".emtcode EMIT_CHARACTER 0x03\n" +".emtcode EMIT_LAST_CHARACTER 0x04\n" +".emtcode EMIT_CURRENT_POSITION 0x05\n" +".errtext INVALID_GRAMMAR \"internal error 2001: invalid grammar script\"\n" +".errtext SYNTAX_EXPECTED \"internal error 2002: '.syntax' keyword expected\"\n" +".errtext IDENTIFIER_EXPECTED \"internal error 2003: identifier expected\"\n" +".errtext MISSING_SEMICOLON \"internal error 2004: missing ';'\"\n" +".errtext INTEGER_EXPECTED \"internal error 2005: integer value expected\"\n" +".errtext STRING_EXPECTED \"internal error 2006: string expected\"\n" +"grammar\n" +" grammar_1 .error INVALID_GRAMMAR;\n" +"grammar_1\n" +" optional_space .and \".syntax\" .error SYNTAX_EXPECTED .and space .and identifier .and\n" +" semicolon .and declaration_list .and optional_space .and '\\0' .emit DECLARATION_END;\n" +"optional_space\n" +" space .or .true;\n" +"space\n" +" single_space .and .loop single_space;\n" +"single_space\n" +" white_char .or comment_block;\n" +"white_char\n" +" ' ' .or '\\t' .or '\\n' .or '\\r';\n" +"comment_block\n" +" '/' .and '*' .and .loop comment_char .and '*' .and '/';\n" +"comment_char\n" +" comment_char_no_star .or comment_char_1;\n" +"comment_char_1\n" +" '*' .and comment_char_no_slash;\n" +"comment_char_no_star\n" +" '\\x2B'-'\\xFF' .or '\\x01'-'\\x29';\n" +"comment_char_no_slash\n" +" '\\x30'-'\\xFF' .or '\\x01'-'\\x2E';\n" +"identifier\n" +" identifier_ne .error IDENTIFIER_EXPECTED;\n" +"identifier_ne\n" +" first_idchar .emit * .and .loop follow_idchar .emit * .and .true .emit '\\0';\n" +"first_idchar\n" +" 'a'-'z' .or 'A'-'Z' .or '_';\n" +"follow_idchar\n" +" first_idchar .or digit_dec;\n" +"digit_dec\n" +" '0'-'9';\n" +"semicolon\n" +" optional_space .and ';' .error MISSING_SEMICOLON .and optional_space;\n" +"declaration_list\n" +" declaration .and .loop declaration;\n" +"declaration\n" +" emitcode_definition .emit DECLARATION_EMITCODE .or\n" +" errortext_definition .emit DECLARATION_ERRORTEXT .or\n" +" regbyte_definition .emit DECLARATION_REGBYTE .or\n" +" lexer_definition .emit DECLARATION_LEXER .or\n" +" rule_definition .emit DECLARATION_RULE;\n" +"emitcode_definition\n" +" \".emtcode\" .and space .and identifier .and space .and integer .and space_or_null;\n" +"integer\n" +" integer_ne .error INTEGER_EXPECTED;\n" +"integer_ne\n" +" hex_prefix .and digit_hex .emit * .and .loop digit_hex .emit * .and .true .emit '\\0';\n" +"hex_prefix\n" +" '0' .and hex_prefix_1;\n" +"hex_prefix_1\n" +" 'x' .or 'X';\n" +"digit_hex\n" +" '0'-'9' .or 'a'-'f' .or 'A'-'F';\n" +"space_or_null\n" +" space .or '\\0';\n" +"errortext_definition\n" +" \".errtext\" .and space .and identifier .and space .and string .and space_or_null;\n" +"string\n" +" string_ne .error STRING_EXPECTED;\n" +"string_ne\n" +" '\"' .and .loop string_char_double_quotes .and '\"' .emit '\\0';\n" +"string_char_double_quotes\n" +" escape_sequence .or string_char .emit * .or '\\'' .emit *;\n" +"string_char\n" +" '\\x5D'-'\\xFF' .or '\\x28'-'\\x5B' .or '\\x23'-'\\x26' .or '\\x0E'-'\\x21' .or '\\x0B'-'\\x0C' .or\n" +" '\\x01'-'\\x09';\n" +"escape_sequence\n" +" '\\\\' .emit * .and escape_code;\n" +"escape_code\n" +" simple_escape_code .emit * .or hex_escape_code .or oct_escape_code;\n" +"simple_escape_code\n" +" '\\'' .or '\"' .or '?' .or '\\\\' .or 'a' .or 'b' .or 'f' .or 'n' .or 'r' .or 't' .or 'v';\n" +"hex_escape_code\n" +" 'x' .emit * .and digit_hex .emit * .and .loop digit_hex .emit *;\n" +"oct_escape_code\n" +" digit_oct .emit * .and optional_digit_oct .and optional_digit_oct;\n" +"digit_oct\n" +" '0'-'7';\n" +"optional_digit_oct\n" +" digit_oct .emit * .or .true;\n" +"regbyte_definition\n" +" \".regbyte\" .and space .and identifier .and space .and integer .and space_or_null;\n" +"lexer_definition\n" +" \".string\" .and space .and identifier .and semicolon;\n" +"rule_definition\n" +" identifier_ne .and space .and definition;\n" +"definition\n" +" specifier .and optional_specifiers_and_or .and semicolon .emit SPECIFIER_END;\n" +"optional_specifiers_and_or\n" +" and_specifiers .emit SPECIFIER_AND_TAG .or or_specifiers .emit SPECIFIER_OR_TAG .or .true;\n" +"specifier\n" +" specifier_condition .and optional_space .and specifier_rule;\n" +"specifier_condition\n" +" specifier_condition_1 .or .true;\n" +"specifier_condition_1\n" +" \".if\" .and optional_space .and '(' .and optional_space .and left_operand .and operator .and\n" +" right_operand .and optional_space .and ')';\n" +"left_operand\n" +" identifier;\n" +"operator\n" +" operator_1 .or operator_2;\n" +"operator_1\n" +" optional_space .and '!' .and '=' .and optional_space;\n" +"operator_2\n" +" optional_space .and '=' .and '=' .and optional_space;\n" +"right_operand\n" +" integer;\n" +"specifier_rule\n" +" specifier_rule_1 .and optional_error .and .loop emit .and .true .emit EMIT_NULL;\n" +"specifier_rule_1\n" +" character_range .emit SPECIFIER_CHARACTER_RANGE .or\n" +" character .emit SPECIFIER_CHARACTER .or\n" +" string_ne .emit SPECIFIER_STRING .or\n" +" \".true\" .emit SPECIFIER_TRUE .or\n" +" \".false\" .emit SPECIFIER_FALSE .or\n" +" \".debug\" .emit SPECIFIER_DEBUG .or\n" +" loop_identifier .emit SPECIFIER_IDENTIFIER;\n" +"character\n" +" '\\'' .and string_char_single_quotes .and '\\'' .emit '\\0';\n" +"string_char_single_quotes\n" +" escape_sequence .or string_char .emit * .or '\"' .emit *;\n" +"character_range\n" +" character .and optional_space .and '-' .and optional_space .and character;\n" +"loop_identifier\n" +" optional_loop .and identifier;\n" +"optional_loop\n" +" optional_loop_1 .emit IDENTIFIER_LOOP .or .true .emit IDENTIFIER_NO_LOOP;\n" +"optional_loop_1\n" +" \".loop\" .and space;\n" +"optional_error\n" +" error .emit ERROR_PRESENT .or .true .emit ERROR_NOT_PRESENT;\n" +"error\n" +" space .and \".error\" .and space .and identifier;\n" +"emit\n" +" emit_output .or emit_regbyte;\n" +"emit_output\n" +" space .and \".emit\" .and space .and emit_param;\n" +"emit_param\n" +" integer_ne .emit EMIT_INTEGER .or\n" +" identifier_ne .emit EMIT_IDENTIFIER .or\n" +" character .emit EMIT_CHARACTER .or\n" +" '*' .emit EMIT_LAST_CHARACTER .or\n" +" '$' .emit EMIT_CURRENT_POSITION;\n" +"emit_regbyte\n" +" space .and \".load\" .and space .and identifier .and space .and emit_param;\n" +"and_specifiers\n" +" and_specifier .and .loop and_specifier;\n" +"or_specifiers\n" +" or_specifier .and .loop or_specifier;\n" +"and_specifier\n" +" space .and \".and\" .and space .and specifier;\n" +"or_specifier\n" +" space .and \".or\" .and space .and specifier;\n" +".string __string_filter;\n" +"__string_filter\n" +" __first_identifier_char .and .loop __next_identifier_char;\n" +"__first_identifier_char\n" +" 'a'-'z' .or 'A'-'Z' .or '_' .or '.';\n" +"__next_identifier_char\n" +" 'a'-'z' .or 'A'-'Z' .or '_' .or '0'-'9';\n" +"" diff --git a/src/mesa/shader/nvfragparse.c b/src/mesa/shader/nvfragparse.c new file mode 100644 index 0000000..187ea05 --- /dev/null +++ b/src/mesa/shader/nvfragparse.c @@ -0,0 +1,1767 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file nvfragparse.c + * NVIDIA fragment program parser. + * \author Brian Paul + */ + +/* + * Regarding GL_NV_fragment_program: + * + * Portions of this software may use or implement intellectual + * property owned and licensed by NVIDIA Corporation. NVIDIA disclaims + * any and all warranties with respect to such intellectual property, + * including any use thereof or modifications thereto. + */ + +#include "glheader.h" +#include "context.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvfragprog.h" +#include "nvfragparse.h" +#include "nvprogram.h" +#include "program.h" + + +#define INPUT_1V 1 +#define INPUT_2V 2 +#define INPUT_3V 3 +#define INPUT_1S 4 +#define INPUT_2S 5 +#define INPUT_CC 6 +#define INPUT_1V_T 7 /* one source vector, plus textureId */ +#define INPUT_3V_T 8 /* one source vector, plus textureId */ +#define INPUT_NONE 9 +#define OUTPUT_V 20 +#define OUTPUT_S 21 +#define OUTPUT_NONE 22 + +/* IRIX defines some of these */ +#undef _R +#undef _H +#undef _X +#undef _C +#undef _S + +/* Optional suffixes */ +#define _R FLOAT32 /* float */ +#define _H FLOAT16 /* half-float */ +#define _X FIXED12 /* fixed */ +#define _C 0x08 /* set cond codes */ +#define _S 0x10 /* saturate, clamp result to [0,1] */ + +struct instruction_pattern { + const char *name; + enum fp_opcode opcode; + GLuint inputs; + GLuint outputs; + GLuint suffixes; +}; + +static const struct instruction_pattern Instructions[] = { + { "ADD", FP_OPCODE_ADD, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "COS", FP_OPCODE_COS, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "DDX", FP_OPCODE_DDX, INPUT_1V, OUTPUT_V, _R | _H | _C | _S }, + { "DDY", FP_OPCODE_DDY, INPUT_1V, OUTPUT_V, _R | _H | _C | _S }, + { "DP3", FP_OPCODE_DP3, INPUT_2V, OUTPUT_S, _R | _H | _X | _C | _S }, + { "DP4", FP_OPCODE_DP4, INPUT_2V, OUTPUT_S, _R | _H | _X | _C | _S }, + { "DST", FP_OPCODE_DP4, INPUT_2V, OUTPUT_V, _R | _H | _C | _S }, + { "EX2", FP_OPCODE_DP4, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "FLR", FP_OPCODE_FLR, INPUT_1V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "FRC", FP_OPCODE_FRC, INPUT_1V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "KIL", FP_OPCODE_KIL_NV, INPUT_CC, OUTPUT_NONE, 0 }, + { "LG2", FP_OPCODE_LG2, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "LIT", FP_OPCODE_LIT, INPUT_1V, OUTPUT_V, _R | _H | _C | _S }, + { "LRP", FP_OPCODE_LRP, INPUT_3V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "MAD", FP_OPCODE_MAD, INPUT_3V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "MAX", FP_OPCODE_MAX, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "MIN", FP_OPCODE_MIN, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "MOV", FP_OPCODE_MOV, INPUT_1V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "MUL", FP_OPCODE_MUL, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "PK2H", FP_OPCODE_PK2H, INPUT_1V, OUTPUT_S, 0 }, + { "PK2US", FP_OPCODE_PK2US, INPUT_1V, OUTPUT_S, 0 }, + { "PK4B", FP_OPCODE_PK4B, INPUT_1V, OUTPUT_S, 0 }, + { "PK4UB", FP_OPCODE_PK4UB, INPUT_1V, OUTPUT_S, 0 }, + { "POW", FP_OPCODE_POW, INPUT_2S, OUTPUT_S, _R | _H | _C | _S }, + { "RCP", FP_OPCODE_RCP, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "RFL", FP_OPCODE_RFL, INPUT_2V, OUTPUT_V, _R | _H | _C | _S }, + { "RSQ", FP_OPCODE_RSQ, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "SEQ", FP_OPCODE_SEQ, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SFL", FP_OPCODE_SFL, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SGE", FP_OPCODE_SGE, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SGT", FP_OPCODE_SGT, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SIN", FP_OPCODE_SIN, INPUT_1S, OUTPUT_S, _R | _H | _C | _S }, + { "SLE", FP_OPCODE_SLE, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SLT", FP_OPCODE_SLT, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SNE", FP_OPCODE_SNE, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "STR", FP_OPCODE_STR, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "SUB", FP_OPCODE_SUB, INPUT_2V, OUTPUT_V, _R | _H | _X | _C | _S }, + { "TEX", FP_OPCODE_TEX, INPUT_1V_T, OUTPUT_V, _C | _S }, + { "TXD", FP_OPCODE_TXD, INPUT_3V_T, OUTPUT_V, _C | _S }, + { "TXP", FP_OPCODE_TXP_NV, INPUT_1V_T, OUTPUT_V, _C | _S }, + { "UP2H", FP_OPCODE_UP2H, INPUT_1S, OUTPUT_V, _C | _S }, + { "UP2US", FP_OPCODE_UP2US, INPUT_1S, OUTPUT_V, _C | _S }, + { "UP4B", FP_OPCODE_UP4B, INPUT_1S, OUTPUT_V, _C | _S }, + { "UP4UB", FP_OPCODE_UP4UB, INPUT_1S, OUTPUT_V, _C | _S }, + { "X2D", FP_OPCODE_X2D, INPUT_3V, OUTPUT_V, _R | _H | _C | _S }, + { NULL, (enum fp_opcode) -1, 0, 0, 0 } +}; + + +/* + * Information needed or computed during parsing. + * Remember, we can't modify the target program object until we've + * _successfully_ parsed the program text. + */ +struct parse_state { + GLcontext *ctx; + const GLubyte *start; /* start of program string */ + const GLubyte *pos; /* current position */ + const GLubyte *curLine; + struct fragment_program *program; /* current program */ + + struct program_parameter_list *parameters; + + GLuint numInst; /* number of instructions parsed */ + GLuint inputsRead; /* bitmask of input registers used */ + GLuint outputsWritten; /* bitmask of 1 << FRAG_OUTPUT_* bits */ + GLuint texturesUsed[MAX_TEXTURE_IMAGE_UNITS]; +}; + + + +/* + * Called whenever we find an error during parsing. + */ +static void +record_error(struct parse_state *parseState, const char *msg, int lineNo) +{ +#ifdef DEBUG + GLint line, column; + const GLubyte *lineStr; + lineStr = _mesa_find_line_column(parseState->start, + parseState->pos, &line, &column); + _mesa_debug(parseState->ctx, + "nvfragparse.c(%d): line %d, column %d:%s (%s)\n", + lineNo, line, column, (char *) lineStr, msg); + _mesa_free((void *) lineStr); +#else + (void) lineNo; +#endif + + /* Check that no error was already recorded. Only record the first one. */ + if (parseState->ctx->Program.ErrorString[0] == 0) { + _mesa_set_program_error(parseState->ctx, + parseState->pos - parseState->start, + msg); + } +} + + +#define RETURN_ERROR \ +do { \ + record_error(parseState, "Unexpected end of input.", __LINE__); \ + return GL_FALSE; \ +} while(0) + +#define RETURN_ERROR1(msg) \ +do { \ + record_error(parseState, msg, __LINE__); \ + return GL_FALSE; \ +} while(0) + +#define RETURN_ERROR2(msg1, msg2) \ +do { \ + char err[1000]; \ + _mesa_sprintf(err, "%s %s", msg1, msg2); \ + record_error(parseState, err, __LINE__); \ + return GL_FALSE; \ +} while(0) + + + + +/* + * Search a list of instruction structures for a match. + */ +static struct instruction_pattern +MatchInstruction(const GLubyte *token) +{ + const struct instruction_pattern *inst; + struct instruction_pattern result; + + for (inst = Instructions; inst->name; inst++) { + if (_mesa_strncmp((const char *) token, inst->name, 3) == 0) { + /* matched! */ + int i = 3; + result = *inst; + result.suffixes = 0; + /* look at suffix */ + if (token[i] == 'R') { + result.suffixes |= _R; + i++; + } + else if (token[i] == 'H') { + result.suffixes |= _H; + i++; + } + else if (token[i] == 'X') { + result.suffixes |= _X; + i++; + } + if (token[i] == 'C') { + result.suffixes |= _C; + i++; + } + if (token[i] == '_' && token[i+1] == 'S' && + token[i+2] == 'A' && token[i+3] == 'T') { + result.suffixes |= _S; + } + return result; + } + } + result.opcode = (enum fp_opcode) -1; + return result; +} + + + + +/**********************************************************************/ + + +static GLboolean IsLetter(GLubyte b) +{ + return (b >= 'a' && b <= 'z') || + (b >= 'A' && b <= 'Z') || + (b == '_') || + (b == '$'); +} + + +static GLboolean IsDigit(GLubyte b) +{ + return b >= '0' && b <= '9'; +} + + +static GLboolean IsWhitespace(GLubyte b) +{ + return b == ' ' || b == '\t' || b == '\n' || b == '\r'; +} + + +/** + * Starting at 'str' find the next token. A token can be an integer, + * an identifier or punctuation symbol. + * \return <= 0 we found an error, else, return number of characters parsed. + */ +static GLint +GetToken(struct parse_state *parseState, GLubyte *token) +{ + const GLubyte *str = parseState->pos; + GLint i = 0, j = 0; + + token[0] = 0; + + /* skip whitespace and comments */ + while (str[i] && (IsWhitespace(str[i]) || str[i] == '#')) { + if (str[i] == '#') { + /* skip comment */ + while (str[i] && (str[i] != '\n' && str[i] != '\r')) { + i++; + } + if (str[i] == '\n' || str[i] == '\r') + parseState->curLine = str + i + 1; + } + else { + /* skip whitespace */ + if (str[i] == '\n' || str[i] == '\r') + parseState->curLine = str + i + 1; + i++; + } + } + + if (str[i] == 0) + return -i; + + /* try matching an integer */ + while (str[i] && IsDigit(str[i])) { + token[j++] = str[i++]; + } + if (j > 0 || !str[i]) { + token[j] = 0; + return i; + } + + /* try matching an identifier */ + if (IsLetter(str[i])) { + while (str[i] && (IsLetter(str[i]) || IsDigit(str[i]))) { + token[j++] = str[i++]; + } + token[j] = 0; + return i; + } + + /* punctuation character */ + if (str[i]) { + token[0] = str[i++]; + token[1] = 0; + return i; + } + + /* end of input */ + token[0] = 0; + return i; +} + + +/** + * Get next token from input stream and increment stream pointer past token. + */ +static GLboolean +Parse_Token(struct parse_state *parseState, GLubyte *token) +{ + GLint i; + i = GetToken(parseState, token); + if (i <= 0) { + parseState->pos += (-i); + return GL_FALSE; + } + parseState->pos += i; + return GL_TRUE; +} + + +/** + * Get next token from input stream but don't increment stream pointer. + */ +static GLboolean +Peek_Token(struct parse_state *parseState, GLubyte *token) +{ + GLint i, len; + i = GetToken(parseState, token); + if (i <= 0) { + parseState->pos += (-i); + return GL_FALSE; + } + len = _mesa_strlen((const char *) token); + parseState->pos += (i - len); + return GL_TRUE; +} + + +/**********************************************************************/ + +static const char *InputRegisters[MAX_NV_FRAGMENT_PROGRAM_INPUTS + 1] = { + "WPOS", "COL0", "COL1", "FOGC", + "TEX0", "TEX1", "TEX2", "TEX3", "TEX4", "TEX5", "TEX6", "TEX7", NULL +}; + +static const char *OutputRegisters[MAX_NV_FRAGMENT_PROGRAM_OUTPUTS + 1] = { + "COLR", "COLH", + /* These are only allows for register combiners */ + /* + "TEX0", "TEX1", "TEX2", "TEX3", + */ + "DEPR", NULL +}; + + + + +/**********************************************************************/ + +/** + * Try to match 'pattern' as the next token after any whitespace/comments. + */ +static GLboolean +Parse_String(struct parse_state *parseState, const char *pattern) +{ + const GLubyte *m; + GLint i; + + /* skip whitespace and comments */ + while (IsWhitespace(*parseState->pos) || *parseState->pos == '#') { + if (*parseState->pos == '#') { + while (*parseState->pos && (*parseState->pos != '\n' && *parseState->pos != '\r')) { + parseState->pos += 1; + } + if (*parseState->pos == '\n' || *parseState->pos == '\r') + parseState->curLine = parseState->pos + 1; + } + else { + /* skip whitespace */ + if (*parseState->pos == '\n' || *parseState->pos == '\r') + parseState->curLine = parseState->pos + 1; + parseState->pos += 1; + } + } + + /* Try to match the pattern */ + m = parseState->pos; + for (i = 0; pattern[i]; i++) { + if (*m != (GLubyte) pattern[i]) + return GL_FALSE; + m += 1; + } + parseState->pos = m; + + return GL_TRUE; /* success */ +} + + +static GLboolean +Parse_Identifier(struct parse_state *parseState, GLubyte *ident) +{ + if (!Parse_Token(parseState, ident)) + RETURN_ERROR; + if (IsLetter(ident[0])) + return GL_TRUE; + else + RETURN_ERROR1("Expected an identfier"); +} + + +/** + * Parse a floating point constant, or a defined symbol name. + * [+/-]N[.N[eN]] + * Output: number[0 .. 3] will get the value. + */ +static GLboolean +Parse_ScalarConstant(struct parse_state *parseState, GLfloat *number) +{ + char *end = NULL; + + *number = (GLfloat) _mesa_strtod((const char *) parseState->pos, &end); + + if (end && end > (char *) parseState->pos) { + /* got a number */ + parseState->pos = (GLubyte *) end; + number[1] = *number; + number[2] = *number; + number[3] = *number; + return GL_TRUE; + } + else { + /* should be an identifier */ + GLubyte ident[100]; + const GLfloat *constant; + if (!Parse_Identifier(parseState, ident)) + RETURN_ERROR1("Expected an identifier"); + constant = _mesa_lookup_parameter_value(parseState->parameters, + -1, (const char *) ident); + /* XXX Check that it's a constant and not a parameter */ + if (!constant) { + RETURN_ERROR1("Undefined symbol"); + } + else { + COPY_4V(number, constant); + return GL_TRUE; + } + } +} + + + +/** + * Parse a vector constant, one of: + * { float } + * { float, float } + * { float, float, float } + * { float, float, float, float } + */ +static GLboolean +Parse_VectorConstant(struct parse_state *parseState, GLfloat *vec) +{ + /* "{" was already consumed */ + + ASSIGN_4V(vec, 0.0, 0.0, 0.0, 1.0); + + if (!Parse_ScalarConstant(parseState, vec+0)) /* X */ + return GL_FALSE; + + if (Parse_String(parseState, "}")) { + return GL_TRUE; + } + + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected comma in vector constant"); + + if (!Parse_ScalarConstant(parseState, vec+1)) /* Y */ + return GL_FALSE; + + if (Parse_String(parseState, "}")) { + return GL_TRUE; + } + + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected comma in vector constant"); + + if (!Parse_ScalarConstant(parseState, vec+2)) /* Z */ + return GL_FALSE; + + if (Parse_String(parseState, "}")) { + return GL_TRUE; + } + + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected comma in vector constant"); + + if (!Parse_ScalarConstant(parseState, vec+3)) /* W */ + return GL_FALSE; + + if (!Parse_String(parseState, "}")) + RETURN_ERROR1("Expected closing brace in vector constant"); + + return GL_TRUE; +} + + +/** + * Parse , or {a, b, c, d}. + * Return number of values in the vector or scalar, or zero if parse error. + */ +static GLuint +Parse_VectorOrScalarConstant(struct parse_state *parseState, GLfloat *vec) +{ + if (Parse_String(parseState, "{")) { + return Parse_VectorConstant(parseState, vec); + } + else { + GLboolean b = Parse_ScalarConstant(parseState, vec); + if (b) { + vec[1] = vec[2] = vec[3] = vec[0]; + } + return b; + } +} + + +/** + * Parse a texture image source: + * [TEX0 | TEX1 | .. | TEX15] , [1D | 2D | 3D | CUBE | RECT] + */ +static GLboolean +Parse_TextureImageId(struct parse_state *parseState, + GLubyte *texUnit, GLubyte *texTargetBit) +{ + GLubyte imageSrc[100]; + GLint unit; + + if (!Parse_Token(parseState, imageSrc)) + RETURN_ERROR; + + if (imageSrc[0] != 'T' || + imageSrc[1] != 'E' || + imageSrc[2] != 'X') { + RETURN_ERROR1("Expected TEX# source"); + } + unit = _mesa_atoi((const char *) imageSrc + 3); + if ((unit < 0 || unit > MAX_TEXTURE_IMAGE_UNITS) || + (unit == 0 && (imageSrc[3] != '0' || imageSrc[4] != 0))) { + RETURN_ERROR1("Invalied TEX# source index"); + } + *texUnit = unit; + + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + + if (Parse_String(parseState, "1D")) { + *texTargetBit = TEXTURE_1D_BIT; + } + else if (Parse_String(parseState, "2D")) { + *texTargetBit = TEXTURE_2D_BIT; + } + else if (Parse_String(parseState, "3D")) { + *texTargetBit = TEXTURE_3D_BIT; + } + else if (Parse_String(parseState, "CUBE")) { + *texTargetBit = TEXTURE_CUBE_BIT; + } + else if (Parse_String(parseState, "RECT")) { + *texTargetBit = TEXTURE_RECT_BIT; + } + else { + RETURN_ERROR1("Invalid texture target token"); + } + + /* update record of referenced texture units */ + parseState->texturesUsed[*texUnit] |= *texTargetBit; + if (_mesa_bitcount(parseState->texturesUsed[*texUnit]) > 1) { + RETURN_ERROR1("Only one texture target can be used per texture unit."); + } + + return GL_TRUE; +} + + +/** + * Parse a scalar suffix like .x, .y, .z or .w or parse a swizzle suffix + * like .wxyz, .xxyy, etc and return the swizzle indexes. + */ +static GLboolean +Parse_SwizzleSuffix(const GLubyte *token, GLuint swizzle[4]) +{ + if (token[1] == 0) { + /* single letter swizzle (scalar) */ + if (token[0] == 'x') + ASSIGN_4V(swizzle, 0, 0, 0, 0); + else if (token[0] == 'y') + ASSIGN_4V(swizzle, 1, 1, 1, 1); + else if (token[0] == 'z') + ASSIGN_4V(swizzle, 2, 2, 2, 2); + else if (token[0] == 'w') + ASSIGN_4V(swizzle, 3, 3, 3, 3); + else + return GL_FALSE; + } + else { + /* 4-component swizzle (vector) */ + GLint k; + for (k = 0; token[k] && k < 4; k++) { + if (token[k] == 'x') + swizzle[k] = 0; + else if (token[k] == 'y') + swizzle[k] = 1; + else if (token[k] == 'z') + swizzle[k] = 2; + else if (token[k] == 'w') + swizzle[k] = 3; + else + return GL_FALSE; + } + if (k != 4) + return GL_FALSE; + } + return GL_TRUE; +} + + +static GLboolean +Parse_CondCodeMask(struct parse_state *parseState, + struct fp_dst_register *dstReg) +{ + if (Parse_String(parseState, "EQ")) + dstReg->CondMask = COND_EQ; + else if (Parse_String(parseState, "GE")) + dstReg->CondMask = COND_GE; + else if (Parse_String(parseState, "GT")) + dstReg->CondMask = COND_GT; + else if (Parse_String(parseState, "LE")) + dstReg->CondMask = COND_LE; + else if (Parse_String(parseState, "LT")) + dstReg->CondMask = COND_LT; + else if (Parse_String(parseState, "NE")) + dstReg->CondMask = COND_NE; + else if (Parse_String(parseState, "TR")) + dstReg->CondMask = COND_TR; + else if (Parse_String(parseState, "FL")) + dstReg->CondMask = COND_FL; + else + RETURN_ERROR1("Invalid condition code mask"); + + /* look for optional .xyzw swizzle */ + if (Parse_String(parseState, ".")) { + GLubyte token[100]; + if (!Parse_Token(parseState, token)) /* get xyzw suffix */ + RETURN_ERROR; + + if (!Parse_SwizzleSuffix(token, dstReg->CondSwizzle)) + RETURN_ERROR1("Invalid swizzle suffix"); + } + + return GL_TRUE; +} + + +/** + * Parse a temporary register: Rnn or Hnn + */ +static GLboolean +Parse_TempReg(struct parse_state *parseState, GLint *tempRegNum) +{ + GLubyte token[100]; + + /* Should be 'R##' or 'H##' */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + if (token[0] != 'R' && token[0] != 'H') + RETURN_ERROR1("Expected R## or H##"); + + if (IsDigit(token[1])) { + GLint reg = _mesa_atoi((const char *) (token + 1)); + if (token[0] == 'H') + reg += 32; + if (reg >= MAX_NV_FRAGMENT_PROGRAM_TEMPS) + RETURN_ERROR1("Invalid temporary register name"); + *tempRegNum = reg; + } + else { + RETURN_ERROR1("Invalid temporary register name"); + } + + return GL_TRUE; +} + + +/** + * Parse a write-only dummy register: RC or HC. + */ +static GLboolean +Parse_DummyReg(struct parse_state *parseState, GLint *regNum) +{ + if (Parse_String(parseState, "RC")) { + *regNum = 0; + } + else if (Parse_String(parseState, "HC")) { + *regNum = 1; + } + else { + RETURN_ERROR1("Invalid write-only register name"); + } + + return GL_TRUE; +} + + +/** + * Parse a program local parameter register "p[##]" + */ +static GLboolean +Parse_ProgramParamReg(struct parse_state *parseState, GLint *regNum) +{ + GLubyte token[100]; + + if (!Parse_String(parseState, "p[")) + RETURN_ERROR1("Expected p["); + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (IsDigit(token[0])) { + /* a numbered program parameter register */ + GLint reg = _mesa_atoi((const char *) token); + if (reg >= MAX_NV_FRAGMENT_PROGRAM_PARAMS) + RETURN_ERROR1("Invalid constant program number"); + *regNum = reg; + } + else { + RETURN_ERROR; + } + + if (!Parse_String(parseState, "]")) + RETURN_ERROR1("Expected ]"); + + return GL_TRUE; +} + + +/** + * Parse f[name] - fragment input register + */ +static GLboolean +Parse_FragReg(struct parse_state *parseState, GLint *tempRegNum) +{ + GLubyte token[100]; + GLint j; + + /* Match 'f[' */ + if (!Parse_String(parseState, "f[")) + RETURN_ERROR1("Expected f["); + + /* get and look for match */ + if (!Parse_Token(parseState, token)) { + RETURN_ERROR; + } + for (j = 0; InputRegisters[j]; j++) { + if (_mesa_strcmp((const char *) token, InputRegisters[j]) == 0) { + *tempRegNum = j; + parseState->inputsRead |= (1 << j); + break; + } + } + if (!InputRegisters[j]) { + /* unknown input register label */ + RETURN_ERROR2("Invalid register name", token); + } + + /* Match '[' */ + if (!Parse_String(parseState, "]")) + RETURN_ERROR1("Expected ]"); + + return GL_TRUE; +} + + +static GLboolean +Parse_OutputReg(struct parse_state *parseState, GLint *outputRegNum) +{ + GLubyte token[100]; + GLint j; + + /* Match "o[" */ + if (!Parse_String(parseState, "o[")) + RETURN_ERROR1("Expected o["); + + /* Get output reg name */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + /* try to match an output register name */ + for (j = 0; OutputRegisters[j]; j++) { + if (_mesa_strcmp((const char *) token, OutputRegisters[j]) == 0) { + static GLuint bothColors = (1 << FRAG_OUTPUT_COLR) | (1 << FRAG_OUTPUT_COLH); + *outputRegNum = j; + parseState->outputsWritten |= (1 << j); + if ((parseState->outputsWritten & bothColors) == bothColors) { + RETURN_ERROR1("Illegal to write to both o[COLR] and o[COLH]"); + } + break; + } + } + if (!OutputRegisters[j]) + RETURN_ERROR1("Invalid output register name"); + + /* Match ']' */ + if (!Parse_String(parseState, "]")) + RETURN_ERROR1("Expected ]"); + + return GL_TRUE; +} + + +static GLboolean +Parse_MaskedDstReg(struct parse_state *parseState, + struct fp_dst_register *dstReg) +{ + GLubyte token[100]; + + /* Dst reg can be R, H, o[n], RC or HC */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + if (_mesa_strcmp((const char *) token, "RC") == 0 || + _mesa_strcmp((const char *) token, "HC") == 0) { + /* a write-only register */ + dstReg->File = PROGRAM_WRITE_ONLY; + if (!Parse_DummyReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'R' || token[0] == 'H') { + /* a temporary register */ + dstReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'o') { + /* an output register */ + dstReg->File = PROGRAM_OUTPUT; + if (!Parse_OutputReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else { + RETURN_ERROR1("Invalid destination register name"); + } + + /* Parse optional write mask */ + if (Parse_String(parseState, ".")) { + /* got a mask */ + GLint k = 0; + + if (!Parse_Token(parseState, token)) /* get xyzw writemask */ + RETURN_ERROR; + + dstReg->WriteMask[0] = GL_FALSE; + dstReg->WriteMask[1] = GL_FALSE; + dstReg->WriteMask[2] = GL_FALSE; + dstReg->WriteMask[3] = GL_FALSE; + + if (token[k] == 'x') { + dstReg->WriteMask[0] = GL_TRUE; + k++; + } + if (token[k] == 'y') { + dstReg->WriteMask[1] = GL_TRUE; + k++; + } + if (token[k] == 'z') { + dstReg->WriteMask[2] = GL_TRUE; + k++; + } + if (token[k] == 'w') { + dstReg->WriteMask[3] = GL_TRUE; + k++; + } + if (k == 0) { + RETURN_ERROR1("Invalid writemask character"); + } + + } + else { + dstReg->WriteMask[0] = GL_TRUE; + dstReg->WriteMask[1] = GL_TRUE; + dstReg->WriteMask[2] = GL_TRUE; + dstReg->WriteMask[3] = GL_TRUE; + } + + /* optional condition code mask */ + if (Parse_String(parseState, "(")) { + /* ("EQ" | "GE" | "GT" | "LE" | "LT" | "NE" | "TR" | "FL".x|y|z|w) */ + /* ("EQ" | "GE" | "GT" | "LE" | "LT" | "NE" | "TR" | "FL".[xyzw]) */ + if (!Parse_CondCodeMask(parseState, dstReg)) + RETURN_ERROR; + + if (!Parse_String(parseState, ")")) /* consume ")" */ + RETURN_ERROR1("Expected )"); + + return GL_TRUE; + } + else { + /* no cond code mask */ + dstReg->CondMask = COND_TR; + dstReg->CondSwizzle[0] = 0; + dstReg->CondSwizzle[1] = 1; + dstReg->CondSwizzle[2] = 2; + dstReg->CondSwizzle[3] = 3; + return GL_TRUE; + } +} + + +/** + * Parse a vector source (register, constant, etc): + * ::= + * | + * ::= "|" "|" + */ +static GLboolean +Parse_VectorSrc(struct parse_state *parseState, + struct fp_src_register *srcReg) +{ + GLfloat sign = 1.0F; + GLubyte token[100]; + + /* + * First, take care of +/- and absolute value stuff. + */ + if (Parse_String(parseState, "-")) + sign = -1.0F; + else if (Parse_String(parseState, "+")) + sign = +1.0F; + + if (Parse_String(parseState, "|")) { + srcReg->Abs = GL_TRUE; + srcReg->NegateAbs = (sign < 0.0F) ? GL_TRUE : GL_FALSE; + + if (Parse_String(parseState, "-")) + srcReg->NegateBase = GL_TRUE; + else if (Parse_String(parseState, "+")) + srcReg->NegateBase = GL_FALSE; + else + srcReg->NegateBase = GL_FALSE; + } + else { + srcReg->Abs = GL_FALSE; + srcReg->NegateAbs = GL_FALSE; + srcReg->NegateBase = (sign < 0.0F) ? GL_TRUE : GL_FALSE; + } + + /* This should be the real src vector/register name */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + /* Src reg can be Rn, Hn, f[n], p[n], a named parameter, a scalar + * literal or vector literal. + */ + if (token[0] == 'R' || token[0] == 'H') { + srcReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'f') { + /* XXX this might be an identier! */ + srcReg->File = PROGRAM_INPUT; + if (!Parse_FragReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'p') { + /* XXX this might be an identier! */ + srcReg->File = PROGRAM_LOCAL_PARAM; + if (!Parse_ProgramParamReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (IsLetter(token[0])){ + GLubyte ident[100]; + GLint paramIndex; + if (!Parse_Identifier(parseState, ident)) + RETURN_ERROR; + paramIndex = _mesa_lookup_parameter_index(parseState->parameters, + -1, (const char *) ident); + if (paramIndex < 0) { + RETURN_ERROR2("Undefined constant or parameter: ", ident); + } + srcReg->File = PROGRAM_NAMED_PARAM; + srcReg->Index = paramIndex; + } + else if (IsDigit(token[0]) || token[0] == '-' || token[0] == '+' || token[0] == '.'){ + /* literal scalar constant */ + GLfloat values[4]; + GLuint paramIndex; + if (!Parse_ScalarConstant(parseState, values)) + RETURN_ERROR; + paramIndex = _mesa_add_unnamed_constant(parseState->parameters, values); + srcReg->File = PROGRAM_NAMED_PARAM; + srcReg->Index = paramIndex; + } + else if (token[0] == '{'){ + /* literal vector constant */ + GLfloat values[4]; + GLuint paramIndex; + (void) Parse_String(parseState, "{"); + if (!Parse_VectorConstant(parseState, values)) + RETURN_ERROR; + paramIndex = _mesa_add_unnamed_constant(parseState->parameters, values); + srcReg->File = PROGRAM_NAMED_PARAM; + srcReg->Index = paramIndex; + } + else { + RETURN_ERROR2("Invalid source register name", token); + } + + /* init swizzle fields */ + srcReg->Swizzle[0] = 0; + srcReg->Swizzle[1] = 1; + srcReg->Swizzle[2] = 2; + srcReg->Swizzle[3] = 3; + + /* Look for optional swizzle suffix */ + if (Parse_String(parseState, ".")) { + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (!Parse_SwizzleSuffix(token, srcReg->Swizzle)) + RETURN_ERROR1("Invalid swizzle suffix"); + } + + /* Finish absolute value */ + if (srcReg->Abs && !Parse_String(parseState, "|")) { + RETURN_ERROR1("Expected |"); + } + + return GL_TRUE; +} + + +static GLboolean +Parse_ScalarSrcReg(struct parse_state *parseState, + struct fp_src_register *srcReg) +{ + GLubyte token[100]; + GLfloat sign = 1.0F; + GLboolean needSuffix = GL_TRUE; + + /* + * First, take care of +/- and absolute value stuff. + */ + if (Parse_String(parseState, "-")) + sign = -1.0F; + else if (Parse_String(parseState, "+")) + sign = +1.0F; + + if (Parse_String(parseState, "|")) { + srcReg->Abs = GL_TRUE; + srcReg->NegateAbs = (sign < 0.0F) ? GL_TRUE : GL_FALSE; + + if (Parse_String(parseState, "-")) + srcReg->NegateBase = GL_TRUE; + else if (Parse_String(parseState, "+")) + srcReg->NegateBase = GL_FALSE; + else + srcReg->NegateBase = GL_FALSE; + } + else { + srcReg->Abs = GL_FALSE; + srcReg->NegateAbs = GL_FALSE; + srcReg->NegateBase = (sign < 0.0F) ? GL_TRUE : GL_FALSE; + } + + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + /* Src reg can be R, H or a named fragment attrib */ + if (token[0] == 'R' || token[0] == 'H') { + srcReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'f') { + srcReg->File = PROGRAM_INPUT; + if (!Parse_FragReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == '{') { + /* vector literal */ + GLfloat values[4]; + GLuint paramIndex; + (void) Parse_String(parseState, "{"); + if (!Parse_VectorConstant(parseState, values)) + RETURN_ERROR; + paramIndex = _mesa_add_unnamed_constant(parseState->parameters, values); + srcReg->File = PROGRAM_NAMED_PARAM; + srcReg->Index = paramIndex; + } + else if (IsDigit(token[0])) { + /* scalar literal */ + GLfloat values[4]; + GLuint paramIndex; + if (!Parse_ScalarConstant(parseState, values)) + RETURN_ERROR; + paramIndex = _mesa_add_unnamed_constant(parseState->parameters, values); + srcReg->Index = paramIndex; + srcReg->File = PROGRAM_NAMED_PARAM; + needSuffix = GL_FALSE; + } + else { + RETURN_ERROR2("Invalid scalar source argument", token); + } + + if (needSuffix) { + /* parse .[xyzw] suffix */ + if (!Parse_String(parseState, ".")) + RETURN_ERROR1("Expected ."); + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (token[0] == 'x' && token[1] == 0) { + srcReg->Swizzle[0] = 0; + } + else if (token[0] == 'y' && token[1] == 0) { + srcReg->Swizzle[0] = 1; + } + else if (token[0] == 'z' && token[1] == 0) { + srcReg->Swizzle[0] = 2; + } + else if (token[0] == 'w' && token[1] == 0) { + srcReg->Swizzle[0] = 3; + } + else { + RETURN_ERROR1("Invalid scalar source suffix"); + } + } + else { + srcReg->Swizzle[0] = 0; + } + srcReg->Swizzle[1] = srcReg->Swizzle[2] = srcReg->Swizzle[3] = 0; + + /* Finish absolute value */ + if (srcReg->Abs && !Parse_String(parseState, "|")) { + RETURN_ERROR1("Expected |"); + } + + return GL_TRUE; +} + + + +static GLboolean +Parse_InstructionSequence(struct parse_state *parseState, + struct fp_instruction program[]) +{ + while (1) { + struct fp_instruction *inst = program + parseState->numInst; + struct instruction_pattern instMatch; + GLubyte token[100]; + + /* Initialize the instruction */ + inst->SrcReg[0].File = (enum register_file) -1; + inst->SrcReg[1].File = (enum register_file) -1; + inst->SrcReg[2].File = (enum register_file) -1; + inst->DstReg.File = (enum register_file) -1; + inst->DstReg.CondSwizzle[0] = 0; + inst->DstReg.CondSwizzle[1] = 1; + inst->DstReg.CondSwizzle[2] = 2; + inst->DstReg.CondSwizzle[3] = 3; + + /* special instructions */ + if (Parse_String(parseState, "DEFINE")) { + GLubyte id[100]; + GLfloat value[7]; /* yes, 7 to be safe */ + if (!Parse_Identifier(parseState, id)) + RETURN_ERROR; + /* XXX make sure id is not a reserved identifer, like R9 */ + if (!Parse_String(parseState, "=")) + RETURN_ERROR1("Expected ="); + if (!Parse_VectorOrScalarConstant(parseState, value)) + RETURN_ERROR; + if (!Parse_String(parseState, ";")) + RETURN_ERROR1("Expected ;"); + if (_mesa_lookup_parameter_index(parseState->parameters, + -1, (const char *) id) >= 0) { + RETURN_ERROR2(id, "already defined"); + } + _mesa_add_named_parameter(parseState->parameters, + (const char *) id, value); + } + else if (Parse_String(parseState, "DECLARE")) { + GLubyte id[100]; + GLfloat value[7] = {0, 0, 0, 0, 0, 0, 0}; /* yes, to be safe */ + if (!Parse_Identifier(parseState, id)) + RETURN_ERROR; + /* XXX make sure id is not a reserved identifer, like R9 */ + if (Parse_String(parseState, "=")) { + if (!Parse_VectorOrScalarConstant(parseState, value)) + RETURN_ERROR; + } + if (!Parse_String(parseState, ";")) + RETURN_ERROR1("Expected ;"); + if (_mesa_lookup_parameter_index(parseState->parameters, + -1, (const char *) id) >= 0) { + RETURN_ERROR2(id, "already declared"); + } + _mesa_add_named_parameter(parseState->parameters, + (const char *) id, value); + } + else if (Parse_String(parseState, "END")) { + inst->Opcode = FP_OPCODE_END; + inst->StringPos = parseState->curLine - parseState->start; + assert(inst->StringPos >= 0); + parseState->numInst++; + if (Parse_Token(parseState, token)) { + RETURN_ERROR1("Code after END opcode."); + } + break; + } + else { + /* general/arithmetic instruction */ + + /* get token */ + if (!Parse_Token(parseState, token)) { + RETURN_ERROR1("Missing END instruction."); + } + + /* try to find matching instuction */ + instMatch = MatchInstruction(token); + if (instMatch.opcode < 0) { + /* bad instruction name */ + RETURN_ERROR2("Unexpected token: ", token); + } + + inst->Opcode = instMatch.opcode; + inst->Precision = instMatch.suffixes & (_R | _H | _X); + inst->Saturate = (instMatch.suffixes & (_S)) ? GL_TRUE : GL_FALSE; + inst->UpdateCondRegister = (instMatch.suffixes & (_C)) ? GL_TRUE : GL_FALSE; + inst->StringPos = parseState->curLine - parseState->start; + assert(inst->StringPos >= 0); + + /* + * parse the input and output operands + */ + if (instMatch.outputs == OUTPUT_S || instMatch.outputs == OUTPUT_V) { + if (!Parse_MaskedDstReg(parseState, &inst->DstReg)) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + } + else if (instMatch.outputs == OUTPUT_NONE) { + ASSERT(instMatch.opcode == FP_OPCODE_KIL_NV); + /* This is a little weird, the cond code info is in the dest register */ + if (!Parse_CondCodeMask(parseState, &inst->DstReg)) + RETURN_ERROR; + } + + if (instMatch.inputs == INPUT_1V) { + if (!Parse_VectorSrc(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_2V) { + if (!Parse_VectorSrc(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_VectorSrc(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_3V) { + if (!Parse_VectorSrc(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_VectorSrc(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_VectorSrc(parseState, &inst->SrcReg[2])) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_1S) { + if (!Parse_ScalarSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_2S) { + if (!Parse_ScalarSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_ScalarSrcReg(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_CC) { + /* XXX to-do */ + } + else if (instMatch.inputs == INPUT_1V_T) { + if (!Parse_VectorSrc(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_TextureImageId(parseState, &inst->TexSrcUnit, + &inst->TexSrcBit)) + RETURN_ERROR; + } + else if (instMatch.inputs == INPUT_3V_T) { + if (!Parse_VectorSrc(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_VectorSrc(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_VectorSrc(parseState, &inst->SrcReg[2])) + RETURN_ERROR; + if (!Parse_String(parseState, ",")) + RETURN_ERROR1("Expected ,"); + if (!Parse_TextureImageId(parseState, &inst->TexSrcUnit, + &inst->TexSrcBit)) + RETURN_ERROR; + } + + /* end of statement semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR1("Expected ;"); + + parseState->numInst++; + + if (parseState->numInst >= MAX_NV_FRAGMENT_PROGRAM_INSTRUCTIONS) + RETURN_ERROR1("Program too long"); + } + } + return GL_TRUE; +} + + + +/** + * Parse/compile the 'str' returning the compiled 'program'. + * ctx->Program.ErrorPos will be -1 if successful. Otherwise, ErrorPos + * indicates the position of the error in 'str'. + */ +void +_mesa_parse_nv_fragment_program(GLcontext *ctx, GLenum dstTarget, + const GLubyte *str, GLsizei len, + struct fragment_program *program) +{ + struct parse_state parseState; + struct fp_instruction instBuffer[MAX_NV_FRAGMENT_PROGRAM_INSTRUCTIONS]; + struct fp_instruction *newInst; + GLenum target; + GLubyte *programString; + + /* Make a null-terminated copy of the program string */ + programString = (GLubyte *) MALLOC(len + 1); + if (!programString) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + return; + } + MEMCPY(programString, str, len); + programString[len] = 0; + + /* Get ready to parse */ + _mesa_bzero(&parseState, sizeof(struct parse_state)); + parseState.ctx = ctx; + parseState.start = programString; + parseState.program = program; + parseState.numInst = 0; + parseState.curLine = programString; + parseState.parameters = _mesa_new_parameter_list(); + + /* Reset error state */ + _mesa_set_program_error(ctx, -1, NULL); + + /* check the program header */ + if (_mesa_strncmp((const char *) programString, "!!FP1.0", 7) == 0) { + target = GL_FRAGMENT_PROGRAM_NV; + parseState.pos = programString + 7; + } + else if (_mesa_strncmp((const char *) programString, "!!FCP1.0", 8) == 0) { + /* fragment / register combiner program - not supported */ + _mesa_set_program_error(ctx, 0, "Invalid fragment program header"); + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV(bad header)"); + return; + } + else { + /* invalid header */ + _mesa_set_program_error(ctx, 0, "Invalid fragment program header"); + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV(bad header)"); + return; + } + + /* make sure target and header match */ + if (target != dstTarget) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glLoadProgramNV(target mismatch 0x%x != 0x%x)", + target, dstTarget); + return; + } + + if (Parse_InstructionSequence(&parseState, instBuffer)) { + GLuint u; + /* successful parse! */ + + if (parseState.outputsWritten == 0) { + /* must write at least one output! */ + _mesa_error(ctx, GL_INVALID_OPERATION, + "Invalid fragment program - no outputs written."); + return; + } + + /* copy the compiled instructions */ + assert(parseState.numInst <= MAX_NV_FRAGMENT_PROGRAM_INSTRUCTIONS); + newInst = (struct fp_instruction *) + MALLOC(parseState.numInst * sizeof(struct fp_instruction)); + if (!newInst) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + return; /* out of memory */ + } + MEMCPY(newInst, instBuffer, + parseState.numInst * sizeof(struct fp_instruction)); + + /* install the program */ + program->Base.Target = target; + if (program->Base.String) { + FREE(program->Base.String); + } + program->Base.String = programString; + program->Base.Format = GL_PROGRAM_FORMAT_ASCII_ARB; + if (program->Instructions) { + FREE(program->Instructions); + } + program->Instructions = newInst; + program->InputsRead = parseState.inputsRead; + program->OutputsWritten = parseState.outputsWritten; + for (u = 0; u < ctx->Const.MaxTextureImageUnits; u++) + program->TexturesUsed[u] = parseState.texturesUsed[u]; + + /* save program parameters */ + program->Parameters = parseState.parameters; + + /* allocate registers for declared program parameters */ +#if 00 + _mesa_assign_program_registers(&(program->SymbolTable)); +#endif + +#ifdef DEBUG_foo + _mesa_printf("--- glLoadProgramNV(%d) result ---\n", program->Base.Id); + _mesa_print_nv_fragment_program(program); + _mesa_printf("----------------------------------\n"); +#endif + } + else { + /* Error! */ + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV"); + /* NOTE: _mesa_set_program_error would have been called already */ + } +} + +#ifdef DEBUG +static void +PrintSrcReg(const struct fragment_program *program, + const struct fp_src_register *src) +{ + static const char comps[5] = "xyzw"; + + if (src->NegateAbs) { + _mesa_printf("-"); + } + if (src->Abs) { + _mesa_printf("|"); + } + if (src->NegateBase) { + _mesa_printf("-"); + } + if (src->File == PROGRAM_NAMED_PARAM) { + if (program->Parameters->Parameters[src->Index].Type == CONSTANT) { + printf("{%g, %g, %g, %g}", + program->Parameters->Parameters[src->Index].Values[0], + program->Parameters->Parameters[src->Index].Values[1], + program->Parameters->Parameters[src->Index].Values[2], + program->Parameters->Parameters[src->Index].Values[3]); + } + else { + ASSERT(program->Parameters->Parameters[src->Index].Type + == NAMED_PARAMETER); + printf("%s", program->Parameters->Parameters[src->Index].Name); + } + } + else if (src->File == PROGRAM_OUTPUT) { + _mesa_printf("o[%s]", OutputRegisters[src->Index]); + } + else if (src->File == PROGRAM_INPUT) { + _mesa_printf("f[%s]", InputRegisters[src->Index]); + } + else if (src->File == PROGRAM_LOCAL_PARAM) { + _mesa_printf("p[%d]", src->Index); + } + else if (src->File == PROGRAM_TEMPORARY) { + if (src->Index >= 32) + _mesa_printf("H%d", src->Index); + else + _mesa_printf("R%d", src->Index); + } + else if (src->File == PROGRAM_WRITE_ONLY) { + _mesa_printf("%cC", "HR"[src->Index]); + } + else { + _mesa_problem(NULL, "Invalid fragment register %d", src->Index); + return; + } + if (src->Swizzle[0] == src->Swizzle[1] && + src->Swizzle[0] == src->Swizzle[2] && + src->Swizzle[0] == src->Swizzle[3]) { + _mesa_printf(".%c", comps[src->Swizzle[0]]); + } + else if (src->Swizzle[0] != 0 || + src->Swizzle[1] != 1 || + src->Swizzle[2] != 2 || + src->Swizzle[3] != 3) { + _mesa_printf(".%c%c%c%c", + comps[src->Swizzle[0]], + comps[src->Swizzle[1]], + comps[src->Swizzle[2]], + comps[src->Swizzle[3]]); + } + if (src->Abs) { + _mesa_printf("|"); + } +} + +static void +PrintTextureSrc(const struct fp_instruction *inst) +{ + _mesa_printf("TEX%d, ", inst->TexSrcUnit); + switch (inst->TexSrcBit) { + case TEXTURE_1D_BIT: + _mesa_printf("1D"); + break; + case TEXTURE_2D_BIT: + _mesa_printf("2D"); + break; + case TEXTURE_3D_BIT: + _mesa_printf("3D"); + break; + case TEXTURE_RECT_BIT: + _mesa_printf("RECT"); + break; + case TEXTURE_CUBE_BIT: + _mesa_printf("CUBE"); + break; + default: + _mesa_problem(NULL, "Invalid textue target in PrintTextureSrc"); + } +} + +static void +PrintCondCode(const struct fp_dst_register *dst) +{ + static const char *comps = "xyzw"; + static const char *ccString[] = { + "??", "GT", "EQ", "LT", "UN", "GE", "LE", "NE", "TR", "FL", "??" + }; + + _mesa_printf("%s", ccString[dst->CondMask]); + if (dst->CondSwizzle[0] == dst->CondSwizzle[1] && + dst->CondSwizzle[0] == dst->CondSwizzle[2] && + dst->CondSwizzle[0] == dst->CondSwizzle[3]) { + _mesa_printf(".%c", comps[dst->CondSwizzle[0]]); + } + else if (dst->CondSwizzle[0] != 0 || + dst->CondSwizzle[1] != 1 || + dst->CondSwizzle[2] != 2 || + dst->CondSwizzle[3] != 3) { + _mesa_printf(".%c%c%c%c", + comps[dst->CondSwizzle[0]], + comps[dst->CondSwizzle[1]], + comps[dst->CondSwizzle[2]], + comps[dst->CondSwizzle[3]]); + } +} + + +static void +PrintDstReg(const struct fp_dst_register *dst) +{ + GLint w = dst->WriteMask[0] + dst->WriteMask[1] + + dst->WriteMask[2] + dst->WriteMask[3]; + + if (dst->File == PROGRAM_OUTPUT) { + _mesa_printf("o[%s]", OutputRegisters[dst->Index]); + } + else if (dst->File == PROGRAM_TEMPORARY) { + if (dst->Index >= 32) + _mesa_printf("H%d", dst->Index); + else + _mesa_printf("R%d", dst->Index); + } + else if (dst->File == PROGRAM_LOCAL_PARAM) { + _mesa_printf("p[%d]", dst->Index); + } + else if (dst->File == PROGRAM_WRITE_ONLY) { + _mesa_printf("%cC", "HR"[dst->Index]); + } + else { + _mesa_printf("???"); + } + + if (w != 0 && w != 4) { + _mesa_printf("."); + if (dst->WriteMask[0]) + _mesa_printf("x"); + if (dst->WriteMask[1]) + _mesa_printf("y"); + if (dst->WriteMask[2]) + _mesa_printf("z"); + if (dst->WriteMask[3]) + _mesa_printf("w"); + } + + if (dst->CondMask != COND_TR || + dst->CondSwizzle[0] != 0 || + dst->CondSwizzle[1] != 1 || + dst->CondSwizzle[2] != 2 || + dst->CondSwizzle[3] != 3) { + _mesa_printf(" ("); + PrintCondCode(dst); + _mesa_printf(")"); + } +} + + +/** + * Print (unparse) the given vertex program. Just for debugging. + */ +void +_mesa_print_nv_fragment_program(const struct fragment_program *program) +{ + const struct fp_instruction *inst; + + for (inst = program->Instructions; inst->Opcode != FP_OPCODE_END; inst++) { + int i; + for (i = 0; Instructions[i].name; i++) { + if (inst->Opcode == Instructions[i].opcode) { + /* print instruction name */ + _mesa_printf("%s", Instructions[i].name); + if (inst->Precision == FLOAT16) + _mesa_printf("H"); + else if (inst->Precision == FIXED12) + _mesa_printf("X"); + if (inst->UpdateCondRegister) + _mesa_printf("C"); + if (inst->Saturate) + _mesa_printf("_SAT"); + _mesa_printf(" "); + + if (Instructions[i].inputs == INPUT_CC) { + PrintCondCode(&inst->DstReg); + } + else if (Instructions[i].outputs == OUTPUT_V || + Instructions[i].outputs == OUTPUT_S) { + /* print dest register */ + PrintDstReg(&inst->DstReg); + _mesa_printf(", "); + } + + /* print source register(s) */ + if (Instructions[i].inputs == INPUT_1V || + Instructions[i].inputs == INPUT_1S) { + PrintSrcReg(program, &inst->SrcReg[0]); + } + else if (Instructions[i].inputs == INPUT_2V || + Instructions[i].inputs == INPUT_2S) { + PrintSrcReg(program, &inst->SrcReg[0]); + _mesa_printf(", "); + PrintSrcReg(program, &inst->SrcReg[1]); + } + else if (Instructions[i].inputs == INPUT_3V) { + PrintSrcReg(program, &inst->SrcReg[0]); + _mesa_printf(", "); + PrintSrcReg(program, &inst->SrcReg[1]); + _mesa_printf(", "); + PrintSrcReg(program, &inst->SrcReg[2]); + } + else if (Instructions[i].inputs == INPUT_1V_T) { + PrintSrcReg(program, &inst->SrcReg[0]); + _mesa_printf(", "); + PrintTextureSrc(inst); + } + else if (Instructions[i].inputs == INPUT_3V_T) { + PrintSrcReg(program, &inst->SrcReg[0]); + _mesa_printf(", "); + PrintSrcReg(program, &inst->SrcReg[1]); + _mesa_printf(", "); + PrintSrcReg(program, &inst->SrcReg[2]); + _mesa_printf(", "); + PrintTextureSrc(inst); + } + _mesa_printf(";\n"); + break; + } + } + if (!Instructions[i].name) { + _mesa_printf("Invalid opcode %d\n", inst->Opcode); + } + } + _mesa_printf("END\n"); +} +#endif + +const char * +_mesa_nv_fragment_input_register_name(GLuint i) +{ + ASSERT(i < MAX_NV_FRAGMENT_PROGRAM_INPUTS); + return InputRegisters[i]; +} + + +const char * +_mesa_nv_fragment_output_register_name(GLuint i) +{ + ASSERT(i < MAX_NV_FRAGMENT_PROGRAM_OUTPUTS); + return OutputRegisters[i]; +} diff --git a/src/mesa/shader/nvfragparse.h b/src/mesa/shader/nvfragparse.h new file mode 100644 index 0000000..849a7fb --- /dev/null +++ b/src/mesa/shader/nvfragparse.h @@ -0,0 +1,52 @@ + +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2002 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: + * Brian Paul + */ + + +#ifndef NVFRAGPARSE_H +#define NVFRAGPARSE_H + + +extern void +_mesa_parse_nv_fragment_program(GLcontext *ctx, GLenum target, + const GLubyte *str, GLsizei len, + struct fragment_program *program); + + +extern void +_mesa_print_nv_fragment_program(const struct fragment_program *program); + + +extern const char * +_mesa_nv_fragment_input_register_name(GLuint i); + + +extern const char * +_mesa_nv_fragment_output_register_name(GLuint i); + + +#endif diff --git a/src/mesa/shader/nvfragprog.h b/src/mesa/shader/nvfragprog.h new file mode 100644 index 0000000..8f02f22 --- /dev/null +++ b/src/mesa/shader/nvfragprog.h @@ -0,0 +1,164 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +/* Private fragment program types and constants only used by files + * related to fragment programs. + * + * XXX TO-DO: Rename this file "fragprog.h" since it's not NV-specific. + */ + + +#ifndef NVFRAGPROG_H +#define NVFRAGPROG_H + +#include "config.h" + + +/* output registers */ +#define FRAG_OUTPUT_COLR 0 +#define FRAG_OUTPUT_COLH 1 +#define FRAG_OUTPUT_DEPR 2 + + +/* condition codes */ +#define COND_GT 1 /* greater than zero */ +#define COND_EQ 2 /* equal to zero */ +#define COND_LT 3 /* less than zero */ +#define COND_UN 4 /* unordered (NaN) */ +#define COND_GE 5 /* greater then or equal to zero */ +#define COND_LE 6 /* less then or equal to zero */ +#define COND_NE 7 /* not equal to zero */ +#define COND_TR 8 /* always true */ +#define COND_FL 9 /* always false */ + + +/* instruction precision */ +#define FLOAT32 0x1 +#define FLOAT16 0x2 +#define FIXED12 0x4 + + +/* Fragment program instruction opcodes */ +enum fp_opcode { + FP_OPCODE_INVALID = -1, /* Force signed enum */ + FP_OPCODE_ABS = 1000, /* ARB_f_p only */ + FP_OPCODE_ADD, + FP_OPCODE_CMP, /* ARB_f_p only */ + FP_OPCODE_COS, + FP_OPCODE_DDX, /* NV_f_p only */ + FP_OPCODE_DDY, /* NV_f_p only */ + FP_OPCODE_DP3, + FP_OPCODE_DP4, + FP_OPCODE_DPH, /* ARB_f_p only */ + FP_OPCODE_DST, + FP_OPCODE_EX2, + FP_OPCODE_FLR, + FP_OPCODE_FRC, + FP_OPCODE_KIL_NV, /* NV_f_p only */ + FP_OPCODE_KIL, /* ARB_f_p only */ + FP_OPCODE_LG2, + FP_OPCODE_LIT, + FP_OPCODE_LRP, + FP_OPCODE_MAD, + FP_OPCODE_MAX, + FP_OPCODE_MIN, + FP_OPCODE_MOV, + FP_OPCODE_MUL, + FP_OPCODE_PK2H, /* NV_f_p only */ + FP_OPCODE_PK2US, /* NV_f_p only */ + FP_OPCODE_PK4B, /* NV_f_p only */ + FP_OPCODE_PK4UB, /* NV_f_p only */ + FP_OPCODE_POW, + FP_OPCODE_RCP, + FP_OPCODE_RFL, /* NV_f_p only */ + FP_OPCODE_RSQ, + FP_OPCODE_SCS, /* ARB_f_p only */ + FP_OPCODE_SEQ, /* NV_f_p only */ + FP_OPCODE_SFL, /* NV_f_p only */ + FP_OPCODE_SGE, /* NV_f_p only */ + FP_OPCODE_SGT, /* NV_f_p only */ + FP_OPCODE_SIN, + FP_OPCODE_SLE, /* NV_f_p only */ + FP_OPCODE_SLT, + FP_OPCODE_SNE, /* NV_f_p only */ + FP_OPCODE_STR, /* NV_f_p only */ + FP_OPCODE_SUB, + FP_OPCODE_SWZ, /* ARB_f_p only */ + FP_OPCODE_TEX, + FP_OPCODE_TXB, /* ARB_f_p only */ + FP_OPCODE_TXD, /* NV_f_p only */ + FP_OPCODE_TXP, /* ARB_f_p only */ + FP_OPCODE_TXP_NV, /* NV_f_p only */ + FP_OPCODE_UP2H, /* NV_f_p only */ + FP_OPCODE_UP2US, /* NV_f_p only */ + FP_OPCODE_UP4B, /* NV_f_p only */ + FP_OPCODE_UP4UB, /* NV_f_p only */ + FP_OPCODE_X2D, /* NV_f_p only - 2d mat mul */ + FP_OPCODE_XPD, /* ARB_f_p only - cross product */ + FP_OPCODE_END /* private opcode */ +}; + + +/* Instruction source register */ +struct fp_src_register +{ + enum register_file File; + GLint Index; + GLuint Swizzle[4]; + GLboolean NegateBase; /* negate before absolute value? */ + GLboolean Abs; /* take absolute value? */ + GLboolean NegateAbs; /* negate after absolute value? */ +}; + + +/* Instruction destination register */ +struct fp_dst_register +{ + enum register_file File; + GLint Index; + GLboolean WriteMask[4]; + GLuint CondMask; + GLuint CondSwizzle[4]; +}; + + +/* Fragment program instruction */ +struct fp_instruction +{ + enum fp_opcode Opcode; + struct fp_src_register SrcReg[3]; + struct fp_dst_register DstReg; + GLboolean Saturate; + GLboolean UpdateCondRegister; + GLubyte Precision; /* FLOAT32, FLOAT16 or FIXED12 */ + GLubyte TexSrcUnit; /* texture unit for TEX, TXD, TXP instructions */ + GLubyte TexSrcBit; /* TEXTURE_1D,2D,3D,CUBE,RECT_BIT source target */ +#if FEATURE_MESA_program_debug + GLint StringPos; +#endif +}; + + +#endif diff --git a/src/mesa/shader/nvprogram.c b/src/mesa/shader/nvprogram.c new file mode 100644 index 0000000..4db78a8 --- /dev/null +++ b/src/mesa/shader/nvprogram.c @@ -0,0 +1,869 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file nvprogram.c + * NVIDIA vertex/fragment program state management functions. + * \author Brian Paul + */ + +/* + * Regarding GL_NV_fragment/vertex_program, GL_NV_vertex_program1_1, etc: + * + * Portions of this software may use or implement intellectual + * property owned and licensed by NVIDIA Corporation. NVIDIA disclaims + * any and all warranties with respect to such intellectual property, + * including any use thereof or modifications thereto. + */ + +#include "glheader.h" +#include "context.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvfragparse.h" +#include "nvfragprog.h" +#include "nvvertexec.h" +#include "nvvertparse.h" +#include "nvvertprog.h" +#include "nvprogram.h" +#include "program.h" + + + +/** + * Execute a vertex state program. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ExecuteProgramNV(GLenum target, GLuint id, const GLfloat *params) +{ + struct vertex_program *vprog; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target != GL_VERTEX_STATE_PROGRAM_NV) { + _mesa_error(ctx, GL_INVALID_ENUM, "glExecuteProgramNV"); + return; + } + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + vprog = (struct vertex_program *) + _mesa_HashLookup(ctx->Shared->Programs, id); + + if (!vprog || vprog->Base.Target != GL_VERTEX_STATE_PROGRAM_NV) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glExecuteProgramNV"); + return; + } + + _mesa_init_vp_per_vertex_registers(ctx); + _mesa_init_vp_per_primitive_registers(ctx); + COPY_4V(ctx->VertexProgram.Inputs[VERT_ATTRIB_POS], params); + _mesa_exec_vertex_program(ctx, vprog); +} + + +/** + * Determine if a set of programs is resident in hardware. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +GLboolean GLAPIENTRY _mesa_AreProgramsResidentNV(GLsizei n, const GLuint *ids, + GLboolean *residences) +{ + GLint i, j; + GLboolean allResident = GL_TRUE; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE); + + if (n < 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glAreProgramsResidentNV(n)"); + return GL_FALSE; + } + + for (i = 0; i < n; i++) { + const struct program *prog; + if (ids[i] == 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glAreProgramsResidentNV"); + return GL_FALSE; + } + prog = (const struct program *) + _mesa_HashLookup(ctx->Shared->Programs, ids[i]); + if (!prog) { + _mesa_error(ctx, GL_INVALID_VALUE, "glAreProgramsResidentNV"); + return GL_FALSE; + } + if (prog->Resident) { + if (!allResident) + residences[i] = GL_TRUE; + } + else { + if (allResident) { + allResident = GL_FALSE; + for (j = 0; j < i; j++) + residences[j] = GL_TRUE; + } + residences[i] = GL_FALSE; + } + } + + return allResident; +} + + +/** + * Request that a set of programs be resident in hardware. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_RequestResidentProgramsNV(GLsizei n, const GLuint *ids) +{ + GLint i; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (n < 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glRequestResidentProgramsNV(n)"); + return; + } + + /* just error checking for now */ + for (i = 0; i < n; i++) { + struct program *prog; + + if (ids[i] == 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glRequestResidentProgramsNV(id)"); + return; + } + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, ids[i]); + if (!prog) { + _mesa_error(ctx, GL_INVALID_VALUE, "glRequestResidentProgramsNV(id)"); + return; + } + + /* XXX this is really a hardware thing we should hook out */ + prog->Resident = GL_TRUE; + } +} + + +/** + * Get a program parameter register. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetProgramParameterfvNV(GLenum target, GLuint index, + GLenum pname, GLfloat *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV) { + if (pname == GL_PROGRAM_PARAMETER_NV) { + if (index < MAX_NV_VERTEX_PROGRAM_PARAMS) { + COPY_4V(params, ctx->VertexProgram.Parameters[index]); + } + else { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramParameterfvNV(index)"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramParameterfvNV(pname)"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramParameterfvNV(target)"); + return; + } +} + + +/** + * Get a program parameter register. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetProgramParameterdvNV(GLenum target, GLuint index, + GLenum pname, GLdouble *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV) { + if (pname == GL_PROGRAM_PARAMETER_NV) { + if (index < MAX_NV_VERTEX_PROGRAM_PARAMS) { + COPY_4V(params, ctx->VertexProgram.Parameters[index]); + } + else { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramParameterdvNV(index)"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramParameterdvNV(pname)"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramParameterdvNV(target)"); + return; + } +} + + +/** + * Get a program attribute. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetProgramivNV(GLuint id, GLenum pname, GLint *params) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + if (!prog) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramivNV"); + return; + } + + switch (pname) { + case GL_PROGRAM_TARGET_NV: + *params = prog->Target; + return; + case GL_PROGRAM_LENGTH_NV: + *params = prog->String ? _mesa_strlen((char *) prog->String) : 0; + return; + case GL_PROGRAM_RESIDENT_NV: + *params = prog->Resident; + return; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramivNV(pname)"); + return; + } +} + + +/** + * Get the program source code. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetProgramStringNV(GLuint id, GLenum pname, GLubyte *program) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (pname != GL_PROGRAM_STRING_NV) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramStringNV(pname)"); + return; + } + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + if (!prog) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramStringNV"); + return; + } + + if (prog->String) { + MEMCPY(program, prog->String, _mesa_strlen((char *) prog->String)); + } + else { + program[0] = 0; + } +} + + +/** + * Get matrix tracking information. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetTrackMatrixivNV(GLenum target, GLuint address, + GLenum pname, GLint *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV + && ctx->Extensions.NV_vertex_program) { + GLuint i; + + if ((address & 0x3) || address >= MAX_NV_VERTEX_PROGRAM_PARAMS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetTrackMatrixivNV(address)"); + return; + } + + i = address / 4; + + switch (pname) { + case GL_TRACK_MATRIX_NV: + params[0] = (GLint) ctx->VertexProgram.TrackMatrix[i]; + return; + case GL_TRACK_MATRIX_TRANSFORM_NV: + params[0] = (GLint) ctx->VertexProgram.TrackMatrixTransform[i]; + return; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetTrackMatrixivNV"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetTrackMatrixivNV"); + return; + } +} + + +/** + * Get a vertex (or vertex array) attribute. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetVertexAttribdvNV(GLuint index, GLenum pname, GLdouble *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index == 0 || index >= MAX_NV_VERTEX_PROGRAM_INPUTS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribdvNV(index)"); + return; + } + + switch (pname) { + case GL_ATTRIB_ARRAY_SIZE_NV: + params[0] = ctx->Array.VertexAttrib[index].Size; + break; + case GL_ATTRIB_ARRAY_STRIDE_NV: + params[0] = ctx->Array.VertexAttrib[index].Stride; + break; + case GL_ATTRIB_ARRAY_TYPE_NV: + params[0] = ctx->Array.VertexAttrib[index].Type; + break; + case GL_CURRENT_ATTRIB_NV: + FLUSH_CURRENT(ctx, 0); + COPY_4V(params, ctx->Current.Attrib[index]); + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribdvNV"); + return; + } +} + +/** + * Get a vertex (or vertex array) attribute. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetVertexAttribfvNV(GLuint index, GLenum pname, GLfloat *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index == 0 || index >= MAX_NV_VERTEX_PROGRAM_INPUTS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribdvNV(index)"); + return; + } + + switch (pname) { + case GL_ATTRIB_ARRAY_SIZE_NV: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Size; + break; + case GL_ATTRIB_ARRAY_STRIDE_NV: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Stride; + break; + case GL_ATTRIB_ARRAY_TYPE_NV: + params[0] = (GLfloat) ctx->Array.VertexAttrib[index].Type; + break; + case GL_CURRENT_ATTRIB_NV: + FLUSH_CURRENT(ctx, 0); + COPY_4V(params, ctx->Current.Attrib[index]); + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribdvNV"); + return; + } +} + +/** + * Get a vertex (or vertex array) attribute. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetVertexAttribivNV(GLuint index, GLenum pname, GLint *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index == 0 || index >= MAX_NV_VERTEX_PROGRAM_INPUTS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribdvNV(index)"); + return; + } + + switch (pname) { + case GL_ATTRIB_ARRAY_SIZE_NV: + params[0] = ctx->Array.VertexAttrib[index].Size; + break; + case GL_ATTRIB_ARRAY_STRIDE_NV: + params[0] = ctx->Array.VertexAttrib[index].Stride; + break; + case GL_ATTRIB_ARRAY_TYPE_NV: + params[0] = ctx->Array.VertexAttrib[index].Type; + break; + case GL_CURRENT_ATTRIB_NV: + FLUSH_CURRENT(ctx, 0); + params[0] = (GLint) ctx->Current.Attrib[index][0]; + params[1] = (GLint) ctx->Current.Attrib[index][1]; + params[2] = (GLint) ctx->Current.Attrib[index][2]; + params[3] = (GLint) ctx->Current.Attrib[index][3]; + break; + case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB: + if (!ctx->Extensions.ARB_vertex_buffer_object) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribdvNV"); + return; + } + params[0] = ctx->Array.VertexAttrib[index].BufferObj->Name; + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribdvNV"); + return; + } +} + + +/** + * Get a vertex array attribute pointer. + * \note Not compiled into display lists. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_GetVertexAttribPointervNV(GLuint index, GLenum pname, GLvoid **pointer) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (index >= MAX_NV_VERTEX_PROGRAM_INPUTS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetVertexAttribPointerNV(index)"); + return; + } + + if (pname != GL_ATTRIB_ARRAY_POINTER_NV) { + _mesa_error(ctx, GL_INVALID_ENUM, "glGetVertexAttribPointerNV(pname)"); + return; + } + + *pointer = (GLvoid *) ctx->Array.VertexAttrib[index].Ptr;; +} + + + +/** + * Load/parse/compile a program. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_LoadProgramNV(GLenum target, GLuint id, GLsizei len, + const GLubyte *program) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (id == 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glLoadProgramNV(id)"); + return; + } + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + + if (prog && prog->Target != 0 && prog->Target != target) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV(target)"); + return; + } + + if ((target == GL_VERTEX_PROGRAM_NV || + target == GL_VERTEX_STATE_PROGRAM_NV) + && ctx->Extensions.NV_vertex_program) { + struct vertex_program *vprog = (struct vertex_program *) prog; + if (!vprog || prog == &_mesa_DummyProgram) { + vprog = (struct vertex_program *) + ctx->Driver.NewProgram(ctx, target, id); + if (!vprog) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + return; + } + _mesa_HashInsert(ctx->Shared->Programs, id, vprog); + } + _mesa_parse_nv_vertex_program(ctx, target, program, len, vprog); + } + else if (target == GL_FRAGMENT_PROGRAM_NV + && ctx->Extensions.NV_fragment_program) { + struct fragment_program *fprog = (struct fragment_program *) prog; + if (!fprog || prog == &_mesa_DummyProgram) { + fprog = (struct fragment_program *) + ctx->Driver.NewProgram(ctx, target, id); + if (!fprog) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + return; + } + _mesa_HashInsert(ctx->Shared->Programs, id, fprog); + } + _mesa_parse_nv_fragment_program(ctx, target, program, len, fprog); + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glLoadProgramNV(target)"); + } +} + + + +/** + * Set a program parameter register. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameter4dNV(GLenum target, GLuint index, + GLdouble x, GLdouble y, GLdouble z, GLdouble w) +{ + _mesa_ProgramParameter4fNV(target, index, + (GLfloat)x, (GLfloat)y, (GLfloat)z, (GLfloat)w); +} + + +/** + * Set a program parameter register. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameter4dvNV(GLenum target, GLuint index, + const GLdouble *params) +{ + _mesa_ProgramParameter4fNV(target, index, + (GLfloat)params[0], (GLfloat)params[1], + (GLfloat)params[2], (GLfloat)params[3]); +} + + +/** + * Set a program parameter register. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameter4fNV(GLenum target, GLuint index, + GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV && ctx->Extensions.NV_vertex_program) { + if (index < MAX_NV_VERTEX_PROGRAM_PARAMS) { + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + ASSIGN_4V(ctx->VertexProgram.Parameters[index], x, y, z, w); + } + else { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramParameterNV(index)"); + return; + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameterNV"); + return; + } +} + + +/** + * Set a program parameter register. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameter4fvNV(GLenum target, GLuint index, + const GLfloat *params) +{ + _mesa_ProgramParameter4fNV(target, index, + params[0], params[1], params[2], params[3]); +} + + + +/** + * Set a sequence of program parameter registers. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameters4dvNV(GLenum target, GLuint index, + GLuint num, const GLdouble *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV && ctx->Extensions.NV_vertex_program) { + GLuint i; + if (index + num > MAX_NV_VERTEX_PROGRAM_PARAMS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramParameters4dvNV"); + return; + } + for (i = 0; i < num; i++) { + ctx->VertexProgram.Parameters[index + i][0] = (GLfloat) params[0]; + ctx->VertexProgram.Parameters[index + i][1] = (GLfloat) params[1]; + ctx->VertexProgram.Parameters[index + i][2] = (GLfloat) params[2]; + ctx->VertexProgram.Parameters[index + i][3] = (GLfloat) params[3]; + params += 4; + }; + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameters4dvNV"); + return; + } +} + + +/** + * Set a sequence of program parameter registers. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_ProgramParameters4fvNV(GLenum target, GLuint index, + GLuint num, const GLfloat *params) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (target == GL_VERTEX_PROGRAM_NV && ctx->Extensions.NV_vertex_program) { + GLuint i; + if (index + num > MAX_NV_VERTEX_PROGRAM_PARAMS) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramParameters4fvNV"); + return; + } + for (i = 0; i < num; i++) { + COPY_4V(ctx->VertexProgram.Parameters[index + i], params); + params += 4; + }; + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameters4fvNV"); + return; + } +} + + + +/** + * Setup tracking of matrices into program parameter registers. + * \note Called from the GL API dispatcher. + */ +void GLAPIENTRY +_mesa_TrackMatrixNV(GLenum target, GLuint address, + GLenum matrix, GLenum transform) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if (target == GL_VERTEX_PROGRAM_NV && ctx->Extensions.NV_vertex_program) { + if (address & 0x3) { + /* addr must be multiple of four */ + _mesa_error(ctx, GL_INVALID_VALUE, "glTrackMatrixNV(address)"); + return; + } + + switch (matrix) { + case GL_NONE: + case GL_MODELVIEW: + case GL_PROJECTION: + case GL_TEXTURE: + case GL_COLOR: + case GL_MODELVIEW_PROJECTION_NV: + case GL_MATRIX0_NV: + case GL_MATRIX1_NV: + case GL_MATRIX2_NV: + case GL_MATRIX3_NV: + case GL_MATRIX4_NV: + case GL_MATRIX5_NV: + case GL_MATRIX6_NV: + case GL_MATRIX7_NV: + /* OK, fallthrough */ + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glTrackMatrixNV(matrix)"); + return; + } + + switch (transform) { + case GL_IDENTITY_NV: + case GL_INVERSE_NV: + case GL_TRANSPOSE_NV: + case GL_INVERSE_TRANSPOSE_NV: + /* OK, fallthrough */ + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glTrackMatrixNV(transform)"); + return; + } + + ctx->VertexProgram.TrackMatrix[address / 4] = matrix; + ctx->VertexProgram.TrackMatrixTransform[address / 4] = transform; + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glTrackMatrixNV(target)"); + return; + } +} + + +void GLAPIENTRY +_mesa_ProgramNamedParameter4fNV(GLuint id, GLsizei len, const GLubyte *name, + GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + struct program *prog; + struct fragment_program *fragProg; + GLfloat *v; + + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + if (!prog || prog->Target != GL_FRAGMENT_PROGRAM_NV) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glProgramNamedParameterNV"); + return; + } + + if (len <= 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramNamedParameterNV(len)"); + return; + } + + fragProg = (struct fragment_program *) prog; + v = _mesa_lookup_parameter_value(fragProg->Parameters, len, (char *) name); + if (v) { + v[0] = x; + v[1] = y; + v[2] = z; + v[3] = w; + return; + } + + _mesa_error(ctx, GL_INVALID_VALUE, "glProgramNamedParameterNV(name)"); +} + + +void GLAPIENTRY +_mesa_ProgramNamedParameter4fvNV(GLuint id, GLsizei len, const GLubyte *name, + const float v[]) +{ + _mesa_ProgramNamedParameter4fNV(id, len, name, v[0], v[1], v[2], v[3]); +} + + +void GLAPIENTRY +_mesa_ProgramNamedParameter4dNV(GLuint id, GLsizei len, const GLubyte *name, + GLdouble x, GLdouble y, GLdouble z, GLdouble w) +{ + _mesa_ProgramNamedParameter4fNV(id, len, name, (GLfloat)x, (GLfloat)y, + (GLfloat)z, (GLfloat)w); +} + + +void GLAPIENTRY +_mesa_ProgramNamedParameter4dvNV(GLuint id, GLsizei len, const GLubyte *name, + const double v[]) +{ + _mesa_ProgramNamedParameter4fNV(id, len, name, + (GLfloat)v[0], (GLfloat)v[1], + (GLfloat)v[2], (GLfloat)v[3]); +} + + +void GLAPIENTRY +_mesa_GetProgramNamedParameterfvNV(GLuint id, GLsizei len, const GLubyte *name, + GLfloat *params) +{ + struct program *prog; + struct fragment_program *fragProg; + const GLfloat *v; + + GET_CURRENT_CONTEXT(ctx); + + if (!ctx->_CurrentProgram) + ASSERT_OUTSIDE_BEGIN_END(ctx); + + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + if (!prog || prog->Target != GL_FRAGMENT_PROGRAM_NV) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramNamedParameterNV"); + return; + } + + if (len <= 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramNamedParameterNV"); + return; + } + + fragProg = (struct fragment_program *) prog; + v = _mesa_lookup_parameter_value(fragProg->Parameters, len, (char *) name); + if (v) { + params[0] = v[0]; + params[1] = v[1]; + params[2] = v[2]; + params[3] = v[3]; + return; + } + + _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramNamedParameterNV"); +} + + +void GLAPIENTRY +_mesa_GetProgramNamedParameterdvNV(GLuint id, GLsizei len, const GLubyte *name, + GLdouble *params) +{ + GLfloat floatParams[4]; + _mesa_GetProgramNamedParameterfvNV(id, len, name, floatParams); + COPY_4V(params, floatParams); +} diff --git a/src/mesa/shader/nvprogram.h b/src/mesa/shader/nvprogram.h new file mode 100644 index 0000000..dcea772 --- /dev/null +++ b/src/mesa/shader/nvprogram.h @@ -0,0 +1,119 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: + * Brian Paul + */ + + +#ifndef NVPROGRAM_H +#define NVPROGRAM_H + + +extern void GLAPIENTRY +_mesa_ExecuteProgramNV(GLenum target, GLuint id, const GLfloat *params); + +extern GLboolean GLAPIENTRY +_mesa_AreProgramsResidentNV(GLsizei n, const GLuint *ids, GLboolean *residences); + +extern void GLAPIENTRY +_mesa_RequestResidentProgramsNV(GLsizei n, const GLuint *ids); + +extern void GLAPIENTRY +_mesa_GetProgramParameterfvNV(GLenum target, GLuint index, GLenum pname, GLfloat *params); + +extern void GLAPIENTRY +_mesa_GetProgramParameterdvNV(GLenum target, GLuint index, GLenum pname, GLdouble *params); + +extern void GLAPIENTRY +_mesa_GetProgramivNV(GLuint id, GLenum pname, GLint *params); + +extern void GLAPIENTRY +_mesa_GetProgramStringNV(GLuint id, GLenum pname, GLubyte *program); + +extern void GLAPIENTRY +_mesa_GetTrackMatrixivNV(GLenum target, GLuint address, GLenum pname, GLint *params); + +extern void GLAPIENTRY +_mesa_GetVertexAttribdvNV(GLuint index, GLenum pname, GLdouble *params); + +extern void GLAPIENTRY +_mesa_GetVertexAttribfvNV(GLuint index, GLenum pname, GLfloat *params); + +extern void GLAPIENTRY +_mesa_GetVertexAttribivNV(GLuint index, GLenum pname, GLint *params); + +extern void GLAPIENTRY +_mesa_GetVertexAttribPointervNV(GLuint index, GLenum pname, GLvoid **pointer); + +extern void GLAPIENTRY +_mesa_LoadProgramNV(GLenum target, GLuint id, GLsizei len, const GLubyte *program); + +extern void GLAPIENTRY +_mesa_ProgramParameter4dNV(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); + +extern void GLAPIENTRY +_mesa_ProgramParameter4dvNV(GLenum target, GLuint index, const GLdouble *params); + +extern void GLAPIENTRY +_mesa_ProgramParameter4fNV(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + +extern void GLAPIENTRY +_mesa_ProgramParameter4fvNV(GLenum target, GLuint index, const GLfloat *params); + +extern void GLAPIENTRY +_mesa_ProgramParameters4dvNV(GLenum target, GLuint index, GLuint num, const GLdouble *params); + +extern void GLAPIENTRY +_mesa_ProgramParameters4fvNV(GLenum target, GLuint index, GLuint num, const GLfloat *params); + +extern void GLAPIENTRY +_mesa_TrackMatrixNV(GLenum target, GLuint address, GLenum matrix, GLenum transform); + + +extern void GLAPIENTRY +_mesa_ProgramNamedParameter4fNV(GLuint id, GLsizei len, const GLubyte *name, + GLfloat x, GLfloat y, GLfloat z, GLfloat w); + +extern void GLAPIENTRY +_mesa_ProgramNamedParameter4fvNV(GLuint id, GLsizei len, const GLubyte *name, + const float v[]); + +extern void GLAPIENTRY +_mesa_ProgramNamedParameter4dNV(GLuint id, GLsizei len, const GLubyte *name, + GLdouble x, GLdouble y, GLdouble z, GLdouble w); + +extern void GLAPIENTRY +_mesa_ProgramNamedParameter4dvNV(GLuint id, GLsizei len, const GLubyte *name, + const double v[]); + +extern void GLAPIENTRY +_mesa_GetProgramNamedParameterfvNV(GLuint id, GLsizei len, const GLubyte *name, + GLfloat *params); + +extern void GLAPIENTRY +_mesa_GetProgramNamedParameterdvNV(GLuint id, GLsizei len, const GLubyte *name, + GLdouble *params); + + +#endif diff --git a/src/mesa/shader/nvvertexec.c b/src/mesa/shader/nvvertexec.c new file mode 100644 index 0000000..503592d --- /dev/null +++ b/src/mesa/shader/nvvertexec.c @@ -0,0 +1,837 @@ +/* + * Mesa 3-D graphics library + * Version: 6.2.2 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file nvvertexec.c + * Code to execute vertex programs. + * \author Brian Paul + */ + +#include "glheader.h" +#include "context.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvvertexec.h" +#include "nvvertprog.h" +#include "program.h" +#include "math/m_matrix.h" + + +static const GLfloat ZeroVec[4] = { 0.0F, 0.0F, 0.0F, 0.0F }; + + +/** + * Load/initialize the vertex program registers which need to be set + * per-vertex. + */ +void +_mesa_init_vp_per_vertex_registers(GLcontext *ctx) +{ + /* Input registers get initialized from the current vertex attribs */ + MEMCPY(ctx->VertexProgram.Inputs, ctx->Current.Attrib, + VERT_ATTRIB_MAX * 4 * sizeof(GLfloat)); + + if (ctx->VertexProgram.Current->IsNVProgram) { + GLuint i; + /* Output/result regs are initialized to [0,0,0,1] */ + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_OUTPUTS; i++) { + ASSIGN_4V(ctx->VertexProgram.Outputs[i], 0.0F, 0.0F, 0.0F, 1.0F); + } + /* Temp regs are initialized to [0,0,0,0] */ + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_TEMPS; i++) { + ASSIGN_4V(ctx->VertexProgram.Temporaries[i], 0.0F, 0.0F, 0.0F, 0.0F); + } + ASSIGN_4V(ctx->VertexProgram.AddressReg, 0, 0, 0, 0); + } +} + + + +/** + * Copy the 16 elements of a matrix into four consecutive program + * registers starting at 'pos'. + */ +static void +load_matrix(GLfloat registers[][4], GLuint pos, const GLfloat mat[16]) +{ + GLuint i; + for (i = 0; i < 4; i++) { + registers[pos + i][0] = mat[0 + i]; + registers[pos + i][1] = mat[4 + i]; + registers[pos + i][2] = mat[8 + i]; + registers[pos + i][3] = mat[12 + i]; + } +} + + +/** + * As above, but transpose the matrix. + */ +static void +load_transpose_matrix(GLfloat registers[][4], GLuint pos, + const GLfloat mat[16]) +{ + MEMCPY(registers[pos], mat, 16 * sizeof(GLfloat)); +} + + +/** + * Load program parameter registers with tracked matrices (if NV program) + * or GL state values (if ARB program). + * This needs to be done per glBegin/glEnd, not per-vertex. + */ +void +_mesa_init_vp_per_primitive_registers(GLcontext *ctx) +{ + if (ctx->VertexProgram.Current->IsNVProgram) { + GLuint i; + + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_PARAMS / 4; i++) { + /* point 'mat' at source matrix */ + GLmatrix *mat; + if (ctx->VertexProgram.TrackMatrix[i] == GL_MODELVIEW) { + mat = ctx->ModelviewMatrixStack.Top; + } + else if (ctx->VertexProgram.TrackMatrix[i] == GL_PROJECTION) { + mat = ctx->ProjectionMatrixStack.Top; + } + else if (ctx->VertexProgram.TrackMatrix[i] == GL_TEXTURE) { + mat = ctx->TextureMatrixStack[ctx->Texture.CurrentUnit].Top; + } + else if (ctx->VertexProgram.TrackMatrix[i] == GL_COLOR) { + mat = ctx->ColorMatrixStack.Top; + } + else if (ctx->VertexProgram.TrackMatrix[i]==GL_MODELVIEW_PROJECTION_NV) { + /* XXX verify the combined matrix is up to date */ + mat = &ctx->_ModelProjectMatrix; + } + else if (ctx->VertexProgram.TrackMatrix[i] >= GL_MATRIX0_NV && + ctx->VertexProgram.TrackMatrix[i] <= GL_MATRIX7_NV) { + GLuint n = ctx->VertexProgram.TrackMatrix[i] - GL_MATRIX0_NV; + ASSERT(n < MAX_PROGRAM_MATRICES); + mat = ctx->ProgramMatrixStack[n].Top; + } + else { + /* no matrix is tracked, but we leave the register values as-is */ + assert(ctx->VertexProgram.TrackMatrix[i] == GL_NONE); + continue; + } + + /* load the matrix */ + if (ctx->VertexProgram.TrackMatrixTransform[i] == GL_IDENTITY_NV) { + load_matrix(ctx->VertexProgram.Parameters, i*4, mat->m); + } + else if (ctx->VertexProgram.TrackMatrixTransform[i] == GL_INVERSE_NV) { + _math_matrix_analyse(mat); /* update the inverse */ + assert((mat->flags & MAT_DIRTY_INVERSE) == 0); + load_matrix(ctx->VertexProgram.Parameters, i*4, mat->inv); + } + else if (ctx->VertexProgram.TrackMatrixTransform[i] == GL_TRANSPOSE_NV) { + load_transpose_matrix(ctx->VertexProgram.Parameters, i*4, mat->m); + } + else { + assert(ctx->VertexProgram.TrackMatrixTransform[i] + == GL_INVERSE_TRANSPOSE_NV); + _math_matrix_analyse(mat); /* update the inverse */ + assert((mat->flags & MAT_DIRTY_INVERSE) == 0); + load_transpose_matrix(ctx->VertexProgram.Parameters, i*4, mat->inv); + } + } + } + else { + /* Using and ARB vertex program */ + if (ctx->VertexProgram.Current->Parameters) { + /* Grab the state GL state and put into registers */ + _mesa_load_state_parameters(ctx, + ctx->VertexProgram.Current->Parameters); + } + } +} + + + +/** + * For debugging. Dump the current vertex program machine registers. + */ +void +_mesa_dump_vp_state( const struct vertex_program_state *state ) +{ + int i; + _mesa_printf("VertexIn:\n"); + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_INPUTS; i++) { + _mesa_printf("%d: %f %f %f %f ", i, + state->Inputs[i][0], + state->Inputs[i][1], + state->Inputs[i][2], + state->Inputs[i][3]); + } + _mesa_printf("\n"); + + _mesa_printf("VertexOut:\n"); + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_OUTPUTS; i++) { + _mesa_printf("%d: %f %f %f %f ", i, + state->Outputs[i][0], + state->Outputs[i][1], + state->Outputs[i][2], + state->Outputs[i][3]); + } + _mesa_printf("\n"); + + _mesa_printf("Registers:\n"); + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_TEMPS; i++) { + _mesa_printf("%d: %f %f %f %f ", i, + state->Temporaries[i][0], + state->Temporaries[i][1], + state->Temporaries[i][2], + state->Temporaries[i][3]); + } + _mesa_printf("\n"); + + _mesa_printf("Parameters:\n"); + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_PARAMS; i++) { + _mesa_printf("%d: %f %f %f %f ", i, + state->Parameters[i][0], + state->Parameters[i][1], + state->Parameters[i][2], + state->Parameters[i][3]); + } + _mesa_printf("\n"); +} + + + +/** + * Return a pointer to the 4-element float vector specified by the given + * source register. + */ +static INLINE const GLfloat * +get_register_pointer( const struct vp_src_register *source, + const struct vertex_program_state *state ) +{ + if (source->RelAddr) { + const GLint reg = source->Index + state->AddressReg[0]; + ASSERT( (source->File == PROGRAM_ENV_PARAM) || + (source->File == PROGRAM_STATE_VAR) ); + if (reg < 0 || reg > MAX_NV_VERTEX_PROGRAM_PARAMS) + return ZeroVec; + else if (source->File == PROGRAM_ENV_PARAM) + return state->Parameters[reg]; + else + return state->Current->Parameters->Parameters[reg].Values; + } + else { + switch (source->File) { + case PROGRAM_TEMPORARY: + ASSERT(source->Index < MAX_NV_VERTEX_PROGRAM_TEMPS); + return state->Temporaries[source->Index]; + case PROGRAM_INPUT: + ASSERT(source->Index < MAX_NV_VERTEX_PROGRAM_INPUTS); + return state->Inputs[source->Index]; + case PROGRAM_LOCAL_PARAM: + ASSERT(source->Index < MAX_PROGRAM_LOCAL_PARAMS); + return state->Current->Base.LocalParams[source->Index]; + case PROGRAM_ENV_PARAM: + ASSERT(source->Index < MAX_NV_VERTEX_PROGRAM_PARAMS); + return state->Parameters[source->Index]; + case PROGRAM_STATE_VAR: + ASSERT(source->Index < state->Current->Parameters->NumParameters); + return state->Current->Parameters->Parameters[source->Index].Values; + default: + _mesa_problem(NULL, + "Bad source register file in get_register_pointer"); + return NULL; + } + } + return NULL; +} + + +/** + * Fetch a 4-element float vector from the given source register. + * Apply swizzling and negating as needed. + */ +static INLINE void +fetch_vector4( const struct vp_src_register *source, + const struct vertex_program_state *state, + GLfloat result[4] ) +{ + const GLfloat *src = get_register_pointer(source, state); + + if (source->Negate) { + result[0] = -src[source->Swizzle[0]]; + result[1] = -src[source->Swizzle[1]]; + result[2] = -src[source->Swizzle[2]]; + result[3] = -src[source->Swizzle[3]]; + } + else { + result[0] = src[source->Swizzle[0]]; + result[1] = src[source->Swizzle[1]]; + result[2] = src[source->Swizzle[2]]; + result[3] = src[source->Swizzle[3]]; + } +} + + + +/** + * As above, but only return result[0] element. + */ +static INLINE void +fetch_vector1( const struct vp_src_register *source, + const struct vertex_program_state *state, + GLfloat result[4] ) +{ + const GLfloat *src = get_register_pointer(source, state); + + if (source->Negate) { + result[0] = -src[source->Swizzle[0]]; + } + else { + result[0] = src[source->Swizzle[0]]; + } +} + + +/** + * Store 4 floats into a register. + */ +static void +store_vector4( const struct vp_dst_register *dest, + struct vertex_program_state *state, + const GLfloat value[4] ) +{ + GLfloat *dst; + switch (dest->File) { + case PROGRAM_TEMPORARY: + dst = state->Temporaries[dest->Index]; + break; + case PROGRAM_OUTPUT: + dst = state->Outputs[dest->Index]; + break; + case PROGRAM_ENV_PARAM: + { + /* a slight hack */ + GET_CURRENT_CONTEXT(ctx); + dst = ctx->VertexProgram.Parameters[dest->Index]; + } + break; + default: + _mesa_problem(NULL, "Invalid register file in store_vector4(file=%d)", + dest->File); + return; + } + + if (dest->WriteMask[0]) + dst[0] = value[0]; + if (dest->WriteMask[1]) + dst[1] = value[1]; + if (dest->WriteMask[2]) + dst[2] = value[2]; + if (dest->WriteMask[3]) + dst[3] = value[3]; +} + + +/** + * Set x to positive or negative infinity. + */ +#if defined(USE_IEEE) || defined(_WIN32) +#define SET_POS_INFINITY(x) ( *((GLuint *) (void *)&x) = 0x7F800000 ) +#define SET_NEG_INFINITY(x) ( *((GLuint *) (void *)&x) = 0xFF800000 ) +#elif defined(VMS) +#define SET_POS_INFINITY(x) x = __MAXFLOAT +#define SET_NEG_INFINITY(x) x = -__MAXFLOAT +#else +#define SET_POS_INFINITY(x) x = (GLfloat) HUGE_VAL +#define SET_NEG_INFINITY(x) x = (GLfloat) -HUGE_VAL +#endif + +#define SET_FLOAT_BITS(x, bits) ((fi_type *) (void *) &(x))->i = bits + + +/** + * Execute the given vertex program + */ +void +_mesa_exec_vertex_program(GLcontext *ctx, const struct vertex_program *program) +{ + struct vertex_program_state *state = &ctx->VertexProgram; + const struct vp_instruction *inst; + + ctx->_CurrentProgram = GL_VERTEX_PROGRAM_ARB; /* or NV, doesn't matter */ + + /* If the program is position invariant, multiply the input + * position and the MVP matrix and stick it into the output pos slot + */ + if (ctx->VertexProgram.Current->IsPositionInvariant) { + TRANSFORM_POINT( ctx->VertexProgram.Outputs[0], + ctx->_ModelProjectMatrix.m, + ctx->VertexProgram.Inputs[0]); + + /* XXX: This could go elsewhere */ + ctx->VertexProgram.Current->OutputsWritten |= 0x1; + } + for (inst = program->Instructions; ; inst++) { + + if (ctx->VertexProgram.CallbackEnabled && + ctx->VertexProgram.Callback) { + ctx->VertexProgram.CurrentPosition = inst->StringPos; + ctx->VertexProgram.Callback(program->Base.Target, + ctx->VertexProgram.CallbackData); + } + + switch (inst->Opcode) { + case VP_OPCODE_MOV: + { + GLfloat t[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_LIT: + { + const GLfloat epsilon = 1.0F / 256.0F; /* per NV spec */ + GLfloat t[4], lit[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + t[0] = MAX2(t[0], 0.0F); + t[1] = MAX2(t[1], 0.0F); + t[3] = CLAMP(t[3], -(128.0F - epsilon), (128.0F - epsilon)); + lit[0] = 1.0; + lit[1] = t[0]; + lit[2] = (t[0] > 0.0) ? (GLfloat) _mesa_pow(t[1], t[3]) : 0.0F; + lit[3] = 1.0; + store_vector4( &inst->DstReg, state, lit ); + } + break; + case VP_OPCODE_RCP: + { + GLfloat t[4]; + fetch_vector1( &inst->SrcReg[0], state, t ); + if (t[0] != 1.0F) + t[0] = 1.0F / t[0]; /* div by zero is infinity! */ + t[1] = t[2] = t[3] = t[0]; + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_RSQ: + { + GLfloat t[4]; + fetch_vector1( &inst->SrcReg[0], state, t ); + t[0] = INV_SQRTF(FABSF(t[0])); + t[1] = t[2] = t[3] = t[0]; + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_EXP: + { + GLfloat t[4], q[4], floor_t0; + fetch_vector1( &inst->SrcReg[0], state, t ); + floor_t0 = (float) floor(t[0]); + if (floor_t0 > FLT_MAX_EXP) { + SET_POS_INFINITY(q[0]); + SET_POS_INFINITY(q[2]); + } + else if (floor_t0 < FLT_MIN_EXP) { + q[0] = 0.0F; + q[2] = 0.0F; + } + else { +#ifdef USE_IEEE + GLint ii = (GLint) floor_t0; + ii = (ii < 23) + 0x3f800000; + SET_FLOAT_BITS(q[0], ii); + q[0] = *((GLfloat *) (void *)&ii); +#else + q[0] = (GLfloat) pow(2.0, floor_t0); +#endif + q[2] = (GLfloat) (q[0] * LOG2(q[1])); + } + q[1] = t[0] - floor_t0; + q[3] = 1.0F; + store_vector4( &inst->DstReg, state, q ); + } + break; + case VP_OPCODE_LOG: + { + GLfloat t[4], q[4], abs_t0; + fetch_vector1( &inst->SrcReg[0], state, t ); + abs_t0 = (GLfloat) fabs(t[0]); + if (abs_t0 != 0.0F) { + /* Since we really can't handle infinite values on VMS + * like other OSes we'll use __MAXFLOAT to represent + * infinity. This may need some tweaking. + */ +#ifdef VMS + if (abs_t0 == __MAXFLOAT) +#else + if (IS_INF_OR_NAN(abs_t0)) +#endif + { + SET_POS_INFINITY(q[0]); + q[1] = 1.0F; + SET_POS_INFINITY(q[2]); + } + else { + int exponent; + double mantissa = frexp(t[0], &exponent); + q[0] = (GLfloat) (exponent - 1); + q[1] = (GLfloat) (2.0 * mantissa); /* map [.5, 1) -> [1, 2) */ + q[2] = (GLfloat) (q[0] + LOG2(q[1])); + } + } + else { + SET_NEG_INFINITY(q[0]); + q[1] = 1.0F; + SET_NEG_INFINITY(q[2]); + } + q[3] = 1.0; + store_vector4( &inst->DstReg, state, q ); + } + break; + case VP_OPCODE_MUL: + { + GLfloat t[4], u[4], prod[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + prod[0] = t[0] * u[0]; + prod[1] = t[1] * u[1]; + prod[2] = t[2] * u[2]; + prod[3] = t[3] * u[3]; + store_vector4( &inst->DstReg, state, prod ); + } + break; + case VP_OPCODE_ADD: + { + GLfloat t[4], u[4], sum[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + sum[0] = t[0] + u[0]; + sum[1] = t[1] + u[1]; + sum[2] = t[2] + u[2]; + sum[3] = t[3] + u[3]; + store_vector4( &inst->DstReg, state, sum ); + } + break; + case VP_OPCODE_DP3: + { + GLfloat t[4], u[4], dot[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + dot[0] = t[0] * u[0] + t[1] * u[1] + t[2] * u[2]; + dot[1] = dot[2] = dot[3] = dot[0]; + store_vector4( &inst->DstReg, state, dot ); + } + break; + case VP_OPCODE_DP4: + { + GLfloat t[4], u[4], dot[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + dot[0] = t[0] * u[0] + t[1] * u[1] + t[2] * u[2] + t[3] * u[3]; + dot[1] = dot[2] = dot[3] = dot[0]; + store_vector4( &inst->DstReg, state, dot ); + } + break; + case VP_OPCODE_DST: + { + GLfloat t[4], u[4], dst[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + dst[0] = 1.0F; + dst[1] = t[1] * u[1]; + dst[2] = t[2]; + dst[3] = u[3]; + store_vector4( &inst->DstReg, state, dst ); + } + break; + case VP_OPCODE_MIN: + { + GLfloat t[4], u[4], min[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + min[0] = (t[0] < u[0]) ? t[0] : u[0]; + min[1] = (t[1] < u[1]) ? t[1] : u[1]; + min[2] = (t[2] < u[2]) ? t[2] : u[2]; + min[3] = (t[3] < u[3]) ? t[3] : u[3]; + store_vector4( &inst->DstReg, state, min ); + } + break; + case VP_OPCODE_MAX: + { + GLfloat t[4], u[4], max[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + max[0] = (t[0] > u[0]) ? t[0] : u[0]; + max[1] = (t[1] > u[1]) ? t[1] : u[1]; + max[2] = (t[2] > u[2]) ? t[2] : u[2]; + max[3] = (t[3] > u[3]) ? t[3] : u[3]; + store_vector4( &inst->DstReg, state, max ); + } + break; + case VP_OPCODE_SLT: + { + GLfloat t[4], u[4], slt[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + slt[0] = (t[0] < u[0]) ? 1.0F : 0.0F; + slt[1] = (t[1] < u[1]) ? 1.0F : 0.0F; + slt[2] = (t[2] < u[2]) ? 1.0F : 0.0F; + slt[3] = (t[3] < u[3]) ? 1.0F : 0.0F; + store_vector4( &inst->DstReg, state, slt ); + } + break; + case VP_OPCODE_SGE: + { + GLfloat t[4], u[4], sge[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + sge[0] = (t[0] >= u[0]) ? 1.0F : 0.0F; + sge[1] = (t[1] >= u[1]) ? 1.0F : 0.0F; + sge[2] = (t[2] >= u[2]) ? 1.0F : 0.0F; + sge[3] = (t[3] >= u[3]) ? 1.0F : 0.0F; + store_vector4( &inst->DstReg, state, sge ); + } + break; + case VP_OPCODE_MAD: + { + GLfloat t[4], u[4], v[4], sum[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + fetch_vector4( &inst->SrcReg[2], state, v ); + sum[0] = t[0] * u[0] + v[0]; + sum[1] = t[1] * u[1] + v[1]; + sum[2] = t[2] * u[2] + v[2]; + sum[3] = t[3] * u[3] + v[3]; + store_vector4( &inst->DstReg, state, sum ); + } + break; + case VP_OPCODE_ARL: + { + GLfloat t[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + state->AddressReg[0] = (GLint) floor(t[0]); + } + break; + case VP_OPCODE_DPH: + { + GLfloat t[4], u[4], dot[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + dot[0] = t[0] * u[0] + t[1] * u[1] + t[2] * u[2] + u[3]; + dot[1] = dot[2] = dot[3] = dot[0]; + store_vector4( &inst->DstReg, state, dot ); + } + break; + case VP_OPCODE_RCC: + { + GLfloat t[4], u; + fetch_vector1( &inst->SrcReg[0], state, t ); + if (t[0] == 1.0F) + u = 1.0F; + else + u = 1.0F / t[0]; + if (u > 0.0F) { + if (u > 1.884467e+019F) { + u = 1.884467e+019F; /* IEEE 32-bit binary value 0x5F800000 */ + } + else if (u < 5.42101e-020F) { + u = 5.42101e-020F; /* IEEE 32-bit binary value 0x1F800000 */ + } + } + else { + if (u < -1.884467e+019F) { + u = -1.884467e+019F; /* IEEE 32-bit binary value 0xDF800000 */ + } + else if (u > -5.42101e-020F) { + u = -5.42101e-020F; /* IEEE 32-bit binary value 0x9F800000 */ + } + } + t[0] = t[1] = t[2] = t[3] = u; + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_SUB: /* GL_NV_vertex_program1_1 */ + { + GLfloat t[4], u[4], sum[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + sum[0] = t[0] - u[0]; + sum[1] = t[1] - u[1]; + sum[2] = t[2] - u[2]; + sum[3] = t[3] - u[3]; + store_vector4( &inst->DstReg, state, sum ); + } + break; + case VP_OPCODE_ABS: /* GL_NV_vertex_program1_1 */ + { + GLfloat t[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + if (t[0] < 0.0) t[0] = -t[0]; + if (t[1] < 0.0) t[1] = -t[1]; + if (t[2] < 0.0) t[2] = -t[2]; + if (t[3] < 0.0) t[3] = -t[3]; + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_FLR: /* GL_ARB_vertex_program */ + { + GLfloat t[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + t[0] = FLOORF(t[0]); + t[1] = FLOORF(t[1]); + t[2] = FLOORF(t[2]); + t[3] = FLOORF(t[3]); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_FRC: /* GL_ARB_vertex_program */ + { + GLfloat t[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + t[0] = t[0] - FLOORF(t[0]); + t[1] = t[1] - FLOORF(t[1]); + t[2] = t[2] - FLOORF(t[2]); + t[3] = t[3] - FLOORF(t[3]); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_EX2: /* GL_ARB_vertex_program */ + { + GLfloat t[4]; + fetch_vector1( &inst->SrcReg[0], state, t ); + t[0] = t[1] = t[2] = t[3] = (GLfloat)_mesa_pow(2.0, t[0]); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_LG2: /* GL_ARB_vertex_program */ + { + GLfloat t[4]; + fetch_vector1( &inst->SrcReg[0], state, t ); + t[0] = t[1] = t[2] = t[3] = LOG2(t[0]); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_POW: /* GL_ARB_vertex_program */ + { + GLfloat t[4], u[4]; + fetch_vector1( &inst->SrcReg[0], state, t ); + fetch_vector1( &inst->SrcReg[1], state, u ); + t[0] = t[1] = t[2] = t[3] = (GLfloat)_mesa_pow(t[0], u[0]); + store_vector4( &inst->DstReg, state, t ); + } + break; + case VP_OPCODE_XPD: /* GL_ARB_vertex_program */ + { + GLfloat t[4], u[4], cross[4]; + fetch_vector4( &inst->SrcReg[0], state, t ); + fetch_vector4( &inst->SrcReg[1], state, u ); + cross[0] = t[1] * u[2] - t[2] * u[1]; + cross[1] = t[2] * u[0] - t[0] * u[2]; + cross[2] = t[0] * u[1] - t[1] * u[0]; + store_vector4( &inst->DstReg, state, cross ); + } + break; + case VP_OPCODE_SWZ: /* GL_ARB_vertex_program */ + { + const struct vp_src_register *source = &inst->SrcReg[0]; + const GLfloat *src = get_register_pointer(source, state); + GLfloat result[4]; + GLuint i; + + /* do extended swizzling here */ + for (i = 0; i < 3; i++) { + if (source->Swizzle[i] == SWIZZLE_ZERO) + result[i] = 0.0; + else if (source->Swizzle[i] == SWIZZLE_ONE) + result[i] = -1.0; + else + result[i] = -src[source->Swizzle[i]]; + if (source->Negate) + result[i] = -result[i]; + } + store_vector4( &inst->DstReg, state, result ); + } + break; + + case VP_OPCODE_END: + ctx->_CurrentProgram = 0; + return; + default: + /* bad instruction opcode */ + _mesa_problem(ctx, "Bad VP Opcode in _mesa_exec_vertex_program"); + ctx->_CurrentProgram = 0; + return; + } /* switch */ + } /* for */ + + ctx->_CurrentProgram = 0; +} + + + +/** +Thoughts on vertex program optimization: + +The obvious thing to do is to compile the vertex program into X86/SSE/3DNow! +assembly code. That will probably be a lot of work. + +Another approach might be to replace the vp_instruction->Opcode field with +a pointer to a specialized C function which executes the instruction. +In particular we can write functions which skip swizzling, negating, +masking, relative addressing, etc. when they're not needed. + +For example: + +void simple_add( struct vp_instruction *inst ) +{ + GLfloat *sum = machine->Registers[inst->DstReg.Register]; + GLfloat *a = machine->Registers[inst->SrcReg[0].Register]; + GLfloat *b = machine->Registers[inst->SrcReg[1].Register]; + sum[0] = a[0] + b[0]; + sum[1] = a[1] + b[1]; + sum[2] = a[2] + b[2]; + sum[3] = a[3] + b[3]; +} + +*/ + +/* + +KW: + +A first step would be to 'vectorize' the programs in the same way as +the normal transformation code in the tnl module. Thus each opcode +takes zero or more input vectors (registers) and produces one or more +output vectors. + +These operations would intially be coded in C, with machine-specific +assembly following, as is currently the case for matrix +transformations in the math/ directory. The preprocessing scheme for +selecting simpler operations Brian describes above would also work +here. + +This should give reasonable performance without excessive effort. + +*/ diff --git a/src/mesa/shader/nvvertexec.h b/src/mesa/shader/nvvertexec.h new file mode 100644 index 0000000..e6e5a3a --- /dev/null +++ b/src/mesa/shader/nvvertexec.h @@ -0,0 +1,43 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: + * Brian Paul + */ + +#ifndef NVVERTEXEC_H +#define NVVERTEXEC_H + +extern void +_mesa_init_vp_per_vertex_registers(GLcontext *ctx); + +extern void +_mesa_init_vp_per_primitive_registers(GLcontext *ctx); + +extern void +_mesa_exec_vertex_program(GLcontext *ctx, const struct vertex_program *program); + +extern void +_mesa_dump_vp_state( const struct vertex_program_state *state ); + +#endif diff --git a/src/mesa/shader/nvvertparse.c b/src/mesa/shader/nvvertparse.c new file mode 100644 index 0000000..2ba02f6 --- /dev/null +++ b/src/mesa/shader/nvvertparse.c @@ -0,0 +1,1498 @@ +/* + * Mesa 3-D graphics library + * Version: 6.1 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file nvvertparse.c + * NVIDIA vertex program parser. + * \author Brian Paul + */ + +/* + * Regarding GL_NV_vertex_program, GL_NV_vertex_program1_1: + * + * Portions of this software may use or implement intellectual + * property owned and licensed by NVIDIA Corporation. NVIDIA disclaims + * any and all warranties with respect to such intellectual property, + * including any use thereof or modifications thereto. + */ + +#include "glheader.h" +#include "context.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "nvprogram.h" +#include "nvvertparse.h" +#include "nvvertprog.h" +#include "program.h" + + +/** + * Current parsing state. This structure is passed among the parsing + * functions and keeps track of the current parser position and various + * program attributes. + */ +struct parse_state { + GLcontext *ctx; + const GLubyte *start; + const GLubyte *pos; + const GLubyte *curLine; + GLboolean isStateProgram; + GLboolean isPositionInvariant; + GLboolean isVersion1_1; + GLuint inputsRead; + GLuint outputsWritten; + GLboolean anyProgRegsWritten; + GLuint numInst; /* number of instructions parsed */ +}; + + +/* + * Called whenever we find an error during parsing. + */ +static void +record_error(struct parse_state *parseState, const char *msg, int lineNo) +{ +#ifdef DEBUG + GLint line, column; + const GLubyte *lineStr; + lineStr = _mesa_find_line_column(parseState->start, + parseState->pos, &line, &column); + _mesa_debug(parseState->ctx, + "nvfragparse.c(%d): line %d, column %d:%s (%s)\n", + lineNo, line, column, (char *) lineStr, msg); + _mesa_free((void *) lineStr); +#else + (void) lineNo; +#endif + + /* Check that no error was already recorded. Only record the first one. */ + if (parseState->ctx->Program.ErrorString[0] == 0) { + _mesa_set_program_error(parseState->ctx, + parseState->pos - parseState->start, + msg); + } +} + + +#define RETURN_ERROR \ +do { \ + record_error(parseState, "Unexpected end of input.", __LINE__); \ + return GL_FALSE; \ +} while(0) + +#define RETURN_ERROR1(msg) \ +do { \ + record_error(parseState, msg, __LINE__); \ + return GL_FALSE; \ +} while(0) + +#define RETURN_ERROR2(msg1, msg2) \ +do { \ + char err[1000]; \ + _mesa_sprintf(err, "%s %s", msg1, msg2); \ + record_error(parseState, err, __LINE__); \ + return GL_FALSE; \ +} while(0) + + + + + +static GLboolean IsLetter(GLubyte b) +{ + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z'); +} + + +static GLboolean IsDigit(GLubyte b) +{ + return b >= '0' && b <= '9'; +} + + +static GLboolean IsWhitespace(GLubyte b) +{ + return b == ' ' || b == '\t' || b == '\n' || b == '\r'; +} + + +/** + * Starting at 'str' find the next token. A token can be an integer, + * an identifier or punctuation symbol. + * \return <= 0 we found an error, else, return number of characters parsed. + */ +static GLint +GetToken(struct parse_state *parseState, GLubyte *token) +{ + const GLubyte *str = parseState->pos; + GLint i = 0, j = 0; + + token[0] = 0; + + /* skip whitespace and comments */ + while (str[i] && (IsWhitespace(str[i]) || str[i] == '#')) { + if (str[i] == '#') { + /* skip comment */ + while (str[i] && (str[i] != '\n' && str[i] != '\r')) { + i++; + } + if (str[i] == '\n' || str[i] == '\r') + parseState->curLine = str + i + 1; + } + else { + /* skip whitespace */ + if (str[i] == '\n' || str[i] == '\r') + parseState->curLine = str + i + 1; + i++; + } + } + + if (str[i] == 0) + return -i; + + /* try matching an integer */ + while (str[i] && IsDigit(str[i])) { + token[j++] = str[i++]; + } + if (j > 0 || !str[i]) { + token[j] = 0; + return i; + } + + /* try matching an identifier */ + if (IsLetter(str[i])) { + while (str[i] && (IsLetter(str[i]) || IsDigit(str[i]))) { + token[j++] = str[i++]; + } + token[j] = 0; + return i; + } + + /* punctuation character */ + if (str[i]) { + token[0] = str[i++]; + token[1] = 0; + return i; + } + + /* end of input */ + token[0] = 0; + return i; +} + + +/** + * Get next token from input stream and increment stream pointer past token. + */ +static GLboolean +Parse_Token(struct parse_state *parseState, GLubyte *token) +{ + GLint i; + i = GetToken(parseState, token); + if (i <= 0) { + parseState->pos += (-i); + return GL_FALSE; + } + parseState->pos += i; + return GL_TRUE; +} + + +/** + * Get next token from input stream but don't increment stream pointer. + */ +static GLboolean +Peek_Token(struct parse_state *parseState, GLubyte *token) +{ + GLint i, len; + i = GetToken(parseState, token); + if (i <= 0) { + parseState->pos += (-i); + return GL_FALSE; + } + len = _mesa_strlen((const char *) token); + parseState->pos += (i - len); + return GL_TRUE; +} + + +/** + * Try to match 'pattern' as the next token after any whitespace/comments. + * Advance the current parsing position only if we match the pattern. + * \return GL_TRUE if pattern is matched, GL_FALSE otherwise. + */ +static GLboolean +Parse_String(struct parse_state *parseState, const char *pattern) +{ + const GLubyte *m; + GLint i; + + /* skip whitespace and comments */ + while (IsWhitespace(*parseState->pos) || *parseState->pos == '#') { + if (*parseState->pos == '#') { + while (*parseState->pos && (*parseState->pos != '\n' && *parseState->pos != '\r')) { + parseState->pos += 1; + } + if (*parseState->pos == '\n' || *parseState->pos == '\r') + parseState->curLine = parseState->pos + 1; + } + else { + /* skip whitespace */ + if (*parseState->pos == '\n' || *parseState->pos == '\r') + parseState->curLine = parseState->pos + 1; + parseState->pos += 1; + } + } + + /* Try to match the pattern */ + m = parseState->pos; + for (i = 0; pattern[i]; i++) { + if (*m != (GLubyte) pattern[i]) + return GL_FALSE; + m += 1; + } + parseState->pos = m; + + return GL_TRUE; /* success */ +} + + +/**********************************************************************/ + +static const char *InputRegisters[MAX_NV_VERTEX_PROGRAM_INPUTS + 1] = { + "OPOS", "WGHT", "NRML", "COL0", "COL1", "FOGC", "6", "7", + "TEX0", "TEX1", "TEX2", "TEX3", "TEX4", "TEX5", "TEX6", "TEX7", NULL +}; + +static const char *OutputRegisters[MAX_NV_VERTEX_PROGRAM_OUTPUTS + 1] = { + "HPOS", "COL0", "COL1", "BFC0", "BFC1", "FOGC", "PSIZ", + "TEX0", "TEX1", "TEX2", "TEX3", "TEX4", "TEX5", "TEX6", "TEX7", NULL +}; + +#ifdef DEBUG +/* NOTE: the order here must match opcodes in nvvertprog.h */ +static const char *Opcodes[] = { + "MOV", "LIT", "RCP", "RSQ", "EXP", "LOG", "MUL", "ADD", "DP3", "DP4", + "DST", "MIN", "MAX", "SLT", "SGE", "MAD", "ARL", "DPH", "RCC", "SUB", + "ABS", "END", + /* GL_ARB_vertex_program */ + "FLR", "FRC", "EX2", "LG2", "POW", "XPD", "SWZ", + NULL +}; +#endif + +/** + * Parse a temporary register: Rnn + */ +static GLboolean +Parse_TempReg(struct parse_state *parseState, GLint *tempRegNum) +{ + GLubyte token[100]; + + /* Should be 'R##' */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + if (token[0] != 'R') + RETURN_ERROR1("Expected R##"); + + if (IsDigit(token[1])) { + GLint reg = _mesa_atoi((char *) (token + 1)); + if (reg >= MAX_NV_VERTEX_PROGRAM_TEMPS) + RETURN_ERROR1("Bad temporary register name"); + *tempRegNum = reg; + } + else { + RETURN_ERROR1("Bad temporary register name"); + } + + return GL_TRUE; +} + + +/** + * Parse address register "A0.x" + */ +static GLboolean +Parse_AddrReg(struct parse_state *parseState) +{ + /* match 'A0' */ + if (!Parse_String(parseState, "A0")) + RETURN_ERROR; + + /* match '.' */ + if (!Parse_String(parseState, ".")) + RETURN_ERROR; + + /* match 'x' */ + if (!Parse_String(parseState, "x")) + RETURN_ERROR; + + return GL_TRUE; +} + + +/** + * Parse absolute program parameter register "c[##]" + */ +static GLboolean +Parse_AbsParamReg(struct parse_state *parseState, GLint *regNum) +{ + GLubyte token[100]; + + if (!Parse_String(parseState, "c")) + RETURN_ERROR; + + if (!Parse_String(parseState, "[")) + RETURN_ERROR; + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (IsDigit(token[0])) { + /* a numbered program parameter register */ + GLint reg = _mesa_atoi((char *) token); + if (reg >= MAX_NV_VERTEX_PROGRAM_PARAMS) + RETURN_ERROR1("Bad program parameter number"); + *regNum = reg; + } + else { + RETURN_ERROR; + } + + if (!Parse_String(parseState, "]")) + RETURN_ERROR; + + return GL_TRUE; +} + + +static GLboolean +Parse_ParamReg(struct parse_state *parseState, struct vp_src_register *srcReg) +{ + GLubyte token[100]; + + if (!Parse_String(parseState, "c")) + RETURN_ERROR; + + if (!Parse_String(parseState, "[")) + RETURN_ERROR; + + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + if (IsDigit(token[0])) { + /* a numbered program parameter register */ + GLint reg; + (void) Parse_Token(parseState, token); + reg = _mesa_atoi((char *) token); + if (reg >= MAX_NV_VERTEX_PROGRAM_PARAMS) + RETURN_ERROR1("Bad program parameter number"); + srcReg->File = PROGRAM_ENV_PARAM; + srcReg->Index = reg; + } + else if (_mesa_strcmp((const char *) token, "A0") == 0) { + /* address register "A0.x" */ + if (!Parse_AddrReg(parseState)) + RETURN_ERROR; + + srcReg->RelAddr = GL_TRUE; + srcReg->File = PROGRAM_ENV_PARAM; + /* Look for +/-N offset */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + if (token[0] == '-' || token[0] == '+') { + const GLubyte sign = token[0]; + (void) Parse_Token(parseState, token); /* consume +/- */ + + /* an integer should be next */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (IsDigit(token[0])) { + const GLint k = _mesa_atoi((char *) token); + if (sign == '-') { + if (k > 64) + RETURN_ERROR1("Bad address offset"); + srcReg->Index = -k; + } + else { + if (k > 63) + RETURN_ERROR1("Bad address offset"); + srcReg->Index = k; + } + } + else { + RETURN_ERROR; + } + } + else { + /* probably got a ']', catch it below */ + } + } + else { + RETURN_ERROR; + } + + /* Match closing ']' */ + if (!Parse_String(parseState, "]")) + RETURN_ERROR; + + return GL_TRUE; +} + + +/** + * Parse v[#] or v[] + */ +static GLboolean +Parse_AttribReg(struct parse_state *parseState, GLint *tempRegNum) +{ + GLubyte token[100]; + GLint j; + + /* Match 'v' */ + if (!Parse_String(parseState, "v")) + RETURN_ERROR; + + /* Match '[' */ + if (!Parse_String(parseState, "[")) + RETURN_ERROR; + + /* match number or named register */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (parseState->isStateProgram && token[0] != '0') + RETURN_ERROR1("Only v[0] accessible in vertex state programs"); + + if (IsDigit(token[0])) { + GLint reg = _mesa_atoi((char *) token); + if (reg >= MAX_NV_VERTEX_PROGRAM_INPUTS) + RETURN_ERROR1("Bad vertex attribute register name"); + *tempRegNum = reg; + } + else { + for (j = 0; InputRegisters[j]; j++) { + if (_mesa_strcmp((const char *) token, InputRegisters[j]) == 0) { + *tempRegNum = j; + break; + } + } + if (!InputRegisters[j]) { + /* unknown input register label */ + RETURN_ERROR2("Bad register name", token); + } + } + + /* Match '[' */ + if (!Parse_String(parseState, "]")) + RETURN_ERROR; + + return GL_TRUE; +} + + +static GLboolean +Parse_OutputReg(struct parse_state *parseState, GLint *outputRegNum) +{ + GLubyte token[100]; + GLint start, j; + + /* Match 'o' */ + if (!Parse_String(parseState, "o")) + RETURN_ERROR; + + /* Match '[' */ + if (!Parse_String(parseState, "[")) + RETURN_ERROR; + + /* Get output reg name */ + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (parseState->isPositionInvariant) + start = 1; /* skip HPOS register name */ + else + start = 0; + + /* try to match an output register name */ + for (j = start; OutputRegisters[j]; j++) { + if (_mesa_strcmp((const char *) token, OutputRegisters[j]) == 0) { + *outputRegNum = j; + break; + } + } + if (!OutputRegisters[j]) + RETURN_ERROR1("Unrecognized output register name"); + + /* Match ']' */ + if (!Parse_String(parseState, "]")) + RETURN_ERROR1("Expected ]"); + + return GL_TRUE; +} + + +static GLboolean +Parse_MaskedDstReg(struct parse_state *parseState, struct vp_dst_register *dstReg) +{ + GLubyte token[100]; + + /* Dst reg can be R or o[n] */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + if (token[0] == 'R') { + /* a temporary register */ + dstReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else if (!parseState->isStateProgram && token[0] == 'o') { + /* an output register */ + dstReg->File = PROGRAM_OUTPUT; + if (!Parse_OutputReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else if (parseState->isStateProgram && token[0] == 'c' && + parseState->isStateProgram) { + /* absolute program parameter register */ + /* Only valid for vertex state programs */ + dstReg->File = PROGRAM_ENV_PARAM; + if (!Parse_AbsParamReg(parseState, &dstReg->Index)) + RETURN_ERROR; + } + else { + RETURN_ERROR1("Bad destination register name"); + } + + /* Parse optional write mask */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + + if (token[0] == '.') { + /* got a mask */ + GLint k = 0; + + if (!Parse_String(parseState, ".")) + RETURN_ERROR; + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + dstReg->WriteMask[0] = GL_FALSE; + dstReg->WriteMask[1] = GL_FALSE; + dstReg->WriteMask[2] = GL_FALSE; + dstReg->WriteMask[3] = GL_FALSE; + + if (token[k] == 'x') { + dstReg->WriteMask[0] = GL_TRUE; + k++; + } + if (token[k] == 'y') { + dstReg->WriteMask[1] = GL_TRUE; + k++; + } + if (token[k] == 'z') { + dstReg->WriteMask[2] = GL_TRUE; + k++; + } + if (token[k] == 'w') { + dstReg->WriteMask[3] = GL_TRUE; + k++; + } + if (k == 0) { + RETURN_ERROR1("Bad writemask character"); + } + return GL_TRUE; + } + else { + dstReg->WriteMask[0] = GL_TRUE; + dstReg->WriteMask[1] = GL_TRUE; + dstReg->WriteMask[2] = GL_TRUE; + dstReg->WriteMask[3] = GL_TRUE; + return GL_TRUE; + } +} + + +static GLboolean +Parse_SwizzleSrcReg(struct parse_state *parseState, struct vp_src_register *srcReg) +{ + GLubyte token[100]; + + srcReg->RelAddr = GL_FALSE; + + /* check for '-' */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + if (token[0] == '-') { + (void) Parse_String(parseState, "-"); + srcReg->Negate = GL_TRUE; + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + } + else { + srcReg->Negate = GL_FALSE; + } + + /* Src reg can be R, c[n], c[n +/- offset], or a named vertex attrib */ + if (token[0] == 'R') { + srcReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'c') { + if (!Parse_ParamReg(parseState, srcReg)) + RETURN_ERROR; + } + else if (token[0] == 'v') { + srcReg->File = PROGRAM_INPUT; + if (!Parse_AttribReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else { + RETURN_ERROR2("Bad source register name", token); + } + + /* init swizzle fields */ + srcReg->Swizzle[0] = 0; + srcReg->Swizzle[1] = 1; + srcReg->Swizzle[2] = 2; + srcReg->Swizzle[3] = 3; + + /* Look for optional swizzle suffix */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + if (token[0] == '.') { + (void) Parse_String(parseState, "."); /* consume . */ + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (token[1] == 0) { + /* single letter swizzle */ + if (token[0] == 'x') + ASSIGN_4V(srcReg->Swizzle, 0, 0, 0, 0); + else if (token[0] == 'y') + ASSIGN_4V(srcReg->Swizzle, 1, 1, 1, 1); + else if (token[0] == 'z') + ASSIGN_4V(srcReg->Swizzle, 2, 2, 2, 2); + else if (token[0] == 'w') + ASSIGN_4V(srcReg->Swizzle, 3, 3, 3, 3); + else + RETURN_ERROR1("Expected x, y, z, or w"); + } + else { + /* 2, 3 or 4-component swizzle */ + GLint k; + for (k = 0; token[k] && k < 5; k++) { + if (token[k] == 'x') + srcReg->Swizzle[k] = 0; + else if (token[k] == 'y') + srcReg->Swizzle[k] = 1; + else if (token[k] == 'z') + srcReg->Swizzle[k] = 2; + else if (token[k] == 'w') + srcReg->Swizzle[k] = 3; + else + RETURN_ERROR; + } + if (k >= 5) + RETURN_ERROR; + } + } + + return GL_TRUE; +} + + +static GLboolean +Parse_ScalarSrcReg(struct parse_state *parseState, struct vp_src_register *srcReg) +{ + GLubyte token[100]; + + srcReg->RelAddr = GL_FALSE; + + /* check for '-' */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + if (token[0] == '-') { + srcReg->Negate = GL_TRUE; + (void) Parse_String(parseState, "-"); /* consume '-' */ + if (!Peek_Token(parseState, token)) + RETURN_ERROR; + } + else { + srcReg->Negate = GL_FALSE; + } + + /* Src reg can be R, c[n], c[n +/- offset], or a named vertex attrib */ + if (token[0] == 'R') { + srcReg->File = PROGRAM_TEMPORARY; + if (!Parse_TempReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else if (token[0] == 'c') { + if (!Parse_ParamReg(parseState, srcReg)) + RETURN_ERROR; + } + else if (token[0] == 'v') { + srcReg->File = PROGRAM_INPUT; + if (!Parse_AttribReg(parseState, &srcReg->Index)) + RETURN_ERROR; + } + else { + RETURN_ERROR2("Bad source register name", token); + } + + /* Look for .[xyzw] suffix */ + if (!Parse_String(parseState, ".")) + RETURN_ERROR; + + if (!Parse_Token(parseState, token)) + RETURN_ERROR; + + if (token[0] == 'x' && token[1] == 0) { + srcReg->Swizzle[0] = 0; + } + else if (token[0] == 'y' && token[1] == 0) { + srcReg->Swizzle[0] = 1; + } + else if (token[0] == 'z' && token[1] == 0) { + srcReg->Swizzle[0] = 2; + } + else if (token[0] == 'w' && token[1] == 0) { + srcReg->Swizzle[0] = 3; + } + else { + RETURN_ERROR1("Bad scalar source suffix"); + } + srcReg->Swizzle[1] = srcReg->Swizzle[2] = srcReg->Swizzle[3] = 0; + + return GL_TRUE; +} + + +static GLint +Parse_UnaryOpInstruction(struct parse_state *parseState, + struct vp_instruction *inst, enum vp_opcode opcode) +{ + if (opcode == VP_OPCODE_ABS && !parseState->isVersion1_1) + RETURN_ERROR1("ABS illegal for vertex program 1.0"); + + inst->Opcode = opcode; + inst->StringPos = parseState->curLine - parseState->start; + + /* dest reg */ + if (!Parse_MaskedDstReg(parseState, &inst->DstReg)) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + + /* semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR; + + return GL_TRUE; +} + + +static GLboolean +Parse_BiOpInstruction(struct parse_state *parseState, + struct vp_instruction *inst, enum vp_opcode opcode) +{ + if (opcode == VP_OPCODE_DPH && !parseState->isVersion1_1) + RETURN_ERROR1("DPH illegal for vertex program 1.0"); + if (opcode == VP_OPCODE_SUB && !parseState->isVersion1_1) + RETURN_ERROR1("SUB illegal for vertex program 1.0"); + + inst->Opcode = opcode; + inst->StringPos = parseState->curLine - parseState->start; + + /* dest reg */ + if (!Parse_MaskedDstReg(parseState, &inst->DstReg)) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* first src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* second src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + + /* semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR; + + /* make sure we don't reference more than one program parameter register */ + if (inst->SrcReg[0].File == PROGRAM_ENV_PARAM && + inst->SrcReg[1].File == PROGRAM_ENV_PARAM && + inst->SrcReg[0].Index != inst->SrcReg[1].Index) + RETURN_ERROR1("Can't reference two program parameter registers"); + + /* make sure we don't reference more than one vertex attribute register */ + if (inst->SrcReg[0].File == PROGRAM_INPUT && + inst->SrcReg[1].File == PROGRAM_INPUT && + inst->SrcReg[0].Index != inst->SrcReg[1].Index) + RETURN_ERROR1("Can't reference two vertex attribute registers"); + + return GL_TRUE; +} + + +static GLboolean +Parse_TriOpInstruction(struct parse_state *parseState, + struct vp_instruction *inst, enum vp_opcode opcode) +{ + inst->Opcode = opcode; + inst->StringPos = parseState->curLine - parseState->start; + + /* dest reg */ + if (!Parse_MaskedDstReg(parseState, &inst->DstReg)) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* first src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* second src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[1])) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* third src arg */ + if (!Parse_SwizzleSrcReg(parseState, &inst->SrcReg[2])) + RETURN_ERROR; + + /* semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR; + + /* make sure we don't reference more than one program parameter register */ + if ((inst->SrcReg[0].File == PROGRAM_ENV_PARAM && + inst->SrcReg[1].File == PROGRAM_ENV_PARAM && + inst->SrcReg[0].Index != inst->SrcReg[1].Index) || + (inst->SrcReg[0].File == PROGRAM_ENV_PARAM && + inst->SrcReg[2].File == PROGRAM_ENV_PARAM && + inst->SrcReg[0].Index != inst->SrcReg[2].Index) || + (inst->SrcReg[1].File == PROGRAM_ENV_PARAM && + inst->SrcReg[2].File == PROGRAM_ENV_PARAM && + inst->SrcReg[1].Index != inst->SrcReg[2].Index)) + RETURN_ERROR1("Can only reference one program register"); + + /* make sure we don't reference more than one vertex attribute register */ + if ((inst->SrcReg[0].File == PROGRAM_INPUT && + inst->SrcReg[1].File == PROGRAM_INPUT && + inst->SrcReg[0].Index != inst->SrcReg[1].Index) || + (inst->SrcReg[0].File == PROGRAM_INPUT && + inst->SrcReg[2].File == PROGRAM_INPUT && + inst->SrcReg[0].Index != inst->SrcReg[2].Index) || + (inst->SrcReg[1].File == PROGRAM_INPUT && + inst->SrcReg[2].File == PROGRAM_INPUT && + inst->SrcReg[1].Index != inst->SrcReg[2].Index)) + RETURN_ERROR1("Can only reference one input register"); + + return GL_TRUE; +} + + +static GLboolean +Parse_ScalarInstruction(struct parse_state *parseState, + struct vp_instruction *inst, enum vp_opcode opcode) +{ + if (opcode == VP_OPCODE_RCC && !parseState->isVersion1_1) + RETURN_ERROR1("RCC illegal for vertex program 1.0"); + + inst->Opcode = opcode; + inst->StringPos = parseState->curLine - parseState->start; + + /* dest reg */ + if (!Parse_MaskedDstReg(parseState, &inst->DstReg)) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* first src arg */ + if (!Parse_ScalarSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + + /* semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR; + + return GL_TRUE; +} + + +static GLboolean +Parse_AddressInstruction(struct parse_state *parseState, struct vp_instruction *inst) +{ + inst->Opcode = VP_OPCODE_ARL; + inst->StringPos = parseState->curLine - parseState->start; + + /* dest A0 reg */ + if (!Parse_AddrReg(parseState)) + RETURN_ERROR; + + /* comma */ + if (!Parse_String(parseState, ",")) + RETURN_ERROR; + + /* parse src reg */ + if (!Parse_ScalarSrcReg(parseState, &inst->SrcReg[0])) + RETURN_ERROR; + + /* semicolon */ + if (!Parse_String(parseState, ";")) + RETURN_ERROR; + + return GL_TRUE; +} + + +static GLboolean +Parse_EndInstruction(struct parse_state *parseState, struct vp_instruction *inst) +{ + GLubyte token[100]; + + inst->Opcode = VP_OPCODE_END; + inst->StringPos = parseState->curLine - parseState->start; + + /* this should fail! */ + if (Parse_Token(parseState, token)) + RETURN_ERROR2("Unexpected token after END:", token); + else + return GL_TRUE; +} + + +static GLboolean +Parse_OptionSequence(struct parse_state *parseState, + struct vp_instruction program[]) +{ + (void) program; + while (1) { + if (!Parse_String(parseState, "OPTION")) + return GL_TRUE; /* ok, not an OPTION statement */ + if (Parse_String(parseState, "NV_position_invariant")) { + parseState->isPositionInvariant = GL_TRUE; + } + else { + RETURN_ERROR1("unexpected OPTION statement"); + } + if (!Parse_String(parseState, ";")) + return GL_FALSE; + } +} + + +static GLboolean +Parse_InstructionSequence(struct parse_state *parseState, + struct vp_instruction program[]) +{ + while (1) { + struct vp_instruction *inst = program + parseState->numInst; + + /* Initialize the instruction */ + inst->SrcReg[0].File = (enum register_file) -1; + inst->SrcReg[1].File = (enum register_file) -1; + inst->SrcReg[2].File = (enum register_file) -1; + inst->DstReg.File = (enum register_file) -1; + + if (Parse_String(parseState, "MOV")) { + if (!Parse_UnaryOpInstruction(parseState, inst, VP_OPCODE_MOV)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "LIT")) { + if (!Parse_UnaryOpInstruction(parseState, inst, VP_OPCODE_LIT)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "ABS")) { + if (!Parse_UnaryOpInstruction(parseState, inst, VP_OPCODE_ABS)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "MUL")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_MUL)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "ADD")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_ADD)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "DP3")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_DP3)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "DP4")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_DP4)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "DST")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_DST)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "MIN")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_MIN)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "MAX")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_MAX)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "SLT")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_SLT)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "SGE")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_SGE)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "DPH")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_DPH)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "SUB")) { + if (!Parse_BiOpInstruction(parseState, inst, VP_OPCODE_SUB)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "MAD")) { + if (!Parse_TriOpInstruction(parseState, inst, VP_OPCODE_MAD)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "RCP")) { + if (!Parse_ScalarInstruction(parseState, inst, VP_OPCODE_RCP)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "RSQ")) { + if (!Parse_ScalarInstruction(parseState, inst, VP_OPCODE_RSQ)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "EXP")) { + if (!Parse_ScalarInstruction(parseState, inst, VP_OPCODE_EXP)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "LOG")) { + if (!Parse_ScalarInstruction(parseState, inst, VP_OPCODE_LOG)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "RCC")) { + if (!Parse_ScalarInstruction(parseState, inst, VP_OPCODE_RCC)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "ARL")) { + if (!Parse_AddressInstruction(parseState, inst)) + RETURN_ERROR; + } + else if (Parse_String(parseState, "END")) { + if (!Parse_EndInstruction(parseState, inst)) + RETURN_ERROR; + else { + parseState->numInst++; + return GL_TRUE; /* all done */ + } + } + else { + /* bad instruction name */ + RETURN_ERROR1("Unexpected token"); + } + + /* examine input/output registers */ + if (inst->DstReg.File == PROGRAM_OUTPUT) + parseState->outputsWritten |= (1 << inst->DstReg.Index); + else if (inst->DstReg.File == PROGRAM_ENV_PARAM) + parseState->anyProgRegsWritten = GL_TRUE; + + if (inst->SrcReg[0].File == PROGRAM_INPUT) + parseState->inputsRead |= (1 << inst->SrcReg[0].Index); + if (inst->SrcReg[1].File == PROGRAM_INPUT) + parseState->inputsRead |= (1 << inst->SrcReg[1].Index); + if (inst->SrcReg[2].File == PROGRAM_INPUT) + parseState->inputsRead |= (1 << inst->SrcReg[2].Index); + + parseState->numInst++; + + if (parseState->numInst >= MAX_NV_VERTEX_PROGRAM_INSTRUCTIONS) + RETURN_ERROR1("Program too long"); + } + + RETURN_ERROR; +} + + +static GLboolean +Parse_Program(struct parse_state *parseState, + struct vp_instruction instBuffer[]) +{ + if (parseState->isVersion1_1) { + if (!Parse_OptionSequence(parseState, instBuffer)) { + return GL_FALSE; + } + } + return Parse_InstructionSequence(parseState, instBuffer); +} + + +/** + * Parse/compile the 'str' returning the compiled 'program'. + * ctx->Program.ErrorPos will be -1 if successful. Otherwise, ErrorPos + * indicates the position of the error in 'str'. + */ +void +_mesa_parse_nv_vertex_program(GLcontext *ctx, GLenum dstTarget, + const GLubyte *str, GLsizei len, + struct vertex_program *program) +{ + struct parse_state parseState; + struct vp_instruction instBuffer[MAX_NV_VERTEX_PROGRAM_INSTRUCTIONS]; + struct vp_instruction *newInst; + GLenum target; + GLubyte *programString; + + /* Make a null-terminated copy of the program string */ + programString = (GLubyte *) MALLOC(len + 1); + if (!programString) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + return; + } + MEMCPY(programString, str, len); + programString[len] = 0; + + /* Get ready to parse */ + parseState.ctx = ctx; + parseState.start = programString; + parseState.isPositionInvariant = GL_FALSE; + parseState.isVersion1_1 = GL_FALSE; + parseState.numInst = 0; + parseState.inputsRead = 0; + parseState.outputsWritten = 0; + parseState.anyProgRegsWritten = GL_FALSE; + + /* Reset error state */ + _mesa_set_program_error(ctx, -1, NULL); + + /* check the program header */ + if (_mesa_strncmp((const char *) programString, "!!VP1.0", 7) == 0) { + target = GL_VERTEX_PROGRAM_NV; + parseState.pos = programString + 7; + parseState.isStateProgram = GL_FALSE; + } + else if (_mesa_strncmp((const char *) programString, "!!VP1.1", 7) == 0) { + target = GL_VERTEX_PROGRAM_NV; + parseState.pos = programString + 7; + parseState.isStateProgram = GL_FALSE; + parseState.isVersion1_1 = GL_TRUE; + } + else if (_mesa_strncmp((const char *) programString, "!!VSP1.0", 8) == 0) { + target = GL_VERTEX_STATE_PROGRAM_NV; + parseState.pos = programString + 8; + parseState.isStateProgram = GL_TRUE; + } + else { + /* invalid header */ + ctx->Program.ErrorPos = 0; + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV(bad header)"); + return; + } + + /* make sure target and header match */ + if (target != dstTarget) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glLoadProgramNV(target mismatch)"); + return; + } + + + if (Parse_Program(&parseState, instBuffer)) { + /* successful parse! */ + + if (parseState.isStateProgram) { + if (!parseState.anyProgRegsWritten) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glLoadProgramNV(c[#] not written)"); + return; + } + } + else { + if (!parseState.isPositionInvariant && + !(parseState.outputsWritten & 1)) { + /* bit 1 = HPOS register */ + _mesa_error(ctx, GL_INVALID_OPERATION, + "glLoadProgramNV(HPOS not written)"); + return; + } + } + + /* copy the compiled instructions */ + assert(parseState.numInst <= MAX_NV_VERTEX_PROGRAM_INSTRUCTIONS); + newInst = (struct vp_instruction *) + MALLOC(parseState.numInst * sizeof(struct vp_instruction)); + if (!newInst) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV"); + FREE(programString); + return; /* out of memory */ + } + MEMCPY(newInst, instBuffer, + parseState.numInst * sizeof(struct vp_instruction)); + + /* install the program */ + program->Base.Target = target; + if (program->Base.String) { + FREE(program->Base.String); + } + program->Base.String = programString; + program->Base.Format = GL_PROGRAM_FORMAT_ASCII_ARB; + if (program->Instructions) { + FREE(program->Instructions); + } + program->Instructions = newInst; + program->InputsRead = parseState.inputsRead; + program->OutputsWritten = parseState.outputsWritten; + program->IsPositionInvariant = parseState.isPositionInvariant; + program->IsNVProgram = GL_TRUE; + +#ifdef DEBUG_foo + _mesa_printf("--- glLoadProgramNV result ---\n"); + _mesa_print_nv_vertex_program(program); + _mesa_printf("------------------------------\n"); +#endif + } + else { + /* Error! */ + _mesa_error(ctx, GL_INVALID_OPERATION, "glLoadProgramNV"); + /* NOTE: _mesa_set_program_error would have been called already */ + /* GL_NV_vertex_program isn't supposed to set the error string + * so we reset it here. + */ + _mesa_set_program_error(ctx, ctx->Program.ErrorPos, NULL); + } +} + +#ifdef DEBUG +static void +PrintSrcReg(const struct vp_src_register *src) +{ + static const char comps[5] = "xyzw"; + if (src->Negate) + _mesa_printf("-"); + if (src->RelAddr) { + if (src->Index > 0) + _mesa_printf("c[A0.x + %d]", src->Index); + else if (src->Index < 0) + _mesa_printf("c[A0.x - %d]", -src->Index); + else + _mesa_printf("c[A0.x]"); + } + else if (src->File == PROGRAM_OUTPUT) { + _mesa_printf("o[%s]", OutputRegisters[src->Index]); + } + else if (src->File == PROGRAM_INPUT) { + _mesa_printf("v[%s]", InputRegisters[src->Index]); + } + else if (src->File == PROGRAM_ENV_PARAM) { + _mesa_printf("c[%d]", src->Index); + } + else { + ASSERT(src->File == PROGRAM_TEMPORARY); + _mesa_printf("R%d", src->Index); + } + + if (src->Swizzle[0] == src->Swizzle[1] && + src->Swizzle[0] == src->Swizzle[2] && + src->Swizzle[0] == src->Swizzle[3]) { + _mesa_printf(".%c", comps[src->Swizzle[0]]); + } + else if (src->Swizzle[0] != 0 || + src->Swizzle[1] != 1 || + src->Swizzle[2] != 2 || + src->Swizzle[3] != 3) { + _mesa_printf(".%c%c%c%c", + comps[src->Swizzle[0]], + comps[src->Swizzle[1]], + comps[src->Swizzle[2]], + comps[src->Swizzle[3]]); + } +} + + +static void +PrintDstReg(const struct vp_dst_register *dst) +{ + GLint w = dst->WriteMask[0] + dst->WriteMask[1] + + dst->WriteMask[2] + dst->WriteMask[3]; + + if (dst->File == PROGRAM_OUTPUT) { + _mesa_printf("o[%s]", OutputRegisters[dst->Index]); + } + else if (dst->File == PROGRAM_INPUT) { + _mesa_printf("v[%s]", InputRegisters[dst->Index]); + } + else if (dst->File == PROGRAM_ENV_PARAM) { + _mesa_printf("c[%d]", dst->Index); + } + else { + ASSERT(dst->File == PROGRAM_TEMPORARY); + _mesa_printf("R%d", dst->Index); + } + + if (w != 0 && w != 4) { + _mesa_printf("."); + if (dst->WriteMask[0]) + _mesa_printf("x"); + if (dst->WriteMask[1]) + _mesa_printf("y"); + if (dst->WriteMask[2]) + _mesa_printf("z"); + if (dst->WriteMask[3]) + _mesa_printf("w"); + } +} + + +/** + * Print a single NVIDIA vertex program instruction. + */ +void +_mesa_print_nv_vertex_instruction(const struct vp_instruction *inst) +{ + switch (inst->Opcode) { + case VP_OPCODE_MOV: + case VP_OPCODE_LIT: + case VP_OPCODE_RCP: + case VP_OPCODE_RSQ: + case VP_OPCODE_EXP: + case VP_OPCODE_LOG: + case VP_OPCODE_RCC: + case VP_OPCODE_ABS: + _mesa_printf("%s ", Opcodes[(int) inst->Opcode]); + PrintDstReg(&inst->DstReg); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[0]); + _mesa_printf(";\n"); + break; + case VP_OPCODE_MUL: + case VP_OPCODE_ADD: + case VP_OPCODE_DP3: + case VP_OPCODE_DP4: + case VP_OPCODE_DST: + case VP_OPCODE_MIN: + case VP_OPCODE_MAX: + case VP_OPCODE_SLT: + case VP_OPCODE_SGE: + case VP_OPCODE_DPH: + case VP_OPCODE_SUB: + _mesa_printf("%s ", Opcodes[(int) inst->Opcode]); + PrintDstReg(&inst->DstReg); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[0]); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[1]); + _mesa_printf(";\n"); + break; + case VP_OPCODE_MAD: + _mesa_printf("MAD "); + PrintDstReg(&inst->DstReg); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[0]); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[1]); + _mesa_printf(", "); + PrintSrcReg(&inst->SrcReg[2]); + _mesa_printf(";\n"); + break; + case VP_OPCODE_ARL: + _mesa_printf("ARL A0.x, "); + PrintSrcReg(&inst->SrcReg[0]); + _mesa_printf(";\n"); + break; + case VP_OPCODE_END: + _mesa_printf("END\n"); + break; + default: + _mesa_printf("BAD INSTRUCTION\n"); + } +} + + +/** + * Print (unparse) the given vertex program. Just for debugging. + */ +void +_mesa_print_nv_vertex_program(const struct vertex_program *program) +{ + const struct vp_instruction *inst; + + for (inst = program->Instructions; ; inst++) { + _mesa_print_nv_vertex_instruction(inst); + if (inst->Opcode == VP_OPCODE_END) + return; + } +} +#endif + +const char * +_mesa_nv_vertex_input_register_name(GLuint i) +{ + ASSERT(i < MAX_NV_VERTEX_PROGRAM_INPUTS); + return InputRegisters[i]; +} + + +const char * +_mesa_nv_vertex_output_register_name(GLuint i) +{ + ASSERT(i < MAX_NV_VERTEX_PROGRAM_OUTPUTS); + return OutputRegisters[i]; +} diff --git a/src/mesa/shader/nvvertparse.h b/src/mesa/shader/nvvertparse.h new file mode 100644 index 0000000..205885f --- /dev/null +++ b/src/mesa/shader/nvvertparse.h @@ -0,0 +1,50 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2003 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: + * Brian Paul + */ + + +#ifndef NVVERTPARSE_H +#define NVVERTPARSE_H + + +extern void +_mesa_parse_nv_vertex_program(GLcontext *ctx, GLenum target, + const GLubyte *str, GLsizei len, + struct vertex_program *program); + +extern void +_mesa_print_nv_vertex_instruction(const struct vp_instruction *inst); + +extern void +_mesa_print_nv_vertex_program(const struct vertex_program *program); + +extern const char * +_mesa_nv_vertex_input_register_name(GLuint i); + +extern const char * +_mesa_nv_vertex_output_register_name(GLuint i); + +#endif diff --git a/src/mesa/shader/nvvertprog.h b/src/mesa/shader/nvvertprog.h new file mode 100644 index 0000000..820b3e5 --- /dev/null +++ b/src/mesa/shader/nvvertprog.h @@ -0,0 +1,107 @@ +/* + * Mesa 3-D graphics library + * Version: 5.1 + * + * Copyright (C) 1999-2002 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + +/* Private vertex program types and constants only used by files + * related to vertex programs. + * + * XXX TO-DO: Rename this file "vertprog.h" since it's not NV-specific. + */ + + +#ifndef NVVERTPROG_H +#define NVVERTPROG_H + + +/* Vertex program opcodes */ +enum vp_opcode +{ + VP_OPCODE_MOV, + VP_OPCODE_LIT, + VP_OPCODE_RCP, + VP_OPCODE_RSQ, + VP_OPCODE_EXP, + VP_OPCODE_LOG, + VP_OPCODE_MUL, + VP_OPCODE_ADD, + VP_OPCODE_DP3, + VP_OPCODE_DP4, + VP_OPCODE_DST, + VP_OPCODE_MIN, + VP_OPCODE_MAX, + VP_OPCODE_SLT, + VP_OPCODE_SGE, + VP_OPCODE_MAD, + VP_OPCODE_ARL, + VP_OPCODE_DPH, + VP_OPCODE_RCC, + VP_OPCODE_SUB, + VP_OPCODE_ABS, + VP_OPCODE_END, + /* Additional opcodes for GL_ARB_vertex_program */ + VP_OPCODE_FLR, + VP_OPCODE_FRC, + VP_OPCODE_EX2, + VP_OPCODE_LG2, + VP_OPCODE_POW, + VP_OPCODE_XPD, + VP_OPCODE_SWZ +}; + + + +/* Instruction source register */ +struct vp_src_register +{ + enum register_file File; /* which register file */ + GLint Index; /* index into register file */ + GLubyte Swizzle[4]; /* Each value is 0,1,2,3 for x,y,z,w or */ + /* SWIZZLE_ZERO or SWIZZLE_ONE for VP_OPCODE_SWZ. */ + GLboolean Negate; + GLboolean RelAddr; +}; + + +/* Instruction destination register */ +struct vp_dst_register +{ + enum register_file File; /* which register file */ + GLint Index; /* index into register file */ + GLboolean WriteMask[4]; +}; + + +/* Vertex program instruction */ +struct vp_instruction +{ + enum vp_opcode Opcode; + struct vp_src_register SrcReg[3]; + struct vp_dst_register DstReg; +#if FEATURE_MESA_program_debug + GLint StringPos; +#endif +}; + + +#endif /* VERTPROG_H */ diff --git a/src/mesa/shader/program.c b/src/mesa/shader/program.c new file mode 100644 index 0000000..9d86170 --- /dev/null +++ b/src/mesa/shader/program.c @@ -0,0 +1,1312 @@ +/* + * Mesa 3-D graphics library + * Version: 6.2 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file program.c + * Vertex and fragment program support functions. + * \author Brian Paul + */ + + +#include "glheader.h" +#include "context.h" +#include "hash.h" +#include "imports.h" +#include "macros.h" +#include "mtypes.h" +#include "program.h" +#include "nvfragparse.h" +#include "nvfragprog.h" +#include "nvvertparse.h" + + +/**********************************************************************/ +/* Utility functions */ +/**********************************************************************/ + + +/* A pointer to this dummy program is put into the hash table when + * glGenPrograms is called. + */ +struct program _mesa_DummyProgram; + + +/** + * Init context's vertex/fragment program state + */ +void +_mesa_init_program(GLcontext *ctx) +{ + GLuint i; + + ctx->Program.ErrorPos = -1; + ctx->Program.ErrorString = _mesa_strdup(""); + +#if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program + ctx->VertexProgram.Enabled = GL_FALSE; + ctx->VertexProgram.PointSizeEnabled = GL_FALSE; + ctx->VertexProgram.TwoSideEnabled = GL_FALSE; + ctx->VertexProgram.Current = (struct vertex_program *) ctx->Shared->DefaultVertexProgram; + assert(ctx->VertexProgram.Current); + ctx->VertexProgram.Current->Base.RefCount++; + for (i = 0; i < MAX_NV_VERTEX_PROGRAM_PARAMS / 4; i++) { + ctx->VertexProgram.TrackMatrix[i] = GL_NONE; + ctx->VertexProgram.TrackMatrixTransform[i] = GL_IDENTITY_NV; + } +#endif + +#if FEATURE_NV_fragment_program || FEATURE_ARB_fragment_program + ctx->FragmentProgram.Enabled = GL_FALSE; + ctx->FragmentProgram.Current = (struct fragment_program *) ctx->Shared->DefaultFragmentProgram; + assert(ctx->FragmentProgram.Current); + ctx->FragmentProgram.Current->Base.RefCount++; +#endif +} + + +/** + * Free a context's vertex/fragment program state + */ +void +_mesa_free_program_data(GLcontext *ctx) +{ +#if FEATURE_NV_vertex_program + if (ctx->VertexProgram.Current) { + ctx->VertexProgram.Current->Base.RefCount--; + if (ctx->VertexProgram.Current->Base.RefCount <= 0) + ctx->Driver.DeleteProgram(ctx, &(ctx->VertexProgram.Current->Base)); + } +#endif +#if FEATURE_NV_fragment_program + if (ctx->FragmentProgram.Current) { + ctx->FragmentProgram.Current->Base.RefCount--; + if (ctx->FragmentProgram.Current->Base.RefCount <= 0) + ctx->Driver.DeleteProgram(ctx, &(ctx->FragmentProgram.Current->Base)); + } +#endif + _mesa_free((void *) ctx->Program.ErrorString); +} + + + + +/** + * Set the vertex/fragment program error state (position and error string). + * This is generally called from within the parsers. + */ +void +_mesa_set_program_error(GLcontext *ctx, GLint pos, const char *string) +{ + ctx->Program.ErrorPos = pos; + _mesa_free((void *) ctx->Program.ErrorString); + if (!string) + string = ""; + ctx->Program.ErrorString = _mesa_strdup(string); +} + + +/** + * Find the line number and column for 'pos' within 'string'. + * Return a copy of the line which contains 'pos'. Free the line with + * _mesa_free(). + * \param string the program string + * \param pos the position within the string + * \param line returns the line number corresponding to 'pos'. + * \param col returns the column number corresponding to 'pos'. + * \return copy of the line containing 'pos'. + */ +const GLubyte * +_mesa_find_line_column(const GLubyte *string, const GLubyte *pos, + GLint *line, GLint *col) +{ + const GLubyte *lineStart = string; + const GLubyte *p = string; + GLubyte *s; + int len; + + *line = 1; + + while (p != pos) { + if (*p == (GLubyte) '\n') { + (*line)++; + lineStart = p + 1; + } + p++; + } + + *col = (pos - lineStart) + 1; + + /* return copy of this line */ + while (*p != 0 && *p != '\n') + p++; + len = p - lineStart; + s = (GLubyte *) _mesa_malloc(len + 1); + _mesa_memcpy(s, lineStart, len); + s[len] = 0; + + return s; +} + + +/** + * Initialize a new vertex/fragment program object. + */ +static struct program * +_mesa_init_program_struct( GLcontext *ctx, struct program *prog, + GLenum target, GLuint id) +{ + (void) ctx; + if (prog) { + prog->Id = id; + prog->Target = target; + prog->Resident = GL_TRUE; + prog->RefCount = 1; + } + + return prog; +} + + +/** + * Initialize a new fragment program object. + */ +struct program * +_mesa_init_fragment_program( GLcontext *ctx, struct fragment_program *prog, + GLenum target, GLuint id) +{ + if (prog) + return _mesa_init_program_struct( ctx, &prog->Base, target, id ); + else + return NULL; +} + + +/** + * Initialize a new vertex program object. + */ +struct program * +_mesa_init_vertex_program( GLcontext *ctx, struct vertex_program *prog, + GLenum target, GLuint id) +{ + if (prog) + return _mesa_init_program_struct( ctx, &prog->Base, target, id ); + else + return NULL; +} + + +/** + * Allocate and initialize a new fragment/vertex program object but + * don't put it into the program hash table. Called via + * ctx->Driver.NewProgram. May be overridden (ie. replaced) by a + * device driver function to implement OO deriviation with additional + * types not understood by this function. + * + * \param ctx context + * \param id program id/number + * \param target program target/type + * \return pointer to new program object + */ +struct program * +_mesa_new_program(GLcontext *ctx, GLenum target, GLuint id) +{ + switch (target) { + case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */ + return _mesa_init_vertex_program( ctx, CALLOC_STRUCT(vertex_program), + target, id ); + case GL_FRAGMENT_PROGRAM_NV: + case GL_FRAGMENT_PROGRAM_ARB: + return _mesa_init_fragment_program( ctx, CALLOC_STRUCT(fragment_program), + target, id ); + default: + _mesa_problem(ctx, "bad target in _mesa_new_program"); + return NULL; + } +} + + +/** + * Delete a program and remove it from the hash table, ignoring the + * reference count. + * Called via ctx->Driver.DeleteProgram. May be wrapped (OO deriviation) + * by a device driver function. + */ +void +_mesa_delete_program(GLcontext *ctx, struct program *prog) +{ + (void) ctx; + ASSERT(prog); + + if (prog->String) + _mesa_free(prog->String); + if (prog->Target == GL_VERTEX_PROGRAM_NV || + prog->Target == GL_VERTEX_STATE_PROGRAM_NV) { + struct vertex_program *vprog = (struct vertex_program *) prog; + if (vprog->Instructions) + _mesa_free(vprog->Instructions); + if (vprog->Parameters) + _mesa_free_parameter_list(vprog->Parameters); + } + else if (prog->Target == GL_FRAGMENT_PROGRAM_NV || + prog->Target == GL_FRAGMENT_PROGRAM_ARB) { + struct fragment_program *fprog = (struct fragment_program *) prog; + if (fprog->Instructions) + _mesa_free(fprog->Instructions); + if (fprog->Parameters) + _mesa_free_parameter_list(fprog->Parameters); + } + _mesa_free(prog); +} + + + +/**********************************************************************/ +/* Program parameter functions */ +/**********************************************************************/ + +struct program_parameter_list * +_mesa_new_parameter_list(void) +{ + return (struct program_parameter_list *) + _mesa_calloc(sizeof(struct program_parameter_list)); +} + + +/** + * Free a parameter list and all its parameters + */ +void +_mesa_free_parameter_list(struct program_parameter_list *paramList) +{ + _mesa_free_parameters(paramList); + _mesa_free(paramList); +} + + +/** + * Free all the parameters in the given list, but don't free the + * paramList structure itself. + */ +void +_mesa_free_parameters(struct program_parameter_list *paramList) +{ + GLuint i; + for (i = 0; i < paramList->NumParameters; i++) { + _mesa_free((void *) paramList->Parameters[i].Name); + } + _mesa_free(paramList->Parameters); + paramList->NumParameters = 0; + paramList->Parameters = NULL; +} + + +/** + * Helper function used by the functions below. + */ +static GLint +add_parameter(struct program_parameter_list *paramList, + const char *name, const GLfloat values[4], + enum parameter_type type) +{ + const GLuint n = paramList->NumParameters; + + paramList->Parameters = (struct program_parameter *) + _mesa_realloc(paramList->Parameters, + n * sizeof(struct program_parameter), + (n + 1) * sizeof(struct program_parameter)); + if (!paramList->Parameters) { + /* out of memory */ + paramList->NumParameters = 0; + return -1; + } + else { + paramList->NumParameters = n + 1; + paramList->Parameters[n].Name = _mesa_strdup(name); + paramList->Parameters[n].Type = type; + if (values) + COPY_4V(paramList->Parameters[n].Values, values); + return (GLint) n; + } +} + + +/** + * Add a new named program parameter (Ex: NV_fragment_program DEFINE statement) + * \return index of the new entry in the parameter list + */ +GLint +_mesa_add_named_parameter(struct program_parameter_list *paramList, + const char *name, const GLfloat values[4]) +{ + return add_parameter(paramList, name, values, NAMED_PARAMETER); +} + + +/** + * Add a new unnamed constant to the parameter list. + * \param paramList - the parameter list + * \param values - four float values + * \return index of the new parameter. + */ +GLint +_mesa_add_named_constant(struct program_parameter_list *paramList, + const char *name, const GLfloat values[4]) +{ + return add_parameter(paramList, name, values, CONSTANT); +} + + +/** + * Add a new unnamed constant to the parameter list. + * \param paramList - the parameter list + * \param values - four float values + * \return index of the new parameter. + */ +GLint +_mesa_add_unnamed_constant(struct program_parameter_list *paramList, + const GLfloat values[4]) +{ + /* generate a new dummy name */ + static GLuint n = 0; + char name[20]; + _mesa_sprintf(name, "constant%d", n); + n++; + /* store it */ + return add_parameter(paramList, name, values, CONSTANT); +} + + +/** + * Add a new state reference to the parameter list. + * \param paramList - the parameter list + * \param state - an array of 6 state tokens + * + * \return index of the new parameter. + */ +GLint +_mesa_add_state_reference(struct program_parameter_list *paramList, + GLint *stateTokens) +{ + /* XXX Should we parse here and produce the parameter's + * list of STATE_* tokens here, or in the parser? + */ + GLint a, idx; + + idx = add_parameter(paramList, "Some State", NULL, STATE); + + for (a=0; a<6; a++) + paramList->Parameters[idx].StateIndexes[a] = (enum state_index) stateTokens[a]; + + return idx; +} + + +/** + * Lookup a parameter value by name in the given parameter list. + * \return pointer to the float[4] values. + */ +GLfloat * +_mesa_lookup_parameter_value(struct program_parameter_list *paramList, + GLsizei nameLen, const char *name) +{ + GLuint i; + + if (!paramList) + return NULL; + + if (nameLen == -1) { + /* name is null-terminated */ + for (i = 0; i < paramList->NumParameters; i++) { + if (_mesa_strcmp(paramList->Parameters[i].Name, name) == 0) + return paramList->Parameters[i].Values; + } + } + else { + /* name is not null-terminated, use nameLen */ + for (i = 0; i < paramList->NumParameters; i++) { + if (_mesa_strncmp(paramList->Parameters[i].Name, name, nameLen) == 0 + && _mesa_strlen(paramList->Parameters[i].Name) == (size_t)nameLen) + return paramList->Parameters[i].Values; + } + } + return NULL; +} + + +/** + * Lookup a parameter index by name in the given parameter list. + * \return index of parameter in the list. + */ +GLint +_mesa_lookup_parameter_index(struct program_parameter_list *paramList, + GLsizei nameLen, const char *name) +{ + GLint i; + + if (!paramList) + return -1; + + if (nameLen == -1) { + /* name is null-terminated */ + for (i = 0; i < (GLint) paramList->NumParameters; i++) { + if (_mesa_strcmp(paramList->Parameters[i].Name, name) == 0) + return i; + } + } + else { + /* name is not null-terminated, use nameLen */ + for (i = 0; i < (GLint) paramList->NumParameters; i++) { + if (_mesa_strncmp(paramList->Parameters[i].Name, name, nameLen) == 0 + && _mesa_strlen(paramList->Parameters[i].Name) == (size_t)nameLen) + return i; + } + } + return -1; +} + + +/** + * Use the list of tokens in the state[] array to find global GL state + * and return it in . Usually, four values are returned in + * but matrix queries may return as many as 16 values. + * This function is used for ARB vertex/fragment programs. + * The program parser will produce the state[] values. + */ +static void +_mesa_fetch_state(GLcontext *ctx, const enum state_index state[], + GLfloat *value) +{ + switch (state[0]) { + case STATE_MATERIAL: + { + /* state[1] is either 0=front or 1=back side */ + const GLuint face = (GLuint) state[1]; + /* state[2] is the material attribute */ + switch (state[2]) { + case STATE_AMBIENT: + if (face == 0) + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_AMBIENT]); + else + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_AMBIENT]); + return; + case STATE_DIFFUSE: + if (face == 0) + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE]); + else + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE]); + return; + case STATE_SPECULAR: + if (face == 0) + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_SPECULAR]); + else + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_SPECULAR]); + return; + case STATE_EMISSION: + if (face == 0) + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_EMISSION]); + else + COPY_4V(value, ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_EMISSION]); + return; + case STATE_SHININESS: + if (face == 0) + value[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_SHININESS][0]; + else + value[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_SHININESS][0]; + value[1] = 0.0F; + value[2] = 0.0F; + value[3] = 1.0F; + return; + default: + _mesa_problem(ctx, "Invalid material state in fetch_state"); + return; + } + } + case STATE_LIGHT: + { + /* state[1] is the light number */ + const GLuint ln = (GLuint) state[1]; + /* state[2] is the light attribute */ + switch (state[2]) { + case STATE_AMBIENT: + COPY_4V(value, ctx->Light.Light[ln].Ambient); + return; + case STATE_DIFFUSE: + COPY_4V(value, ctx->Light.Light[ln].Diffuse); + return; + case STATE_SPECULAR: + COPY_4V(value, ctx->Light.Light[ln].Specular); + return; + case STATE_POSITION: + COPY_4V(value, ctx->Light.Light[ln].EyePosition); + return; + case STATE_ATTENUATION: + value[0] = ctx->Light.Light[ln].ConstantAttenuation; + value[1] = ctx->Light.Light[ln].LinearAttenuation; + value[2] = ctx->Light.Light[ln].QuadraticAttenuation; + value[3] = ctx->Light.Light[ln].SpotExponent; + return; + case STATE_SPOT_DIRECTION: + COPY_3V(value, ctx->Light.Light[ln].EyeDirection); + value[3] = ctx->Light.Light[ln]._CosCutoff; + return; + case STATE_HALF: + { + GLfloat eye_z[] = {0, 0, 1}; + + /* Compute infinite half angle vector: + * half-vector = light_position + (0, 0, 1) + * and then normalize. w = 0 + * + * light.EyePosition.w should be 0 for infinite lights. + */ + ADD_3V(value, eye_z, ctx->Light.Light[ln].EyePosition); + NORMALIZE_3FV(value); + value[3] = 0; + } + return; + default: + _mesa_problem(ctx, "Invalid light state in fetch_state"); + return; + } + } + case STATE_LIGHTMODEL_AMBIENT: + COPY_4V(value, ctx->Light.Model.Ambient); + return; + case STATE_LIGHTMODEL_SCENECOLOR: + if (state[1] == 0) { + /* front */ + GLint i; + for (i = 0; i < 4; i++) { + value[i] = ctx->Light.Model.Ambient[i] + * ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_AMBIENT][i] + + ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_EMISSION][i]; + } + } + else { + /* back */ + GLint i; + for (i = 0; i < 4; i++) { + value[i] = ctx->Light.Model.Ambient[i] + * ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_AMBIENT][i] + + ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_EMISSION][i]; + } + } + return; + case STATE_LIGHTPROD: + { + const GLuint ln = (GLuint) state[1]; + const GLuint face = (GLuint) state[2]; + GLint i; + ASSERT(face == 0 || face == 1); + switch (state[3]) { + case STATE_AMBIENT: + for (i = 0; i < 3; i++) { + value[i] = ctx->Light.Light[ln].Ambient[i] * + ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_AMBIENT+face][i]; + } + /* [3] = material alpha */ + value[3] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE+face][3]; + return; + case STATE_DIFFUSE: + for (i = 0; i < 3; i++) { + value[i] = ctx->Light.Light[ln].Diffuse[i] * + ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE+face][i]; + } + /* [3] = material alpha */ + value[3] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE+face][3]; + return; + case STATE_SPECULAR: + for (i = 0; i < 3; i++) { + value[i] = ctx->Light.Light[ln].Specular[i] * + ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_SPECULAR+face][i]; + } + /* [3] = material alpha */ + value[3] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE+face][3]; + return; + default: + _mesa_problem(ctx, "Invalid lightprod state in fetch_state"); + return; + } + } + case STATE_TEXGEN: + { + /* state[1] is the texture unit */ + const GLuint unit = (GLuint) state[1]; + /* state[2] is the texgen attribute */ + switch (state[2]) { + case STATE_TEXGEN_EYE_S: + COPY_4V(value, ctx->Texture.Unit[unit].EyePlaneS); + return; + case STATE_TEXGEN_EYE_T: + COPY_4V(value, ctx->Texture.Unit[unit].EyePlaneT); + return; + case STATE_TEXGEN_EYE_R: + COPY_4V(value, ctx->Texture.Unit[unit].EyePlaneR); + return; + case STATE_TEXGEN_EYE_Q: + COPY_4V(value, ctx->Texture.Unit[unit].EyePlaneQ); + return; + case STATE_TEXGEN_OBJECT_S: + COPY_4V(value, ctx->Texture.Unit[unit].ObjectPlaneS); + return; + case STATE_TEXGEN_OBJECT_T: + COPY_4V(value, ctx->Texture.Unit[unit].ObjectPlaneT); + return; + case STATE_TEXGEN_OBJECT_R: + COPY_4V(value, ctx->Texture.Unit[unit].ObjectPlaneR); + return; + case STATE_TEXGEN_OBJECT_Q: + COPY_4V(value, ctx->Texture.Unit[unit].ObjectPlaneQ); + return; + default: + _mesa_problem(ctx, "Invalid texgen state in fetch_state"); + return; + } + } + case STATE_TEXENV_COLOR: + { + /* state[1] is the texture unit */ + const GLuint unit = (GLuint) state[1]; + COPY_4V(value, ctx->Texture.Unit[unit].EnvColor); + } + return; + case STATE_FOG_COLOR: + COPY_4V(value, ctx->Fog.Color); + return; + case STATE_FOG_PARAMS: + value[0] = ctx->Fog.Density; + value[1] = ctx->Fog.Start; + value[2] = ctx->Fog.End; + value[3] = 1.0F / (ctx->Fog.End - ctx->Fog.Start); + return; + case STATE_CLIPPLANE: + { + const GLuint plane = (GLuint) state[1]; + COPY_4V(value, ctx->Transform.EyeUserPlane[plane]); + } + return; + case STATE_POINT_SIZE: + value[0] = ctx->Point.Size; + value[1] = ctx->Point.MinSize; + value[2] = ctx->Point.MaxSize; + value[3] = ctx->Point.Threshold; + return; + case STATE_POINT_ATTENUATION: + value[0] = ctx->Point.Params[0]; + value[1] = ctx->Point.Params[1]; + value[2] = ctx->Point.Params[2]; + value[3] = 1.0F; + return; + case STATE_MATRIX: + { + /* state[1] = modelview, projection, texture, etc. */ + /* state[2] = which texture matrix or program matrix */ + /* state[3] = first column to fetch */ + /* state[4] = last column to fetch */ + /* state[5] = transpose, inverse or invtrans */ + + const GLmatrix *matrix; + const enum state_index mat = state[1]; + const GLuint index = (GLuint) state[2]; + const GLuint first = (GLuint) state[3]; + const GLuint last = (GLuint) state[4]; + const enum state_index modifier = state[5]; + const GLfloat *m; + GLuint row, i; + if (mat == STATE_MODELVIEW) { + matrix = ctx->ModelviewMatrixStack.Top; + } + else if (mat == STATE_PROJECTION) { + matrix = ctx->ProjectionMatrixStack.Top; + } + else if (mat == STATE_MVP) { + matrix = &ctx->_ModelProjectMatrix; + } + else if (mat == STATE_TEXTURE) { + matrix = ctx->TextureMatrixStack[index].Top; + } + else if (mat == STATE_PROGRAM) { + matrix = ctx->ProgramMatrixStack[index].Top; + } + else { + _mesa_problem(ctx, "Bad matrix name in _mesa_fetch_state()"); + return; + } + if (modifier == STATE_MATRIX_INVERSE || + modifier == STATE_MATRIX_INVTRANS) { + /* XXX be sure inverse is up to date */ + m = matrix->inv; + } + else { + m = matrix->m; + } + if (modifier == STATE_MATRIX_TRANSPOSE || + modifier == STATE_MATRIX_INVTRANS) { + for (i = 0, row = first; row <= last; row++) { + value[i++] = m[row * 4 + 0]; + value[i++] = m[row * 4 + 1]; + value[i++] = m[row * 4 + 2]; + value[i++] = m[row * 4 + 3]; + } + } + else { + for (i = 0, row = first; row <= last; row++) { + value[i++] = m[row + 0]; + value[i++] = m[row + 4]; + value[i++] = m[row + 8]; + value[i++] = m[row + 12]; + } + } + } + return; + case STATE_DEPTH_RANGE: + value[0] = ctx->Viewport.Near; /* near */ + value[1] = ctx->Viewport.Far; /* far */ + value[2] = ctx->Viewport.Far - ctx->Viewport.Near; /* far - near */ + value[3] = 0; + return; + case STATE_FRAGMENT_PROGRAM: + { + /* state[1] = {STATE_ENV, STATE_LOCAL} */ + /* state[2] = parameter index */ + const int idx = (int) state[2]; + switch (state[1]) { + case STATE_ENV: + COPY_4V(value, ctx->FragmentProgram.Parameters[idx]); + break; + case STATE_LOCAL: + COPY_4V(value, ctx->FragmentProgram.Current->Base.LocalParams[idx]); + break; + default: + _mesa_problem(ctx, "Bad state switch in _mesa_fetch_state()"); + return; + } + } + return; + + case STATE_VERTEX_PROGRAM: + { + /* state[1] = {STATE_ENV, STATE_LOCAL} */ + /* state[2] = parameter index */ + const int idx = (int) state[2]; + switch (state[1]) { + case STATE_ENV: + COPY_4V(value, ctx->VertexProgram.Parameters[idx]); + break; + case STATE_LOCAL: + COPY_4V(value, ctx->VertexProgram.Current->Base.LocalParams[idx]); + break; + default: + _mesa_problem(ctx, "Bad state switch in _mesa_fetch_state()"); + return; + } + } + return; + default: + _mesa_problem(ctx, "Invalid state in _mesa_fetch_state"); + return; + } +} + + +/** + * Loop over all the parameters in a parameter list. If the parameter + * is a GL state reference, look up the current value of that state + * variable and put it into the parameter's Value[4] array. + * This would be called at glBegin time when using a fragment program. + */ +void +_mesa_load_state_parameters(GLcontext *ctx, + struct program_parameter_list *paramList) +{ + GLuint i; + + if (!paramList) + return; + + for (i = 0; i < paramList->NumParameters; i++) { + if (paramList->Parameters[i].Type == STATE) { + _mesa_fetch_state(ctx, paramList->Parameters[i].StateIndexes, + paramList->Parameters[i].Values); + } + } +} + + + +/**********************************************************************/ +/* API functions */ +/**********************************************************************/ + + +/** + * Bind a program (make it current) + * \note Called from the GL API dispatcher by both glBindProgramNV + * and glBindProgramARB. + */ +void GLAPIENTRY +_mesa_BindProgram(GLenum target, GLuint id) +{ + struct program *prog; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + FLUSH_VERTICES(ctx, _NEW_PROGRAM); + + if ((target == GL_VERTEX_PROGRAM_NV + && ctx->Extensions.NV_vertex_program) || + (target == GL_VERTEX_PROGRAM_ARB + && ctx->Extensions.ARB_vertex_program)) { + /*** Vertex program binding ***/ + struct vertex_program *curProg = ctx->VertexProgram.Current; + if (curProg->Base.Id == id) { + /* binding same program - no change */ + return; + } + if (curProg->Base.Id != 0) { + /* decrement refcount on previously bound vertex program */ + curProg->Base.RefCount--; + /* and delete if refcount goes below one */ + if (curProg->Base.RefCount <= 0) { + ASSERT(curProg->Base.DeletePending); + ctx->Driver.DeleteProgram(ctx, &(curProg->Base)); + _mesa_HashRemove(ctx->Shared->Programs, id); + } + } + } + else if ((target == GL_FRAGMENT_PROGRAM_NV + && ctx->Extensions.NV_fragment_program) || + (target == GL_FRAGMENT_PROGRAM_ARB + && ctx->Extensions.ARB_fragment_program)) { + /*** Fragment program binding ***/ + struct fragment_program *curProg = ctx->FragmentProgram.Current; + if (curProg->Base.Id == id) { + /* binding same program - no change */ + return; + } + if (curProg->Base.Id != 0) { + /* decrement refcount on previously bound fragment program */ + curProg->Base.RefCount--; + /* and delete if refcount goes below one */ + if (curProg->Base.RefCount <= 0) { + ASSERT(curProg->Base.DeletePending); + ctx->Driver.DeleteProgram(ctx, &(curProg->Base)); + _mesa_HashRemove(ctx->Shared->Programs, id); + } + } + } + else { + _mesa_error(ctx, GL_INVALID_ENUM, "glBindProgramNV/ARB(target)"); + return; + } + + /* NOTE: binding to a non-existant program is not an error. + * That's supposed to be caught in glBegin. + */ + if (id == 0) { + /* Bind default program */ + prog = NULL; + if (target == GL_VERTEX_PROGRAM_NV || target == GL_VERTEX_PROGRAM_ARB) + prog = ctx->Shared->DefaultVertexProgram; + else + prog = ctx->Shared->DefaultFragmentProgram; + } + else { + /* Bind user program */ + prog = (struct program *) _mesa_HashLookup(ctx->Shared->Programs, id); + if (!prog || prog == &_mesa_DummyProgram) { + /* allocate a new program now */ + prog = ctx->Driver.NewProgram(ctx, target, id); + if (!prog) { + _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindProgramNV/ARB"); + return; + } + _mesa_HashInsert(ctx->Shared->Programs, id, prog); + } + else if (prog->Target != target) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glBindProgramNV/ARB(target mismatch)"); + return; + } + } + + /* bind now */ + if (target == GL_VERTEX_PROGRAM_NV || target == GL_VERTEX_PROGRAM_ARB) { + ctx->VertexProgram.Current = (struct vertex_program *) prog; + } + else if (target == GL_FRAGMENT_PROGRAM_NV || target == GL_FRAGMENT_PROGRAM_ARB) { + ctx->FragmentProgram.Current = (struct fragment_program *) prog; + } + + /* Never null pointers */ + ASSERT(ctx->VertexProgram.Current); + ASSERT(ctx->FragmentProgram.Current); + + if (prog) + prog->RefCount++; + + if (ctx->Driver.BindProgram) + ctx->Driver.BindProgram(ctx, target, prog); +} + + +/** + * Delete a list of programs. + * \note Not compiled into display lists. + * \note Called by both glDeleteProgramsNV and glDeleteProgramsARB. + */ +void GLAPIENTRY +_mesa_DeletePrograms(GLsizei n, const GLuint *ids) +{ + GLint i; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx); + + if (n < 0) { + _mesa_error( ctx, GL_INVALID_VALUE, "glDeleteProgramsNV" ); + return; + } + + for (i = 0; i < n; i++) { + if (ids[i] != 0) { + struct program *prog = (struct program *) + _mesa_HashLookup(ctx->Shared->Programs, ids[i]); + if (prog == &_mesa_DummyProgram) { + _mesa_HashRemove(ctx->Shared->Programs, ids[i]); + } + else if (prog) { + /* Unbind program if necessary */ + if (prog->Target == GL_VERTEX_PROGRAM_NV || + prog->Target == GL_VERTEX_STATE_PROGRAM_NV) { + if (ctx->VertexProgram.Current && + ctx->VertexProgram.Current->Base.Id == ids[i]) { + /* unbind this currently bound program */ + _mesa_BindProgram(prog->Target, 0); + } + } + else if (prog->Target == GL_FRAGMENT_PROGRAM_NV || + prog->Target == GL_FRAGMENT_PROGRAM_ARB) { + if (ctx->FragmentProgram.Current && + ctx->FragmentProgram.Current->Base.Id == ids[i]) { + /* unbind this currently bound program */ + _mesa_BindProgram(prog->Target, 0); + } + } + else { + _mesa_problem(ctx, "bad target in glDeleteProgramsNV"); + return; + } + /* Decrement reference count if not already marked for delete */ + if (!prog->DeletePending) { + prog->DeletePending = GL_TRUE; + prog->RefCount--; + } + if (prog->RefCount <= 0) { + _mesa_HashRemove(ctx->Shared->Programs, ids[i]); + ctx->Driver.DeleteProgram(ctx, prog); + } + } + } + } +} + + +/** + * Generate a list of new program identifiers. + * \note Not compiled into display lists. + * \note Called by both glGenProgramsNV and glGenProgramsARB. + */ +void GLAPIENTRY +_mesa_GenPrograms(GLsizei n, GLuint *ids) +{ + GLuint first; + GLuint i; + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END(ctx); + + if (n < 0) { + _mesa_error(ctx, GL_INVALID_VALUE, "glGenPrograms"); + return; + } + + if (!ids) + return; + + first = _mesa_HashFindFreeKeyBlock(ctx->Shared->Programs, n); + + /* Insert pointer to dummy program as placeholder */ + for (i = 0; i < (GLuint) n; i++) { + _mesa_HashInsert(ctx->Shared->Programs, first + i, &_mesa_DummyProgram); + } + + /* Return the program names */ + for (i = 0; i < (GLuint) n; i++) { + ids[i] = first + i; + } +} + + +/** + * Determine if id names a vertex or fragment program. + * \note Not compiled into display lists. + * \note Called from both glIsProgramNV and glIsProgramARB. + * \param id is the program identifier + * \return GL_TRUE if id is a program, else GL_FALSE. + */ +GLboolean GLAPIENTRY +_mesa_IsProgram(GLuint id) +{ + GET_CURRENT_CONTEXT(ctx); + ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE); + + if (id == 0) + return GL_FALSE; + + if (_mesa_HashLookup(ctx->Shared->Programs, id)) + return GL_TRUE; + else + return GL_FALSE; +} + + + +/**********************************************************************/ +/* GL_MESA_program_debug extension */ +/**********************************************************************/ + + +/* XXX temporary */ +void +glProgramCallbackMESA(GLenum target, GLprogramcallbackMESA callback, + GLvoid *data) +{ + _mesa_ProgramCallbackMESA(target, callback, data); +} + + +void +_mesa_ProgramCallbackMESA(GLenum target, GLprogramcallbackMESA callback, + GLvoid *data) +{ + GET_CURRENT_CONTEXT(ctx); + + switch (target) { + case GL_FRAGMENT_PROGRAM_ARB: + if (!ctx->Extensions.ARB_fragment_program) { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramCallbackMESA(target)"); + return; + } + ctx->FragmentProgram.Callback = callback; + ctx->FragmentProgram.CallbackData = data; + break; + case GL_FRAGMENT_PROGRAM_NV: + if (!ctx->Extensions.NV_fragment_program) { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramCallbackMESA(target)"); + return; + } + ctx->FragmentProgram.Callback = callback; + ctx->FragmentProgram.CallbackData = data; + break; + case GL_VERTEX_PROGRAM_ARB: /* == GL_VERTEX_PROGRAM_NV */ + if (!ctx->Extensions.ARB_vertex_program && + !ctx->Extensions.NV_vertex_program) { + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramCallbackMESA(target)"); + return; + } + ctx->VertexProgram.Callback = callback; + ctx->VertexProgram.CallbackData = data; + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, "glProgramCallbackMESA(target)"); + return; + } +} + + +/* XXX temporary */ +void +glGetProgramRegisterfvMESA(GLenum target, + GLsizei len, const GLubyte *registerName, + GLfloat *v) +{ + _mesa_GetProgramRegisterfvMESA(target, len, registerName, v); +} + + +void +_mesa_GetProgramRegisterfvMESA(GLenum target, + GLsizei len, const GLubyte *registerName, + GLfloat *v) +{ + char reg[1000]; + GET_CURRENT_CONTEXT(ctx); + + /* We _should_ be inside glBegin/glEnd */ +#if 0 + if (ctx->Driver.CurrentExecPrimitive == PRIM_OUTSIDE_BEGIN_END) { + _mesa_error(ctx, GL_INVALID_OPERATION, "glGetProgramRegisterfvMESA"); + return; + } +#endif + + /* make null-terminated copy of registerName */ + len = MIN2((unsigned int) len, sizeof(reg) - 1); + _mesa_memcpy(reg, registerName, len); + reg[len] = 0; + + switch (target) { + case GL_VERTEX_PROGRAM_NV: + if (!ctx->Extensions.ARB_vertex_program && + !ctx->Extensions.NV_vertex_program) { + _mesa_error(ctx, GL_INVALID_ENUM, + "glGetProgramRegisterfvMESA(target)"); + return; + } + if (!ctx->VertexProgram._Enabled) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glGetProgramRegisterfvMESA"); + return; + } + /* GL_NV_vertex_program */ + if (reg[0] == 'R') { + /* Temp register */ + GLint i = _mesa_atoi(reg + 1); + if (i >= (GLint)ctx->Const.MaxVertexProgramTemps) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + COPY_4V(v, ctx->VertexProgram.Temporaries[i]); + } + else if (reg[0] == 'v' && reg[1] == '[') { + /* Vertex Input attribute */ + GLuint i; + for (i = 0; i < ctx->Const.MaxVertexProgramAttribs; i++) { + const char *name = _mesa_nv_vertex_input_register_name(i); + char number[10]; + sprintf(number, "%d", i); + if (_mesa_strncmp(reg + 2, name, 4) == 0 || + _mesa_strncmp(reg + 2, number, _mesa_strlen(number)) == 0) { + COPY_4V(v, ctx->VertexProgram.Inputs[i]); + return; + } + } + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + else if (reg[0] == 'o' && reg[1] == '[') { + /* Vertex output attribute */ + } + /* GL_ARB_vertex_program */ + else if (_mesa_strncmp(reg, "vertex.", 7) == 0) { + + } + else { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + break; + case GL_FRAGMENT_PROGRAM_ARB: + if (!ctx->Extensions.ARB_fragment_program) { + _mesa_error(ctx, GL_INVALID_ENUM, + "glGetProgramRegisterfvMESA(target)"); + return; + } + if (!ctx->FragmentProgram._Enabled) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glGetProgramRegisterfvMESA"); + return; + } + /* XXX to do */ + break; + case GL_FRAGMENT_PROGRAM_NV: + if (!ctx->Extensions.NV_fragment_program) { + _mesa_error(ctx, GL_INVALID_ENUM, + "glGetProgramRegisterfvMESA(target)"); + return; + } + if (!ctx->FragmentProgram._Enabled) { + _mesa_error(ctx, GL_INVALID_OPERATION, + "glGetProgramRegisterfvMESA"); + return; + } + if (reg[0] == 'R') { + /* Temp register */ + GLint i = _mesa_atoi(reg + 1); + if (i >= (GLint)ctx->Const.MaxFragmentProgramTemps) { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + COPY_4V(v, ctx->FragmentProgram.Machine.Temporaries[i]); + } + else if (reg[0] == 'f' && reg[1] == '[') { + /* Fragment input attribute */ + GLuint i; + for (i = 0; i < ctx->Const.MaxFragmentProgramAttribs; i++) { + const char *name = _mesa_nv_fragment_input_register_name(i); + if (_mesa_strncmp(reg + 2, name, 4) == 0) { + COPY_4V(v, ctx->FragmentProgram.Machine.Inputs[i]); + return; + } + } + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + else if (_mesa_strcmp(reg, "o[COLR]") == 0) { + /* Fragment output color */ + COPY_4V(v, ctx->FragmentProgram.Machine.Outputs[FRAG_OUTPUT_COLR]); + } + else if (_mesa_strcmp(reg, "o[COLH]") == 0) { + /* Fragment output color */ + COPY_4V(v, ctx->FragmentProgram.Machine.Outputs[FRAG_OUTPUT_COLH]); + } + else if (_mesa_strcmp(reg, "o[DEPR]") == 0) { + /* Fragment output depth */ + COPY_4V(v, ctx->FragmentProgram.Machine.Outputs[FRAG_OUTPUT_DEPR]); + } + else { + /* try user-defined identifiers */ + const GLfloat *value = _mesa_lookup_parameter_value( + ctx->FragmentProgram.Current->Parameters, -1, reg); + if (value) { + COPY_4V(v, value); + } + else { + _mesa_error(ctx, GL_INVALID_VALUE, + "glGetProgramRegisterfvMESA(registerName)"); + return; + } + } + break; + default: + _mesa_error(ctx, GL_INVALID_ENUM, + "glGetProgramRegisterfvMESA(target)"); + return; + } + +} diff --git a/src/mesa/shader/program.h b/src/mesa/shader/program.h new file mode 100644 index 0000000..e8a667d --- /dev/null +++ b/src/mesa/shader/program.h @@ -0,0 +1,267 @@ +/* + * Mesa 3-D graphics library + * Version: 6.2 + * + * Copyright (C) 1999-2004 Brian Paul All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN + * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +/** + * \file program.c + * Vertex and fragment program support functions. + * \author Brian Paul + */ + + +/** + * \mainpage Mesa vertex and fragment program module + * + * This module or directory contains most of the code for vertex and + * fragment programs and shaders, including state management, parsers, + * and (some) software routines for executing programs + */ + +#ifndef PROGRAM_H +#define PROGRAM_H + +#include "mtypes.h" + + +/* for GL_ARB_v_p and GL_ARB_f_p SWZ instruction */ +#define SWIZZLE_X 0 +#define SWIZZLE_Y 1 +#define SWIZZLE_Z 2 +#define SWIZZLE_W 3 +#define SWIZZLE_ZERO 4 /* keep these values together: KW */ +#define SWIZZLE_ONE 5 /* keep these values together: KW */ + + +extern struct program _mesa_DummyProgram; + + +/* + * Internal functions + */ + +extern void +_mesa_init_program(GLcontext *ctx); + +extern void +_mesa_free_program_data(GLcontext *ctx); + +extern void +_mesa_set_program_error(GLcontext *ctx, GLint pos, const char *string); + +extern const GLubyte * +_mesa_find_line_column(const GLubyte *string, const GLubyte *pos, + GLint *line, GLint *col); + + +extern struct program * +_mesa_init_vertex_program( GLcontext *ctx, + struct vertex_program *prog, + GLenum target, + GLuint id ); + +extern struct program * +_mesa_init_fragment_program( GLcontext *ctx, + struct fragment_program *prog, + GLenum target, + GLuint id ); + +extern struct program * +_mesa_new_program(GLcontext *ctx, GLenum target, GLuint id); + +extern void +_mesa_delete_program(GLcontext *ctx, struct program *prog); + + + +/* + * Used for describing GL state referenced from inside ARB vertex and + * fragment programs. + * A string such as "state.light[0].ambient" gets translated into a + * sequence of tokens such as [ STATE_LIGHT, 0, STATE_AMBIENT ]. + */ +enum state_index { + STATE_MATERIAL, + + STATE_LIGHT, + STATE_LIGHTMODEL_AMBIENT, + STATE_LIGHTMODEL_SCENECOLOR, + STATE_LIGHTPROD, + + STATE_TEXGEN, + + STATE_FOG_COLOR, + STATE_FOG_PARAMS, + + STATE_CLIPPLANE, + + STATE_POINT_SIZE, + STATE_POINT_ATTENUATION, + + STATE_MATRIX, + STATE_MODELVIEW, + STATE_PROJECTION, + STATE_MVP, + STATE_TEXTURE, + STATE_PROGRAM, + STATE_MATRIX_INVERSE, + STATE_MATRIX_TRANSPOSE, + STATE_MATRIX_INVTRANS, + + STATE_AMBIENT, + STATE_DIFFUSE, + STATE_SPECULAR, + STATE_EMISSION, + STATE_SHININESS, + STATE_HALF, + + STATE_POSITION, + STATE_ATTENUATION, + STATE_SPOT_DIRECTION, + + STATE_TEXGEN_EYE_S, + STATE_TEXGEN_EYE_T, + STATE_TEXGEN_EYE_R, + STATE_TEXGEN_EYE_Q, + STATE_TEXGEN_OBJECT_S, + STATE_TEXGEN_OBJECT_T, + STATE_TEXGEN_OBJECT_R, + STATE_TEXGEN_OBJECT_Q, + + STATE_TEXENV_COLOR, + + STATE_DEPTH_RANGE, + + STATE_VERTEX_PROGRAM, + STATE_FRAGMENT_PROGRAM, + + STATE_ENV, + STATE_LOCAL +}; + + + +/* + * Named program parameters + * Used for NV_fragment_program "DEFINE"d constants and "DECLARE"d parameters, + * and ARB_fragment_program global state references. For the later, Name + * might be "state.light[0].diffuse", for example. + */ + +enum parameter_type +{ + NAMED_PARAMETER, + CONSTANT, + STATE +}; + + +struct program_parameter +{ + const char *Name; /* Null-terminated */ + enum parameter_type Type; + enum state_index StateIndexes[6]; /* Global state reference */ + GLfloat Values[4]; +}; + + +struct program_parameter_list +{ + GLuint NumParameters; + struct program_parameter *Parameters; +}; + + +/* + * Program parameter functions + */ + +extern struct program_parameter_list * +_mesa_new_parameter_list(void); + +extern void +_mesa_free_parameter_list(struct program_parameter_list *paramList); + +extern void +_mesa_free_parameters(struct program_parameter_list *paramList); + +extern GLint +_mesa_add_named_parameter(struct program_parameter_list *paramList, + const char *name, const GLfloat values[4]); + +extern GLint +_mesa_add_named_constant(struct program_parameter_list *paramList, + const char *name, const GLfloat values[4]); + +extern GLint +_mesa_add_unnamed_constant(struct program_parameter_list *paramList, + const GLfloat values[4]); + +extern GLint +_mesa_add_state_reference(struct program_parameter_list *paramList, + GLint *stateTokens); + +extern GLfloat * +_mesa_lookup_parameter_value(struct program_parameter_list *paramList, + GLsizei nameLen, const char *name); + +extern GLint +_mesa_lookup_parameter_index(struct program_parameter_list *paramList, + GLsizei nameLen, const char *name); + +extern void +_mesa_load_state_parameters(GLcontext *ctx, + struct program_parameter_list *paramList); + + +/* + * API functions + */ + +extern void GLAPIENTRY +_mesa_BindProgram(GLenum target, GLuint id); + +extern void GLAPIENTRY +_mesa_DeletePrograms(GLsizei n, const GLuint *ids); + +extern void GLAPIENTRY +_mesa_GenPrograms(GLsizei n, GLuint *ids); + +extern GLboolean GLAPIENTRY +_mesa_IsProgram(GLuint id); + + + +/* + * GL_MESA_program_debug + */ + +extern void +_mesa_ProgramCallbackMESA(GLenum target, GLprogramcallbackMESA callback, + GLvoid *data); + +extern void +_mesa_GetProgramRegisterfvMESA(GLenum target, GLsizei len, + const GLubyte *registerName, GLfloat *v); + + +#endif /* PROGRAM_H */ diff --git a/src/mesa/shader/shader.dsp b/src/mesa/shader/shader.dsp new file mode 100644 index 0000000..fa5e557 --- /dev/null +++ b/src/mesa/shader/shader.dsp @@ -0,0 +1,197 @@ +# Microsoft Developer Studio Project File - Name="shader" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Static Library" 0x0104 + +CFG=shader - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "shader.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "shader.mak" CFG="shader - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "shader - Win32 Release" (based on "Win32 (x86) Static Library") +!MESSAGE "shader - Win32 Debug" (based on "Win32 (x86) Static Library") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "shader - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "Release" +# PROP BASE Intermediate_Dir "Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "Release" +# PROP Intermediate_Dir "Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /I "../../../include" /I "../" /I "../main" /I "../glapi" /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /Zm500 /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ELSEIF "$(CFG)" == "shader - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "Debug" +# PROP BASE Intermediate_Dir "Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "Debug" +# PROP Intermediate_Dir "Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../../../include" /I "../" /I "../main" /I "../glapi" /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /Zm500 /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LIB32=link.exe -lib +# ADD BASE LIB32 /nologo +# ADD LIB32 /nologo + +!ENDIF + +# Begin Target + +# Name "shader - Win32 Release" +# Name "shader - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=.\arbfragparse.c +# End Source File +# Begin Source File + +SOURCE=.\arbprogparse.c +# End Source File +# Begin Source File + +SOURCE=.\arbprogram.c +# End Source File +# Begin Source File + +SOURCE=.\arbvertparse.c +# End Source File +# Begin Source File + +SOURCE=.\grammar.c +# PROP Exclude_From_Build 1 +# End Source File +# Begin Source File + +SOURCE=.\grammar_mesa.c +# End Source File +# Begin Source File + +SOURCE=.\nvfragparse.c +# End Source File +# Begin Source File + +SOURCE=.\nvprogram.c +# End Source File +# Begin Source File + +SOURCE=.\nvvertexec.c +# End Source File +# Begin Source File + +SOURCE=.\nvvertparse.c +# End Source File +# Begin Source File + +SOURCE=.\program.c +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# Begin Source File + +SOURCE=.\arbfragparse.h +# End Source File +# Begin Source File + +SOURCE=.\arbprogparse.h +# End Source File +# Begin Source File + +SOURCE=.\arbprogram.h +# End Source File +# Begin Source File + +SOURCE=.\arbprogram_syn.h +# End Source File +# Begin Source File + +SOURCE=.\arbvertparse.h +# End Source File +# Begin Source File + +SOURCE=.\grammar.h +# End Source File +# Begin Source File + +SOURCE=.\grammar_mesa.h +# End Source File +# Begin Source File + +SOURCE=.\grammar_syn.h +# End Source File +# Begin Source File + +SOURCE=.\nvfragparse.h +# End Source File +# Begin Source File + +SOURCE=.\nvfragprog.h +# End Source File +# Begin Source File + +SOURCE=.\nvprogram.h +# End Source File +# Begin Source File + +SOURCE=.\nvvertexec.h +# End Source File +# Begin Source File + +SOURCE=.\nvvertparse.h +# End Source File +# Begin Source File + +SOURCE=.\nvvertprog.h +# End Source File +# Begin Source File + +SOURCE=.\program.h +# End Source File +# End Group +# End Target +# End Project -- cgit