aboutsummaryrefslogtreecommitdiff
path: root/mesalib/src
diff options
context:
space:
mode:
Diffstat (limited to 'mesalib/src')
-rw-r--r--mesalib/src/glsl/ast.h4
-rw-r--r--mesalib/src/glsl/ast_expr.cpp190
-rw-r--r--mesalib/src/glsl/ast_to_hir.cpp6926
-rw-r--r--mesalib/src/glsl/ast_type.cpp276
-rw-r--r--mesalib/src/glsl/getopt.cpp552
-rw-r--r--mesalib/src/glsl/glcpp/glcpp.c8
-rw-r--r--mesalib/src/glsl/glsl_parser_extras.cpp1652
-rw-r--r--mesalib/src/glsl/glsl_parser_extras.h558
-rw-r--r--mesalib/src/glsl/glsl_symbol_table.cpp4
-rw-r--r--mesalib/src/glsl/glsl_symbol_table.h5
-rw-r--r--mesalib/src/glsl/glsl_types.cpp994
-rw-r--r--mesalib/src/glsl/glsl_types.h952
-rw-r--r--mesalib/src/glsl/hir_field_selection.cpp204
-rw-r--r--mesalib/src/glsl/ir.h3280
-rw-r--r--mesalib/src/glsl/ir_constant_expression.cpp2744
-rw-r--r--mesalib/src/glsl/ir_import_prototypes.cpp244
-rw-r--r--mesalib/src/glsl/ir_print_visitor.cpp942
-rw-r--r--mesalib/src/glsl/ir_validate.cpp1058
-rw-r--r--mesalib/src/glsl/link_functions.cpp532
-rw-r--r--mesalib/src/glsl/linker.cpp3418
-rw-r--r--mesalib/src/glsl/list.h8
-rw-r--r--mesalib/src/glsl/loop_controls.cpp608
-rw-r--r--mesalib/src/glsl/lower_mat_op_to_vec.cpp980
-rw-r--r--mesalib/src/glsl/main.cpp679
-rw-r--r--mesalib/src/glsl/opt_constant_propagation.cpp868
-rw-r--r--mesalib/src/glsl/opt_constant_variable.cpp390
-rw-r--r--mesalib/src/glsl/opt_dead_code.cpp284
-rw-r--r--mesalib/src/glsl/opt_dead_code_local.cpp444
-rw-r--r--mesalib/src/glsl/opt_dead_functions.cpp306
-rw-r--r--mesalib/src/glsl/opt_structure_splitting.cpp722
-rw-r--r--mesalib/src/glsl/opt_swizzle_swizzle.cpp186
-rw-r--r--mesalib/src/glsl/opt_tree_grafting.cpp736
-rw-r--r--mesalib/src/glsl/s_expression.cpp366
-rw-r--r--mesalib/src/mapi/glapi/gen/gen.bat20
-rw-r--r--mesalib/src/mapi/glapi/gen/gl_API.xml596
-rw-r--r--mesalib/src/mapi/glapi/glapi.h31
-rw-r--r--mesalib/src/mapi/glapi/glapi_getproc.c11
-rw-r--r--mesalib/src/mapi/glapi/glapi_nop.c4
-rw-r--r--mesalib/src/mapi/glapi/glthread.c2
-rw-r--r--mesalib/src/mesa/drivers/dri/Makefile.template222
-rw-r--r--mesalib/src/mesa/drivers/dri/common/dri_util.c2060
-rw-r--r--mesalib/src/mesa/drivers/dri/common/dri_util.h1126
-rw-r--r--mesalib/src/mesa/drivers/dri/common/utils.c2
-rw-r--r--mesalib/src/mesa/drivers/dri/swrast/swrast.c1617
-rw-r--r--mesalib/src/mesa/drivers/dri/swrast/swrast_priv.h7
-rw-r--r--mesalib/src/mesa/drivers/windows/gdi/wmesa.c3324
-rw-r--r--mesalib/src/mesa/drivers/windows/gldirect/dglcontext.c4424
-rw-r--r--mesalib/src/mesa/main/api_arrayelt.c2
-rw-r--r--mesalib/src/mesa/main/api_exec.c1
-rw-r--r--mesalib/src/mesa/main/blend.c1644
-rw-r--r--mesalib/src/mesa/main/bufferobj.c4316
-rw-r--r--mesalib/src/mesa/main/compiler.h24
-rw-r--r--mesalib/src/mesa/main/context.c3764
-rw-r--r--mesalib/src/mesa/main/context.h626
-rw-r--r--mesalib/src/mesa/main/depth.c348
-rw-r--r--mesalib/src/mesa/main/dlist.c20664
-rw-r--r--mesalib/src/mesa/main/dlopen.c6
-rw-r--r--mesalib/src/mesa/main/hint.c294
-rw-r--r--mesalib/src/mesa/main/imports.c2056
-rw-r--r--mesalib/src/mesa/main/imports.h1242
-rw-r--r--mesalib/src/mesa/main/lines.c234
-rw-r--r--mesalib/src/mesa/main/queryobj.c1246
-rw-r--r--mesalib/src/mesa/main/shaderapi.c3884
-rw-r--r--mesalib/src/mesa/main/state.c1468
-rw-r--r--mesalib/src/mesa/main/stencil.c1228
-rw-r--r--mesalib/src/mesa/main/syncobj.c12
-rw-r--r--mesalib/src/mesa/main/syncobj.h12
-rw-r--r--mesalib/src/mesa/main/texcompress_s3tc.c4
-rw-r--r--mesalib/src/mesa/program/sampler.cpp274
-rw-r--r--mesalib/src/mesa/state_tracker/st_atom_blend.c604
-rw-r--r--mesalib/src/mesa/state_tracker/st_atom_framebuffer.c364
-rw-r--r--mesalib/src/mesa/state_tracker/st_atom_sampler.c456
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_bitmap.c1786
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_bufferobjects.c936
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_clear.c1158
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_drawtex.c614
-rw-r--r--mesalib/src/mesa/state_tracker/st_cb_texture.c3836
-rw-r--r--mesalib/src/mesa/state_tracker/st_context.c594
-rw-r--r--mesalib/src/mesa/state_tracker/st_context.h540
-rw-r--r--mesalib/src/mesa/state_tracker/st_draw.c1518
-rw-r--r--mesalib/src/mesa/state_tracker/st_draw_feedback.c554
-rw-r--r--mesalib/src/mesa/state_tracker/st_format.c2298
-rw-r--r--mesalib/src/mesa/state_tracker/st_format.h172
-rw-r--r--mesalib/src/mesa/state_tracker/st_gen_mipmap.c844
-rw-r--r--mesalib/src/mesa/state_tracker/st_program.c2330
-rw-r--r--mesalib/src/mesa/tnl/t_draw.c1068
-rw-r--r--mesalib/src/mesa/vbo/vbo.h350
-rw-r--r--mesalib/src/mesa/vbo/vbo_exec.h402
-rw-r--r--mesalib/src/mesa/vbo/vbo_exec_api.c2208
-rw-r--r--mesalib/src/mesa/vbo/vbo_exec_array.c2648
-rw-r--r--mesalib/src/mesa/vbo/vbo_exec_draw.c852
-rw-r--r--mesalib/src/mesa/vbo/vbo_save_draw.c610
92 files changed, 57636 insertions, 57021 deletions
diff --git a/mesalib/src/glsl/ast.h b/mesalib/src/glsl/ast.h
index 878f48b20..6963b83af 100644
--- a/mesalib/src/glsl/ast.h
+++ b/mesalib/src/glsl/ast.h
@@ -63,6 +63,10 @@ public:
/* If the user *does* call delete, that's OK, we will just
* ralloc_free in that case. */
+ static void operator delete(void *table, void *ctx)
+ {
+ ralloc_free(table);
+ }
static void operator delete(void *table)
{
ralloc_free(table);
diff --git a/mesalib/src/glsl/ast_expr.cpp b/mesalib/src/glsl/ast_expr.cpp
index e624d11cf..e8812e7a1 100644
--- a/mesalib/src/glsl/ast_expr.cpp
+++ b/mesalib/src/glsl/ast_expr.cpp
@@ -1,95 +1,95 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-#include <assert.h>
-#include "ast.h"
-
-const char *
-ast_expression::operator_string(enum ast_operators op)
-{
- static const char *const operators[] = {
- "=",
- "+",
- "-",
- "+",
- "-",
- "*",
- "/",
- "%",
- "<<",
- ">>",
- "<",
- ">",
- "<=",
- ">=",
- "==",
- "!=",
- "&",
- "^",
- "|",
- "~",
- "&&",
- "^^",
- "||",
- "!",
-
- "*=",
- "/=",
- "%=",
- "+=",
- "-=",
- "<<=",
- ">>=",
- "&=",
- "^=",
- "|=",
-
- "?:",
-
- "++",
- "--",
- "++",
- "--",
- ".",
- };
-
- assert((unsigned int)op < sizeof(operators) / sizeof(operators[0]));
-
- return operators[op];
-}
-
-
-ast_expression_bin::ast_expression_bin(int oper, ast_expression *ex0,
- ast_expression *ex1) :
- ast_expression(oper, ex0, ex1, NULL)
-{
- assert((oper >= ast_plus) && (oper <= ast_logic_not));
-}
-
-
-void
-ast_expression_bin::print(void) const
-{
- subexpressions[0]->print();
- printf("%s ", operator_string(oper));
- subexpressions[1]->print();
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+#include <assert.h>
+#include "ast.h"
+
+const char *
+ast_expression::operator_string(enum ast_operators op)
+{
+ static const char *const operators[] = {
+ "=",
+ "+",
+ "-",
+ "+",
+ "-",
+ "*",
+ "/",
+ "%",
+ "<<",
+ ">>",
+ "<",
+ ">",
+ "<=",
+ ">=",
+ "==",
+ "!=",
+ "&",
+ "^",
+ "|",
+ "~",
+ "&&",
+ "^^",
+ "||",
+ "!",
+
+ "*=",
+ "/=",
+ "%=",
+ "+=",
+ "-=",
+ "<<=",
+ ">>=",
+ "&=",
+ "^=",
+ "|=",
+
+ "?:",
+
+ "++",
+ "--",
+ "++",
+ "--",
+ ".",
+ };
+
+ assert((unsigned int)op < sizeof(operators) / sizeof(operators[0]));
+
+ return operators[op];
+}
+
+
+ast_expression_bin::ast_expression_bin(int oper, ast_expression *ex0,
+ ast_expression *ex1) :
+ ast_expression(oper, ex0, ex1, NULL)
+{
+ assert((oper >= ast_plus) && (oper <= ast_logic_not));
+}
+
+
+void
+ast_expression_bin::print(void) const
+{
+ subexpressions[0]->print();
+ printf("%s ", operator_string(oper));
+ subexpressions[1]->print();
+}
diff --git a/mesalib/src/glsl/ast_to_hir.cpp b/mesalib/src/glsl/ast_to_hir.cpp
index bef099cca..27c4301a0 100644
--- a/mesalib/src/glsl/ast_to_hir.cpp
+++ b/mesalib/src/glsl/ast_to_hir.cpp
@@ -1,3463 +1,3463 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 ast_to_hir.c
- * Convert abstract syntax to to high-level intermediate reprensentation (HIR).
- *
- * During the conversion to HIR, the majority of the symantic checking is
- * preformed on the program. This includes:
- *
- * * Symbol table management
- * * Type checking
- * * Function binding
- *
- * The majority of this work could be done during parsing, and the parser could
- * probably generate HIR directly. However, this results in frequent changes
- * to the parser code. Since we do not assume that every system this complier
- * is built on will have Flex and Bison installed, we have to store the code
- * generated by these tools in our version control system. In other parts of
- * the system we've seen problems where a parser was changed but the generated
- * code was not committed, merge conflicts where created because two developers
- * had slightly different versions of Bison installed, etc.
- *
- * I have also noticed that running Bison generated parsers in GDB is very
- * irritating. When you get a segfault on '$$ = $1->foo', you can't very
- * well 'print $1' in GDB.
- *
- * As a result, my preference is to put as little C code as possible in the
- * parser (and lexer) sources.
- */
-
-#include "main/core.h" /* for struct gl_extensions */
-#include "glsl_symbol_table.h"
-#include "glsl_parser_extras.h"
-#include "ast.h"
-#include "glsl_types.h"
-#include "ir.h"
-
-void
-_mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
-{
- _mesa_glsl_initialize_variables(instructions, state);
- _mesa_glsl_initialize_functions(state);
-
- state->symbols->language_version = state->language_version;
-
- state->current_function = NULL;
-
- /* Section 4.2 of the GLSL 1.20 specification states:
- * "The built-in functions are scoped in a scope outside the global scope
- * users declare global variables in. That is, a shader's global scope,
- * available for user-defined functions and global variables, is nested
- * inside the scope containing the built-in functions."
- *
- * Since built-in functions like ftransform() access built-in variables,
- * it follows that those must be in the outer scope as well.
- *
- * We push scope here to create this nesting effect...but don't pop.
- * This way, a shader's globals are still in the symbol table for use
- * by the linker.
- */
- state->symbols->push_scope();
-
- foreach_list_typed (ast_node, ast, link, & state->translation_unit)
- ast->hir(instructions, state);
-}
-
-
-/**
- * If a conversion is available, convert one operand to a different type
- *
- * The \c from \c ir_rvalue is converted "in place".
- *
- * \param to Type that the operand it to be converted to
- * \param from Operand that is being converted
- * \param state GLSL compiler state
- *
- * \return
- * If a conversion is possible (or unnecessary), \c true is returned.
- * Otherwise \c false is returned.
- */
-bool
-apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- if (to->base_type == from->type->base_type)
- return true;
-
- /* This conversion was added in GLSL 1.20. If the compilation mode is
- * GLSL 1.10, the conversion is skipped.
- */
- if (state->language_version < 120)
- return false;
-
- /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
- *
- * "There are no implicit array or structure conversions. For
- * example, an array of int cannot be implicitly converted to an
- * array of float. There are no implicit conversions between
- * signed and unsigned integers."
- */
- /* FINISHME: The above comment is partially a lie. There is int/uint
- * FINISHME: conversion for immediate constants.
- */
- if (!to->is_float() || !from->type->is_numeric())
- return false;
-
- /* Convert to a floating point type with the same number of components
- * as the original type - i.e. int to float, not int to vec4.
- */
- to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
- from->type->matrix_columns);
-
- switch (from->type->base_type) {
- case GLSL_TYPE_INT:
- from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
- break;
- case GLSL_TYPE_UINT:
- from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
- break;
- case GLSL_TYPE_BOOL:
- from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
- break;
- default:
- assert(0);
- }
-
- return true;
-}
-
-
-static const struct glsl_type *
-arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
- bool multiply,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- const glsl_type *type_a = value_a->type;
- const glsl_type *type_b = value_b->type;
-
- /* From GLSL 1.50 spec, page 56:
- *
- * "The arithmetic binary operators add (+), subtract (-),
- * multiply (*), and divide (/) operate on integer and
- * floating-point scalars, vectors, and matrices."
- */
- if (!type_a->is_numeric() || !type_b->is_numeric()) {
- _mesa_glsl_error(loc, state,
- "Operands to arithmetic operators must be numeric");
- return glsl_type::error_type;
- }
-
-
- /* "If one operand is floating-point based and the other is
- * not, then the conversions from Section 4.1.10 "Implicit
- * Conversions" are applied to the non-floating-point-based operand."
- */
- if (!apply_implicit_conversion(type_a, value_b, state)
- && !apply_implicit_conversion(type_b, value_a, state)) {
- _mesa_glsl_error(loc, state,
- "Could not implicitly convert operands to "
- "arithmetic operator");
- return glsl_type::error_type;
- }
- type_a = value_a->type;
- type_b = value_b->type;
-
- /* "If the operands are integer types, they must both be signed or
- * both be unsigned."
- *
- * From this rule and the preceeding conversion it can be inferred that
- * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
- * The is_numeric check above already filtered out the case where either
- * type is not one of these, so now the base types need only be tested for
- * equality.
- */
- if (type_a->base_type != type_b->base_type) {
- _mesa_glsl_error(loc, state,
- "base type mismatch for arithmetic operator");
- return glsl_type::error_type;
- }
-
- /* "All arithmetic binary operators result in the same fundamental type
- * (signed integer, unsigned integer, or floating-point) as the
- * operands they operate on, after operand type conversion. After
- * conversion, the following cases are valid
- *
- * * The two operands are scalars. In this case the operation is
- * applied, resulting in a scalar."
- */
- if (type_a->is_scalar() && type_b->is_scalar())
- return type_a;
-
- /* "* One operand is a scalar, and the other is a vector or matrix.
- * In this case, the scalar operation is applied independently to each
- * component of the vector or matrix, resulting in the same size
- * vector or matrix."
- */
- if (type_a->is_scalar()) {
- if (!type_b->is_scalar())
- return type_b;
- } else if (type_b->is_scalar()) {
- return type_a;
- }
-
- /* All of the combinations of <scalar, scalar>, <vector, scalar>,
- * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
- * handled.
- */
- assert(!type_a->is_scalar());
- assert(!type_b->is_scalar());
-
- /* "* The two operands are vectors of the same size. In this case, the
- * operation is done component-wise resulting in the same size
- * vector."
- */
- if (type_a->is_vector() && type_b->is_vector()) {
- if (type_a == type_b) {
- return type_a;
- } else {
- _mesa_glsl_error(loc, state,
- "vector size mismatch for arithmetic operator");
- return glsl_type::error_type;
- }
- }
-
- /* All of the combinations of <scalar, scalar>, <vector, scalar>,
- * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
- * <vector, vector> have been handled. At least one of the operands must
- * be matrix. Further, since there are no integer matrix types, the base
- * type of both operands must be float.
- */
- assert(type_a->is_matrix() || type_b->is_matrix());
- assert(type_a->base_type == GLSL_TYPE_FLOAT);
- assert(type_b->base_type == GLSL_TYPE_FLOAT);
-
- /* "* The operator is add (+), subtract (-), or divide (/), and the
- * operands are matrices with the same number of rows and the same
- * number of columns. In this case, the operation is done component-
- * wise resulting in the same size matrix."
- * * The operator is multiply (*), where both operands are matrices or
- * one operand is a vector and the other a matrix. A right vector
- * operand is treated as a column vector and a left vector operand as a
- * row vector. In all these cases, it is required that the number of
- * columns of the left operand is equal to the number of rows of the
- * right operand. Then, the multiply (*) operation does a linear
- * algebraic multiply, yielding an object that has the same number of
- * rows as the left operand and the same number of columns as the right
- * operand. Section 5.10 "Vector and Matrix Operations" explains in
- * more detail how vectors and matrices are operated on."
- */
- if (! multiply) {
- if (type_a == type_b)
- return type_a;
- } else {
- if (type_a->is_matrix() && type_b->is_matrix()) {
- /* Matrix multiply. The columns of A must match the rows of B. Given
- * the other previously tested constraints, this means the vector type
- * of a row from A must be the same as the vector type of a column from
- * B.
- */
- if (type_a->row_type() == type_b->column_type()) {
- /* The resulting matrix has the number of columns of matrix B and
- * the number of rows of matrix A. We get the row count of A by
- * looking at the size of a vector that makes up a column. The
- * transpose (size of a row) is done for B.
- */
- const glsl_type *const type =
- glsl_type::get_instance(type_a->base_type,
- type_a->column_type()->vector_elements,
- type_b->row_type()->vector_elements);
- assert(type != glsl_type::error_type);
-
- return type;
- }
- } else if (type_a->is_matrix()) {
- /* A is a matrix and B is a column vector. Columns of A must match
- * rows of B. Given the other previously tested constraints, this
- * means the vector type of a row from A must be the same as the
- * vector the type of B.
- */
- if (type_a->row_type() == type_b) {
- /* The resulting vector has a number of elements equal to
- * the number of rows of matrix A. */
- const glsl_type *const type =
- glsl_type::get_instance(type_a->base_type,
- type_a->column_type()->vector_elements,
- 1);
- assert(type != glsl_type::error_type);
-
- return type;
- }
- } else {
- assert(type_b->is_matrix());
-
- /* A is a row vector and B is a matrix. Columns of A must match rows
- * of B. Given the other previously tested constraints, this means
- * the type of A must be the same as the vector type of a column from
- * B.
- */
- if (type_a == type_b->column_type()) {
- /* The resulting vector has a number of elements equal to
- * the number of columns of matrix B. */
- const glsl_type *const type =
- glsl_type::get_instance(type_a->base_type,
- type_b->row_type()->vector_elements,
- 1);
- assert(type != glsl_type::error_type);
-
- return type;
- }
- }
-
- _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
- return glsl_type::error_type;
- }
-
-
- /* "All other cases are illegal."
- */
- _mesa_glsl_error(loc, state, "type mismatch");
- return glsl_type::error_type;
-}
-
-
-static const struct glsl_type *
-unary_arithmetic_result_type(const struct glsl_type *type,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- /* From GLSL 1.50 spec, page 57:
- *
- * "The arithmetic unary operators negate (-), post- and pre-increment
- * and decrement (-- and ++) operate on integer or floating-point
- * values (including vectors and matrices). All unary operators work
- * component-wise on their operands. These result with the same type
- * they operated on."
- */
- if (!type->is_numeric()) {
- _mesa_glsl_error(loc, state,
- "Operands to arithmetic operators must be numeric");
- return glsl_type::error_type;
- }
-
- return type;
-}
-
-/**
- * \brief Return the result type of a bit-logic operation.
- *
- * If the given types to the bit-logic operator are invalid, return
- * glsl_type::error_type.
- *
- * \param type_a Type of LHS of bit-logic op
- * \param type_b Type of RHS of bit-logic op
- */
-static const struct glsl_type *
-bit_logic_result_type(const struct glsl_type *type_a,
- const struct glsl_type *type_b,
- ast_operators op,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- if (state->language_version < 130) {
- _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
- return glsl_type::error_type;
- }
-
- /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
- *
- * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
- * (|). The operands must be of type signed or unsigned integers or
- * integer vectors."
- */
- if (!type_a->is_integer()) {
- _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
- ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
- if (!type_b->is_integer()) {
- _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
- ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* "The fundamental types of the operands (signed or unsigned) must
- * match,"
- */
- if (type_a->base_type != type_b->base_type) {
- _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
- "base type", ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* "The operands cannot be vectors of differing size." */
- if (type_a->is_vector() &&
- type_b->is_vector() &&
- type_a->vector_elements != type_b->vector_elements) {
- _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
- "different sizes", ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* "If one operand is a scalar and the other a vector, the scalar is
- * applied component-wise to the vector, resulting in the same type as
- * the vector. The fundamental types of the operands [...] will be the
- * resulting fundamental type."
- */
- if (type_a->is_scalar())
- return type_b;
- else
- return type_a;
-}
-
-static const struct glsl_type *
-modulus_result_type(const struct glsl_type *type_a,
- const struct glsl_type *type_b,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- if (state->language_version < 130) {
- _mesa_glsl_error(loc, state,
- "operator '%%' is reserved in %s",
- state->version_string);
- return glsl_type::error_type;
- }
-
- /* From GLSL 1.50 spec, page 56:
- * "The operator modulus (%) operates on signed or unsigned integers or
- * integer vectors. The operand types must both be signed or both be
- * unsigned."
- */
- if (!type_a->is_integer() || !type_b->is_integer()
- || (type_a->base_type != type_b->base_type)) {
- _mesa_glsl_error(loc, state, "type mismatch");
- return glsl_type::error_type;
- }
-
- /* "The operands cannot be vectors of differing size. If one operand is
- * a scalar and the other vector, then the scalar is applied component-
- * wise to the vector, resulting in the same type as the vector. If both
- * are vectors of the same size, the result is computed component-wise."
- */
- if (type_a->is_vector()) {
- if (!type_b->is_vector()
- || (type_a->vector_elements == type_b->vector_elements))
- return type_a;
- } else
- return type_b;
-
- /* "The operator modulus (%) is not defined for any other data types
- * (non-integer types)."
- */
- _mesa_glsl_error(loc, state, "type mismatch");
- return glsl_type::error_type;
-}
-
-
-static const struct glsl_type *
-relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- const glsl_type *type_a = value_a->type;
- const glsl_type *type_b = value_b->type;
-
- /* From GLSL 1.50 spec, page 56:
- * "The relational operators greater than (>), less than (<), greater
- * than or equal (>=), and less than or equal (<=) operate only on
- * scalar integer and scalar floating-point expressions."
- */
- if (!type_a->is_numeric()
- || !type_b->is_numeric()
- || !type_a->is_scalar()
- || !type_b->is_scalar()) {
- _mesa_glsl_error(loc, state,
- "Operands to relational operators must be scalar and "
- "numeric");
- return glsl_type::error_type;
- }
-
- /* "Either the operands' types must match, or the conversions from
- * Section 4.1.10 "Implicit Conversions" will be applied to the integer
- * operand, after which the types must match."
- */
- if (!apply_implicit_conversion(type_a, value_b, state)
- && !apply_implicit_conversion(type_b, value_a, state)) {
- _mesa_glsl_error(loc, state,
- "Could not implicitly convert operands to "
- "relational operator");
- return glsl_type::error_type;
- }
- type_a = value_a->type;
- type_b = value_b->type;
-
- if (type_a->base_type != type_b->base_type) {
- _mesa_glsl_error(loc, state, "base type mismatch");
- return glsl_type::error_type;
- }
-
- /* "The result is scalar Boolean."
- */
- return glsl_type::bool_type;
-}
-
-/**
- * \brief Return the result type of a bit-shift operation.
- *
- * If the given types to the bit-shift operator are invalid, return
- * glsl_type::error_type.
- *
- * \param type_a Type of LHS of bit-shift op
- * \param type_b Type of RHS of bit-shift op
- */
-static const struct glsl_type *
-shift_result_type(const struct glsl_type *type_a,
- const struct glsl_type *type_b,
- ast_operators op,
- struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
-{
- if (state->language_version < 130) {
- _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
- return glsl_type::error_type;
- }
-
- /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
- *
- * "The shift operators (<<) and (>>). For both operators, the operands
- * must be signed or unsigned integers or integer vectors. One operand
- * can be signed while the other is unsigned."
- */
- if (!type_a->is_integer()) {
- _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
- "integer vector", ast_expression::operator_string(op));
- return glsl_type::error_type;
-
- }
- if (!type_b->is_integer()) {
- _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
- "integer vector", ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* "If the first operand is a scalar, the second operand has to be
- * a scalar as well."
- */
- if (type_a->is_scalar() && !type_b->is_scalar()) {
- _mesa_glsl_error(loc, state, "If the first operand of %s is scalar, the "
- "second must be scalar as well",
- ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* If both operands are vectors, check that they have same number of
- * elements.
- */
- if (type_a->is_vector() &&
- type_b->is_vector() &&
- type_a->vector_elements != type_b->vector_elements) {
- _mesa_glsl_error(loc, state, "Vector operands to operator %s must "
- "have same number of elements",
- ast_expression::operator_string(op));
- return glsl_type::error_type;
- }
-
- /* "In all cases, the resulting type will be the same type as the left
- * operand."
- */
- return type_a;
-}
-
-/**
- * Validates that a value can be assigned to a location with a specified type
- *
- * Validates that \c rhs can be assigned to some location. If the types are
- * not an exact match but an automatic conversion is possible, \c rhs will be
- * converted.
- *
- * \return
- * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
- * Otherwise the actual RHS to be assigned will be returned. This may be
- * \c rhs, or it may be \c rhs after some type conversion.
- *
- * \note
- * In addition to being used for assignments, this function is used to
- * type-check return values.
- */
-ir_rvalue *
-validate_assignment(struct _mesa_glsl_parse_state *state,
- const glsl_type *lhs_type, ir_rvalue *rhs)
-{
- /* If there is already some error in the RHS, just return it. Anything
- * else will lead to an avalanche of error message back to the user.
- */
- if (rhs->type->is_error())
- return rhs;
-
- /* If the types are identical, the assignment can trivially proceed.
- */
- if (rhs->type == lhs_type)
- return rhs;
-
- /* If the array element types are the same and the size of the LHS is zero,
- * the assignment is okay.
- *
- * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
- * is handled by ir_dereference::is_lvalue.
- */
- if (lhs_type->is_array() && rhs->type->is_array()
- && (lhs_type->element_type() == rhs->type->element_type())
- && (lhs_type->array_size() == 0)) {
- return rhs;
- }
-
- /* Check for implicit conversion in GLSL 1.20 */
- if (apply_implicit_conversion(lhs_type, rhs, state)) {
- if (rhs->type == lhs_type)
- return rhs;
- }
-
- return NULL;
-}
-
-ir_rvalue *
-do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
- ir_rvalue *lhs, ir_rvalue *rhs,
- YYLTYPE lhs_loc)
-{
- void *ctx = state;
- bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
-
- if (!error_emitted) {
- if (lhs->variable_referenced() != NULL
- && lhs->variable_referenced()->read_only) {
- _mesa_glsl_error(&lhs_loc, state,
- "assignment to read-only variable '%s'",
- lhs->variable_referenced()->name);
- error_emitted = true;
-
- } else if (!lhs->is_lvalue()) {
- _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
- error_emitted = true;
- }
-
- if (state->es_shader && lhs->type->is_array()) {
- _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
- "allowed in GLSL ES 1.00.");
- error_emitted = true;
- }
- }
-
- ir_rvalue *new_rhs = validate_assignment(state, lhs->type, rhs);
- if (new_rhs == NULL) {
- _mesa_glsl_error(& lhs_loc, state, "type mismatch");
- } else {
- rhs = new_rhs;
-
- /* If the LHS array was not declared with a size, it takes it size from
- * the RHS. If the LHS is an l-value and a whole array, it must be a
- * dereference of a variable. Any other case would require that the LHS
- * is either not an l-value or not a whole array.
- */
- if (lhs->type->array_size() == 0) {
- ir_dereference *const d = lhs->as_dereference();
-
- assert(d != NULL);
-
- ir_variable *const var = d->variable_referenced();
-
- assert(var != NULL);
-
- if (var->max_array_access >= unsigned(rhs->type->array_size())) {
- /* FINISHME: This should actually log the location of the RHS. */
- _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
- "previous access",
- var->max_array_access);
- }
-
- var->type = glsl_type::get_array_instance(lhs->type->element_type(),
- rhs->type->array_size());
- d->type = var->type;
- }
- }
-
- /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
- * but not post_inc) need the converted assigned value as an rvalue
- * to handle things like:
- *
- * i = j += 1;
- *
- * So we always just store the computed value being assigned to a
- * temporary and return a deref of that temporary. If the rvalue
- * ends up not being used, the temp will get copy-propagated out.
- */
- ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
- ir_var_temporary);
- ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
- instructions->push_tail(var);
- instructions->push_tail(new(ctx) ir_assignment(deref_var,
- rhs,
- NULL));
- deref_var = new(ctx) ir_dereference_variable(var);
-
- if (!error_emitted)
- instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
-
- return new(ctx) ir_dereference_variable(var);
-}
-
-static ir_rvalue *
-get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
-{
- void *ctx = ralloc_parent(lvalue);
- ir_variable *var;
-
- var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
- ir_var_temporary);
- instructions->push_tail(var);
- var->mode = ir_var_auto;
-
- instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
- lvalue, NULL));
-
- /* Once we've created this temporary, mark it read only so it's no
- * longer considered an lvalue.
- */
- var->read_only = true;
-
- return new(ctx) ir_dereference_variable(var);
-}
-
-
-ir_rvalue *
-ast_node::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- (void) instructions;
- (void) state;
-
- return NULL;
-}
-
-static void
-mark_whole_array_access(ir_rvalue *access)
-{
- ir_dereference_variable *deref = access->as_dereference_variable();
-
- if (deref) {
- deref->var->max_array_access = deref->type->length - 1;
- }
-}
-
-static ir_rvalue *
-do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
-{
- int join_op;
- ir_rvalue *cmp = NULL;
-
- if (operation == ir_binop_all_equal)
- join_op = ir_binop_logic_and;
- else
- join_op = ir_binop_logic_or;
-
- switch (op0->type->base_type) {
- case GLSL_TYPE_FLOAT:
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT:
- case GLSL_TYPE_BOOL:
- return new(mem_ctx) ir_expression(operation, op0, op1);
-
- case GLSL_TYPE_ARRAY: {
- for (unsigned int i = 0; i < op0->type->length; i++) {
- ir_rvalue *e0, *e1, *result;
-
- e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
- new(mem_ctx) ir_constant(i));
- e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
- new(mem_ctx) ir_constant(i));
- result = do_comparison(mem_ctx, operation, e0, e1);
-
- if (cmp) {
- cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
- } else {
- cmp = result;
- }
- }
-
- mark_whole_array_access(op0);
- mark_whole_array_access(op1);
- break;
- }
-
- case GLSL_TYPE_STRUCT: {
- for (unsigned int i = 0; i < op0->type->length; i++) {
- ir_rvalue *e0, *e1, *result;
- const char *field_name = op0->type->fields.structure[i].name;
-
- e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
- field_name);
- e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
- field_name);
- result = do_comparison(mem_ctx, operation, e0, e1);
-
- if (cmp) {
- cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
- } else {
- cmp = result;
- }
- }
- break;
- }
-
- case GLSL_TYPE_ERROR:
- case GLSL_TYPE_VOID:
- case GLSL_TYPE_SAMPLER:
- /* I assume a comparison of a struct containing a sampler just
- * ignores the sampler present in the type.
- */
- break;
-
- default:
- assert(!"Should not get here.");
- break;
- }
-
- if (cmp == NULL)
- cmp = new(mem_ctx) ir_constant(true);
-
- return cmp;
-}
-
-ir_rvalue *
-ast_expression::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- static const int operations[AST_NUM_OPERATORS] = {
- -1, /* ast_assign doesn't convert to ir_expression. */
- -1, /* ast_plus doesn't convert to ir_expression. */
- ir_unop_neg,
- ir_binop_add,
- ir_binop_sub,
- ir_binop_mul,
- ir_binop_div,
- ir_binop_mod,
- ir_binop_lshift,
- ir_binop_rshift,
- ir_binop_less,
- ir_binop_greater,
- ir_binop_lequal,
- ir_binop_gequal,
- ir_binop_all_equal,
- ir_binop_any_nequal,
- ir_binop_bit_and,
- ir_binop_bit_xor,
- ir_binop_bit_or,
- ir_unop_bit_not,
- ir_binop_logic_and,
- ir_binop_logic_xor,
- ir_binop_logic_or,
- ir_unop_logic_not,
-
- /* Note: The following block of expression types actually convert
- * to multiple IR instructions.
- */
- ir_binop_mul, /* ast_mul_assign */
- ir_binop_div, /* ast_div_assign */
- ir_binop_mod, /* ast_mod_assign */
- ir_binop_add, /* ast_add_assign */
- ir_binop_sub, /* ast_sub_assign */
- ir_binop_lshift, /* ast_ls_assign */
- ir_binop_rshift, /* ast_rs_assign */
- ir_binop_bit_and, /* ast_and_assign */
- ir_binop_bit_xor, /* ast_xor_assign */
- ir_binop_bit_or, /* ast_or_assign */
-
- -1, /* ast_conditional doesn't convert to ir_expression. */
- ir_binop_add, /* ast_pre_inc. */
- ir_binop_sub, /* ast_pre_dec. */
- ir_binop_add, /* ast_post_inc. */
- ir_binop_sub, /* ast_post_dec. */
- -1, /* ast_field_selection doesn't conv to ir_expression. */
- -1, /* ast_array_index doesn't convert to ir_expression. */
- -1, /* ast_function_call doesn't conv to ir_expression. */
- -1, /* ast_identifier doesn't convert to ir_expression. */
- -1, /* ast_int_constant doesn't convert to ir_expression. */
- -1, /* ast_uint_constant doesn't conv to ir_expression. */
- -1, /* ast_float_constant doesn't conv to ir_expression. */
- -1, /* ast_bool_constant doesn't conv to ir_expression. */
- -1, /* ast_sequence doesn't convert to ir_expression. */
- };
- ir_rvalue *result = NULL;
- ir_rvalue *op[3];
- const struct glsl_type *type = glsl_type::error_type;
- bool error_emitted = false;
- YYLTYPE loc;
-
- loc = this->get_location();
-
- switch (this->oper) {
- case ast_assign: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- result = do_assignment(instructions, state, op[0], op[1],
- this->subexpressions[0]->get_location());
- error_emitted = result->type->is_error();
- type = result->type;
- break;
- }
-
- case ast_plus:
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- type = unary_arithmetic_result_type(op[0]->type, state, & loc);
-
- error_emitted = type->is_error();
-
- result = op[0];
- break;
-
- case ast_neg:
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- type = unary_arithmetic_result_type(op[0]->type, state, & loc);
-
- error_emitted = type->is_error();
-
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], NULL);
- break;
-
- case ast_add:
- case ast_sub:
- case ast_mul:
- case ast_div:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- type = arithmetic_result_type(op[0], op[1],
- (this->oper == ast_mul),
- state, & loc);
- error_emitted = type->is_error();
-
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
- break;
-
- case ast_mod:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
-
- assert(operations[this->oper] == ir_binop_mod);
-
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
- error_emitted = type->is_error();
- break;
-
- case ast_lshift:
- case ast_rshift:
- if (state->language_version < 130) {
- _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
- operator_string(this->oper));
- error_emitted = true;
- }
-
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
- type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
- &loc);
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
- break;
-
- case ast_less:
- case ast_greater:
- case ast_lequal:
- case ast_gequal:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- type = relational_result_type(op[0], op[1], state, & loc);
-
- /* The relational operators must either generate an error or result
- * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
- */
- assert(type->is_error()
- || ((type->base_type == GLSL_TYPE_BOOL)
- && type->is_scalar()));
-
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
- error_emitted = type->is_error();
- break;
-
- case ast_nequal:
- case ast_equal:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
- *
- * "The equality operators equal (==), and not equal (!=)
- * operate on all types. They result in a scalar Boolean. If
- * the operand types do not match, then there must be a
- * conversion from Section 4.1.10 "Implicit Conversions"
- * applied to one operand that can make them match, in which
- * case this conversion is done."
- */
- if ((!apply_implicit_conversion(op[0]->type, op[1], state)
- && !apply_implicit_conversion(op[1]->type, op[0], state))
- || (op[0]->type != op[1]->type)) {
- _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
- "type", (this->oper == ast_equal) ? "==" : "!=");
- error_emitted = true;
- } else if ((state->language_version <= 110)
- && (op[0]->type->is_array() || op[1]->type->is_array())) {
- _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
- "GLSL 1.10");
- error_emitted = true;
- }
-
- result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
- type = glsl_type::bool_type;
-
- assert(error_emitted || (result->type == glsl_type::bool_type));
- break;
-
- case ast_bit_and:
- case ast_bit_xor:
- case ast_bit_or:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
- type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
- state, &loc);
- result = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
- break;
-
- case ast_bit_not:
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- if (state->language_version < 130) {
- _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
- error_emitted = true;
- }
-
- if (!op[0]->type->is_integer()) {
- _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
- error_emitted = true;
- }
-
- type = op[0]->type;
- result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
- break;
-
- case ast_logic_and: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[0]->get_location();
-
- _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
-
- ir_constant *op0_const = op[0]->constant_expression_value();
- if (op0_const) {
- if (op0_const->value.b[0]) {
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[1]->get_location();
-
- _mesa_glsl_error(& loc, state,
- "RHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
- result = op[1];
- } else {
- result = op0_const;
- }
- type = glsl_type::bool_type;
- } else {
- ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
- "and_tmp",
- ir_var_temporary);
- instructions->push_tail(tmp);
-
- ir_if *const stmt = new(ctx) ir_if(op[0]);
- instructions->push_tail(stmt);
-
- op[1] = this->subexpressions[1]->hir(&stmt->then_instructions, state);
-
- if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[1]->get_location();
-
- _mesa_glsl_error(& loc, state,
- "RHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
-
- ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const then_assign =
- new(ctx) ir_assignment(then_deref, op[1], NULL);
- stmt->then_instructions.push_tail(then_assign);
-
- ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const else_assign =
- new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
- stmt->else_instructions.push_tail(else_assign);
-
- result = new(ctx) ir_dereference_variable(tmp);
- type = tmp->type;
- }
- break;
- }
-
- case ast_logic_or: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[0]->get_location();
-
- _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
-
- ir_constant *op0_const = op[0]->constant_expression_value();
- if (op0_const) {
- if (op0_const->value.b[0]) {
- result = op0_const;
- } else {
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[1]->get_location();
-
- _mesa_glsl_error(& loc, state,
- "RHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
- result = op[1];
- }
- type = glsl_type::bool_type;
- } else {
- ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
- "or_tmp",
- ir_var_temporary);
- instructions->push_tail(tmp);
-
- ir_if *const stmt = new(ctx) ir_if(op[0]);
- instructions->push_tail(stmt);
-
- op[1] = this->subexpressions[1]->hir(&stmt->else_instructions, state);
-
- if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[1]->get_location();
-
- _mesa_glsl_error(& loc, state, "RHS of `%s' must be scalar boolean",
- operator_string(this->oper));
- error_emitted = true;
- }
-
- ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const then_assign =
- new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
- stmt->then_instructions.push_tail(then_assign);
-
- ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const else_assign =
- new(ctx) ir_assignment(else_deref, op[1], NULL);
- stmt->else_instructions.push_tail(else_assign);
-
- result = new(ctx) ir_dereference_variable(tmp);
- type = tmp->type;
- }
- break;
- }
-
- case ast_logic_xor:
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
-
- result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
- op[0], op[1]);
- type = glsl_type::bool_type;
- break;
-
- case ast_logic_not:
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[0]->get_location();
-
- _mesa_glsl_error(& loc, state,
- "operand of `!' must be scalar boolean");
- error_emitted = true;
- }
-
- result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
- op[0], NULL);
- type = glsl_type::bool_type;
- break;
-
- case ast_mul_assign:
- case ast_div_assign:
- case ast_add_assign:
- case ast_sub_assign: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- type = arithmetic_result_type(op[0], op[1],
- (this->oper == ast_mul_assign),
- state, & loc);
-
- ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
-
- result = do_assignment(instructions, state,
- op[0]->clone(ctx, NULL), temp_rhs,
- this->subexpressions[0]->get_location());
- type = result->type;
- error_emitted = (op[0]->type->is_error());
-
- /* GLSL 1.10 does not allow array assignment. However, we don't have to
- * explicitly test for this because none of the binary expression
- * operators allow array operands either.
- */
-
- break;
- }
-
- case ast_mod_assign: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
-
- type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
-
- assert(operations[this->oper] == ir_binop_mod);
-
- ir_rvalue *temp_rhs;
- temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
-
- result = do_assignment(instructions, state,
- op[0]->clone(ctx, NULL), temp_rhs,
- this->subexpressions[0]->get_location());
- type = result->type;
- error_emitted = type->is_error();
- break;
- }
-
- case ast_ls_assign:
- case ast_rs_assign: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
- type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
- &loc);
- ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
- type, op[0], op[1]);
- result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
- temp_rhs,
- this->subexpressions[0]->get_location());
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
- break;
- }
-
- case ast_and_assign:
- case ast_xor_assign:
- case ast_or_assign: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- op[1] = this->subexpressions[1]->hir(instructions, state);
- type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
- state, &loc);
- ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
- type, op[0], op[1]);
- result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
- temp_rhs,
- this->subexpressions[0]->get_location());
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
- break;
- }
-
- case ast_conditional: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
-
- /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
- *
- * "The ternary selection operator (?:). It operates on three
- * expressions (exp1 ? exp2 : exp3). This operator evaluates the
- * first expression, which must result in a scalar Boolean."
- */
- if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
- YYLTYPE loc = this->subexpressions[0]->get_location();
-
- _mesa_glsl_error(& loc, state, "?: condition must be scalar boolean");
- error_emitted = true;
- }
-
- /* The :? operator is implemented by generating an anonymous temporary
- * followed by an if-statement. The last instruction in each branch of
- * the if-statement assigns a value to the anonymous temporary. This
- * temporary is the r-value of the expression.
- */
- exec_list then_instructions;
- exec_list else_instructions;
-
- op[1] = this->subexpressions[1]->hir(&then_instructions, state);
- op[2] = this->subexpressions[2]->hir(&else_instructions, state);
-
- /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
- *
- * "The second and third expressions can be any type, as
- * long their types match, or there is a conversion in
- * Section 4.1.10 "Implicit Conversions" that can be applied
- * to one of the expressions to make their types match. This
- * resulting matching type is the type of the entire
- * expression."
- */
- if ((!apply_implicit_conversion(op[1]->type, op[2], state)
- && !apply_implicit_conversion(op[2]->type, op[1], state))
- || (op[1]->type != op[2]->type)) {
- YYLTYPE loc = this->subexpressions[1]->get_location();
-
- _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
- "operator must have matching types.");
- error_emitted = true;
- type = glsl_type::error_type;
- } else {
- type = op[1]->type;
- }
-
- /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
- *
- * "The second and third expressions must be the same type, but can
- * be of any type other than an array."
- */
- if ((state->language_version <= 110) && type->is_array()) {
- _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
- "operator must not be arrays.");
- error_emitted = true;
- }
-
- ir_constant *cond_val = op[0]->constant_expression_value();
- ir_constant *then_val = op[1]->constant_expression_value();
- ir_constant *else_val = op[2]->constant_expression_value();
-
- if (then_instructions.is_empty()
- && else_instructions.is_empty()
- && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
- result = (cond_val->value.b[0]) ? then_val : else_val;
- } else {
- ir_variable *const tmp =
- new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
- instructions->push_tail(tmp);
-
- ir_if *const stmt = new(ctx) ir_if(op[0]);
- instructions->push_tail(stmt);
-
- then_instructions.move_nodes_to(& stmt->then_instructions);
- ir_dereference *const then_deref =
- new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const then_assign =
- new(ctx) ir_assignment(then_deref, op[1], NULL);
- stmt->then_instructions.push_tail(then_assign);
-
- else_instructions.move_nodes_to(& stmt->else_instructions);
- ir_dereference *const else_deref =
- new(ctx) ir_dereference_variable(tmp);
- ir_assignment *const else_assign =
- new(ctx) ir_assignment(else_deref, op[2], NULL);
- stmt->else_instructions.push_tail(else_assign);
-
- result = new(ctx) ir_dereference_variable(tmp);
- }
- break;
- }
-
- case ast_pre_inc:
- case ast_pre_dec: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
- op[1] = new(ctx) ir_constant(1.0f);
- else
- op[1] = new(ctx) ir_constant(1);
-
- type = arithmetic_result_type(op[0], op[1], false, state, & loc);
-
- ir_rvalue *temp_rhs;
- temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
-
- result = do_assignment(instructions, state,
- op[0]->clone(ctx, NULL), temp_rhs,
- this->subexpressions[0]->get_location());
- type = result->type;
- error_emitted = op[0]->type->is_error();
- break;
- }
-
- case ast_post_inc:
- case ast_post_dec: {
- op[0] = this->subexpressions[0]->hir(instructions, state);
- if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
- op[1] = new(ctx) ir_constant(1.0f);
- else
- op[1] = new(ctx) ir_constant(1);
-
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
-
- type = arithmetic_result_type(op[0], op[1], false, state, & loc);
-
- ir_rvalue *temp_rhs;
- temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
- op[0], op[1]);
-
- /* Get a temporary of a copy of the lvalue before it's modified.
- * This may get thrown away later.
- */
- result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
-
- (void)do_assignment(instructions, state,
- op[0]->clone(ctx, NULL), temp_rhs,
- this->subexpressions[0]->get_location());
-
- type = result->type;
- error_emitted = op[0]->type->is_error();
- break;
- }
-
- case ast_field_selection:
- result = _mesa_ast_field_selection_to_hir(this, instructions, state);
- type = result->type;
- break;
-
- case ast_array_index: {
- YYLTYPE index_loc = subexpressions[1]->get_location();
-
- op[0] = subexpressions[0]->hir(instructions, state);
- op[1] = subexpressions[1]->hir(instructions, state);
-
- error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
-
- ir_rvalue *const array = op[0];
-
- result = new(ctx) ir_dereference_array(op[0], op[1]);
-
- /* Do not use op[0] after this point. Use array.
- */
- op[0] = NULL;
-
-
- if (error_emitted)
- break;
-
- if (!array->type->is_array()
- && !array->type->is_matrix()
- && !array->type->is_vector()) {
- _mesa_glsl_error(& index_loc, state,
- "cannot dereference non-array / non-matrix / "
- "non-vector");
- error_emitted = true;
- }
-
- if (!op[1]->type->is_integer()) {
- _mesa_glsl_error(& index_loc, state,
- "array index must be integer type");
- error_emitted = true;
- } else if (!op[1]->type->is_scalar()) {
- _mesa_glsl_error(& index_loc, state,
- "array index must be scalar");
- error_emitted = true;
- }
-
- /* If the array index is a constant expression and the array has a
- * declared size, ensure that the access is in-bounds. If the array
- * index is not a constant expression, ensure that the array has a
- * declared size.
- */
- ir_constant *const const_index = op[1]->constant_expression_value();
- if (const_index != NULL) {
- const int idx = const_index->value.i[0];
- const char *type_name;
- unsigned bound = 0;
-
- if (array->type->is_matrix()) {
- type_name = "matrix";
- } else if (array->type->is_vector()) {
- type_name = "vector";
- } else {
- type_name = "array";
- }
-
- /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
- *
- * "It is illegal to declare an array with a size, and then
- * later (in the same shader) index the same array with an
- * integral constant expression greater than or equal to the
- * declared size. It is also illegal to index an array with a
- * negative constant expression."
- */
- if (array->type->is_matrix()) {
- if (array->type->row_type()->vector_elements <= idx) {
- bound = array->type->row_type()->vector_elements;
- }
- } else if (array->type->is_vector()) {
- if (array->type->vector_elements <= idx) {
- bound = array->type->vector_elements;
- }
- } else {
- if ((array->type->array_size() > 0)
- && (array->type->array_size() <= idx)) {
- bound = array->type->array_size();
- }
- }
-
- if (bound > 0) {
- _mesa_glsl_error(& loc, state, "%s index must be < %u",
- type_name, bound);
- error_emitted = true;
- } else if (idx < 0) {
- _mesa_glsl_error(& loc, state, "%s index must be >= 0",
- type_name);
- error_emitted = true;
- }
-
- if (array->type->is_array()) {
- /* If the array is a variable dereference, it dereferences the
- * whole array, by definition. Use this to get the variable.
- *
- * FINISHME: Should some methods for getting / setting / testing
- * FINISHME: array access limits be added to ir_dereference?
- */
- ir_variable *const v = array->whole_variable_referenced();
- if ((v != NULL) && (unsigned(idx) > v->max_array_access))
- v->max_array_access = idx;
- }
- } else if (array->type->array_size() == 0) {
- _mesa_glsl_error(&loc, state, "unsized array index must be constant");
- } else {
- if (array->type->is_array()) {
- /* whole_variable_referenced can return NULL if the array is a
- * member of a structure. In this case it is safe to not update
- * the max_array_access field because it is never used for fields
- * of structures.
- */
- ir_variable *v = array->whole_variable_referenced();
- if (v != NULL)
- v->max_array_access = array->type->array_size();
- }
- }
-
- /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
- *
- * "Samplers aggregated into arrays within a shader (using square
- * brackets [ ]) can only be indexed with integral constant
- * expressions [...]."
- *
- * This restriction was added in GLSL 1.30. Shaders using earlier version
- * of the language should not be rejected by the compiler front-end for
- * using this construct. This allows useful things such as using a loop
- * counter as the index to an array of samplers. If the loop in unrolled,
- * the code should compile correctly. Instead, emit a warning.
- */
- if (array->type->is_array() &&
- array->type->element_type()->is_sampler() &&
- const_index == NULL) {
-
- if (state->language_version == 100) {
- _mesa_glsl_warning(&loc, state,
- "sampler arrays indexed with non-constant "
- "expressions is optional in GLSL ES 1.00");
- } else if (state->language_version < 130) {
- _mesa_glsl_warning(&loc, state,
- "sampler arrays indexed with non-constant "
- "expressions is forbidden in GLSL 1.30 and "
- "later");
- } else {
- _mesa_glsl_error(&loc, state,
- "sampler arrays indexed with non-constant "
- "expressions is forbidden in GLSL 1.30 and "
- "later");
- error_emitted = true;
- }
- }
-
- if (error_emitted)
- result->type = glsl_type::error_type;
-
- type = result->type;
- break;
- }
-
- case ast_function_call:
- /* Should *NEVER* get here. ast_function_call should always be handled
- * by ast_function_expression::hir.
- */
- assert(0);
- break;
-
- case ast_identifier: {
- /* ast_identifier can appear several places in a full abstract syntax
- * tree. This particular use must be at location specified in the grammar
- * as 'variable_identifier'.
- */
- ir_variable *var =
- state->symbols->get_variable(this->primary_expression.identifier);
-
- result = new(ctx) ir_dereference_variable(var);
-
- if (var != NULL) {
- var->used = true;
- type = result->type;
- } else {
- _mesa_glsl_error(& loc, state, "`%s' undeclared",
- this->primary_expression.identifier);
-
- error_emitted = true;
- }
- break;
- }
-
- case ast_int_constant:
- type = glsl_type::int_type;
- result = new(ctx) ir_constant(this->primary_expression.int_constant);
- break;
-
- case ast_uint_constant:
- type = glsl_type::uint_type;
- result = new(ctx) ir_constant(this->primary_expression.uint_constant);
- break;
-
- case ast_float_constant:
- type = glsl_type::float_type;
- result = new(ctx) ir_constant(this->primary_expression.float_constant);
- break;
-
- case ast_bool_constant:
- type = glsl_type::bool_type;
- result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
- break;
-
- case ast_sequence: {
- /* It should not be possible to generate a sequence in the AST without
- * any expressions in it.
- */
- assert(!this->expressions.is_empty());
-
- /* The r-value of a sequence is the last expression in the sequence. If
- * the other expressions in the sequence do not have side-effects (and
- * therefore add instructions to the instruction list), they get dropped
- * on the floor.
- */
- foreach_list_typed (ast_node, ast, link, &this->expressions)
- result = ast->hir(instructions, state);
-
- type = result->type;
-
- /* Any errors should have already been emitted in the loop above.
- */
- error_emitted = true;
- break;
- }
- }
-
- if (type->is_error() && !error_emitted)
- _mesa_glsl_error(& loc, state, "type mismatch");
-
- return result;
-}
-
-
-ir_rvalue *
-ast_expression_statement::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- /* It is possible to have expression statements that don't have an
- * expression. This is the solitary semicolon:
- *
- * for (i = 0; i < 5; i++)
- * ;
- *
- * In this case the expression will be NULL. Test for NULL and don't do
- * anything in that case.
- */
- if (expression != NULL)
- expression->hir(instructions, state);
-
- /* Statements do not have r-values.
- */
- return NULL;
-}
-
-
-ir_rvalue *
-ast_compound_statement::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- if (new_scope)
- state->symbols->push_scope();
-
- foreach_list_typed (ast_node, ast, link, &this->statements)
- ast->hir(instructions, state);
-
- if (new_scope)
- state->symbols->pop_scope();
-
- /* Compound statements do not have r-values.
- */
- return NULL;
-}
-
-
-static const glsl_type *
-process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
- struct _mesa_glsl_parse_state *state)
-{
- unsigned length = 0;
-
- /* FINISHME: Reject delcarations of multidimensional arrays. */
-
- if (array_size != NULL) {
- exec_list dummy_instructions;
- ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
- YYLTYPE loc = array_size->get_location();
-
- /* FINISHME: Verify that the grammar forbids side-effects in array
- * FINISHME: sizes. i.e., 'vec4 [x = 12] data'
- */
- assert(dummy_instructions.is_empty());
-
- if (ir != NULL) {
- if (!ir->type->is_integer()) {
- _mesa_glsl_error(& loc, state, "array size must be integer type");
- } else if (!ir->type->is_scalar()) {
- _mesa_glsl_error(& loc, state, "array size must be scalar type");
- } else {
- ir_constant *const size = ir->constant_expression_value();
-
- if (size == NULL) {
- _mesa_glsl_error(& loc, state, "array size must be a "
- "constant valued expression");
- } else if (size->value.i[0] <= 0) {
- _mesa_glsl_error(& loc, state, "array size must be > 0");
- } else {
- assert(size->type == ir->type);
- length = size->value.u[0];
- }
- }
- }
- } else if (state->es_shader) {
- /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
- * array declarations have been removed from the language.
- */
- _mesa_glsl_error(loc, state, "unsized array declarations are not "
- "allowed in GLSL ES 1.00.");
- }
-
- return glsl_type::get_array_instance(base, length);
-}
-
-
-const glsl_type *
-ast_type_specifier::glsl_type(const char **name,
- struct _mesa_glsl_parse_state *state) const
-{
- const struct glsl_type *type;
-
- type = state->symbols->get_type(this->type_name);
- *name = this->type_name;
-
- if (this->is_array) {
- YYLTYPE loc = this->get_location();
- type = process_array_type(&loc, type, this->array_size, state);
- }
-
- return type;
-}
-
-
-static void
-apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
- ir_variable *var,
- struct _mesa_glsl_parse_state *state,
- YYLTYPE *loc)
-{
- if (qual->flags.q.invariant) {
- if (var->used) {
- _mesa_glsl_error(loc, state,
- "variable `%s' may not be redeclared "
- "`invariant' after being used",
- var->name);
- } else {
- var->invariant = 1;
- }
- }
-
- if (qual->flags.q.constant || qual->flags.q.attribute
- || qual->flags.q.uniform
- || (qual->flags.q.varying && (state->target == fragment_shader)))
- var->read_only = 1;
-
- if (qual->flags.q.centroid)
- var->centroid = 1;
-
- if (qual->flags.q.attribute && state->target != vertex_shader) {
- var->type = glsl_type::error_type;
- _mesa_glsl_error(loc, state,
- "`attribute' variables may not be declared in the "
- "%s shader",
- _mesa_glsl_shader_target_name(state->target));
- }
-
- /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
- *
- * "The varying qualifier can be used only with the data types
- * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
- * these."
- */
- if (qual->flags.q.varying) {
- const glsl_type *non_array_type;
-
- if (var->type && var->type->is_array())
- non_array_type = var->type->fields.array;
- else
- non_array_type = var->type;
-
- if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
- var->type = glsl_type::error_type;
- _mesa_glsl_error(loc, state,
- "varying variables must be of base type float");
- }
- }
-
- /* If there is no qualifier that changes the mode of the variable, leave
- * the setting alone.
- */
- if (qual->flags.q.in && qual->flags.q.out)
- var->mode = ir_var_inout;
- else if (qual->flags.q.attribute || qual->flags.q.in
- || (qual->flags.q.varying && (state->target == fragment_shader)))
- var->mode = ir_var_in;
- else if (qual->flags.q.out
- || (qual->flags.q.varying && (state->target == vertex_shader)))
- var->mode = ir_var_out;
- else if (qual->flags.q.uniform)
- var->mode = ir_var_uniform;
-
- if (state->all_invariant && (state->current_function == NULL)) {
- switch (state->target) {
- case vertex_shader:
- if (var->mode == ir_var_out)
- var->invariant = true;
- break;
- case geometry_shader:
- if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
- var->invariant = true;
- break;
- case fragment_shader:
- if (var->mode == ir_var_in)
- var->invariant = true;
- break;
- }
- }
-
- if (qual->flags.q.flat)
- var->interpolation = ir_var_flat;
- else if (qual->flags.q.noperspective)
- var->interpolation = ir_var_noperspective;
- else
- var->interpolation = ir_var_smooth;
-
- var->pixel_center_integer = qual->flags.q.pixel_center_integer;
- var->origin_upper_left = qual->flags.q.origin_upper_left;
- if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
- && (strcmp(var->name, "gl_FragCoord") != 0)) {
- const char *const qual_string = (qual->flags.q.origin_upper_left)
- ? "origin_upper_left" : "pixel_center_integer";
-
- _mesa_glsl_error(loc, state,
- "layout qualifier `%s' can only be applied to "
- "fragment shader input `gl_FragCoord'",
- qual_string);
- }
-
- if (qual->flags.q.explicit_location) {
- const bool global_scope = (state->current_function == NULL);
- bool fail = false;
- const char *string = "";
-
- /* In the vertex shader only shader inputs can be given explicit
- * locations.
- *
- * In the fragment shader only shader outputs can be given explicit
- * locations.
- */
- switch (state->target) {
- case vertex_shader:
- if (!global_scope || (var->mode != ir_var_in)) {
- fail = true;
- string = "input";
- }
- break;
-
- case geometry_shader:
- _mesa_glsl_error(loc, state,
- "geometry shader variables cannot be given "
- "explicit locations\n");
- break;
-
- case fragment_shader:
- if (!global_scope || (var->mode != ir_var_in)) {
- fail = true;
- string = "output";
- }
- break;
- };
-
- if (fail) {
- _mesa_glsl_error(loc, state,
- "only %s shader %s variables can be given an "
- "explicit location\n",
- _mesa_glsl_shader_target_name(state->target),
- string);
- } else {
- var->explicit_location = true;
-
- /* This bit of silliness is needed because invalid explicit locations
- * are supposed to be flagged during linking. Small negative values
- * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
- * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
- * The linker needs to be able to differentiate these cases. This
- * ensures that negative values stay negative.
- */
- if (qual->location >= 0) {
- var->location = (state->target == vertex_shader)
- ? (qual->location + VERT_ATTRIB_GENERIC0)
- : (qual->location + FRAG_RESULT_DATA0);
- } else {
- var->location = qual->location;
- }
- }
- }
-
- /* Does the declaration use the 'layout' keyword?
- */
- const bool uses_layout = qual->flags.q.pixel_center_integer
- || qual->flags.q.origin_upper_left
- || qual->flags.q.explicit_location;
-
- /* Does the declaration use the deprecated 'attribute' or 'varying'
- * keywords?
- */
- const bool uses_deprecated_qualifier = qual->flags.q.attribute
- || qual->flags.q.varying;
-
- /* Is the 'layout' keyword used with parameters that allow relaxed checking.
- * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
- * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
- * allowed the layout qualifier to be used with 'varying' and 'attribute'.
- * These extensions and all following extensions that add the 'layout'
- * keyword have been modified to require the use of 'in' or 'out'.
- *
- * The following extension do not allow the deprecated keywords:
- *
- * GL_AMD_conservative_depth
- * GL_ARB_gpu_shader5
- * GL_ARB_separate_shader_objects
- * GL_ARB_tesselation_shader
- * GL_ARB_transform_feedback3
- * GL_ARB_uniform_buffer_object
- *
- * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
- * allow layout with the deprecated keywords.
- */
- const bool relaxed_layout_qualifier_checking =
- state->ARB_fragment_coord_conventions_enable;
-
- if (uses_layout && uses_deprecated_qualifier) {
- if (relaxed_layout_qualifier_checking) {
- _mesa_glsl_warning(loc, state,
- "`layout' qualifier may not be used with "
- "`attribute' or `varying'");
- } else {
- _mesa_glsl_error(loc, state,
- "`layout' qualifier may not be used with "
- "`attribute' or `varying'");
- }
- }
-
- /* Layout qualifiers for gl_FragDepth, which are enabled by extension
- * AMD_conservative_depth.
- */
- int depth_layout_count = qual->flags.q.depth_any
- + qual->flags.q.depth_greater
- + qual->flags.q.depth_less
- + qual->flags.q.depth_unchanged;
- if (depth_layout_count > 0
- && !state->AMD_conservative_depth_enable) {
- _mesa_glsl_error(loc, state,
- "extension GL_AMD_conservative_depth must be enabled "
- "to use depth layout qualifiers");
- } else if (depth_layout_count > 0
- && strcmp(var->name, "gl_FragDepth") != 0) {
- _mesa_glsl_error(loc, state,
- "depth layout qualifiers can be applied only to "
- "gl_FragDepth");
- } else if (depth_layout_count > 1
- && strcmp(var->name, "gl_FragDepth") == 0) {
- _mesa_glsl_error(loc, state,
- "at most one depth layout qualifier can be applied to "
- "gl_FragDepth");
- }
- if (qual->flags.q.depth_any)
- var->depth_layout = ir_depth_layout_any;
- else if (qual->flags.q.depth_greater)
- var->depth_layout = ir_depth_layout_greater;
- else if (qual->flags.q.depth_less)
- var->depth_layout = ir_depth_layout_less;
- else if (qual->flags.q.depth_unchanged)
- var->depth_layout = ir_depth_layout_unchanged;
- else
- var->depth_layout = ir_depth_layout_none;
-
- if (var->type->is_array() && state->language_version != 110) {
- var->array_lvalue = true;
- }
-}
-
-
-ir_rvalue *
-ast_declarator_list::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- const struct glsl_type *decl_type;
- const char *type_name = NULL;
- ir_rvalue *result = NULL;
- YYLTYPE loc = this->get_location();
-
- /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
- *
- * "To ensure that a particular output variable is invariant, it is
- * necessary to use the invariant qualifier. It can either be used to
- * qualify a previously declared variable as being invariant
- *
- * invariant gl_Position; // make existing gl_Position be invariant"
- *
- * In these cases the parser will set the 'invariant' flag in the declarator
- * list, and the type will be NULL.
- */
- if (this->invariant) {
- assert(this->type == NULL);
-
- if (state->current_function != NULL) {
- _mesa_glsl_error(& loc, state,
- "All uses of `invariant' keyword must be at global "
- "scope\n");
- }
-
- foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
- assert(!decl->is_array);
- assert(decl->array_size == NULL);
- assert(decl->initializer == NULL);
-
- ir_variable *const earlier =
- state->symbols->get_variable(decl->identifier);
- if (earlier == NULL) {
- _mesa_glsl_error(& loc, state,
- "Undeclared variable `%s' cannot be marked "
- "invariant\n", decl->identifier);
- } else if ((state->target == vertex_shader)
- && (earlier->mode != ir_var_out)) {
- _mesa_glsl_error(& loc, state,
- "`%s' cannot be marked invariant, vertex shader "
- "outputs only\n", decl->identifier);
- } else if ((state->target == fragment_shader)
- && (earlier->mode != ir_var_in)) {
- _mesa_glsl_error(& loc, state,
- "`%s' cannot be marked invariant, fragment shader "
- "inputs only\n", decl->identifier);
- } else if (earlier->used) {
- _mesa_glsl_error(& loc, state,
- "variable `%s' may not be redeclared "
- "`invariant' after being used",
- earlier->name);
- } else {
- earlier->invariant = true;
- }
- }
-
- /* Invariant redeclarations do not have r-values.
- */
- return NULL;
- }
-
- assert(this->type != NULL);
- assert(!this->invariant);
-
- /* The type specifier may contain a structure definition. Process that
- * before any of the variable declarations.
- */
- (void) this->type->specifier->hir(instructions, state);
-
- decl_type = this->type->specifier->glsl_type(& type_name, state);
- if (this->declarations.is_empty()) {
- /* The only valid case where the declaration list can be empty is when
- * the declaration is setting the default precision of a built-in type
- * (e.g., 'precision highp vec4;').
- */
-
- if (decl_type != NULL) {
- } else {
- _mesa_glsl_error(& loc, state, "incomplete declaration");
- }
- }
-
- foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
- const struct glsl_type *var_type;
- ir_variable *var;
-
- /* FINISHME: Emit a warning if a variable declaration shadows a
- * FINISHME: declaration at a higher scope.
- */
-
- if ((decl_type == NULL) || decl_type->is_void()) {
- if (type_name != NULL) {
- _mesa_glsl_error(& loc, state,
- "invalid type `%s' in declaration of `%s'",
- type_name, decl->identifier);
- } else {
- _mesa_glsl_error(& loc, state,
- "invalid type in declaration of `%s'",
- decl->identifier);
- }
- continue;
- }
-
- if (decl->is_array) {
- var_type = process_array_type(&loc, decl_type, decl->array_size,
- state);
- } else {
- var_type = decl_type;
- }
-
- var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
-
- /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
- *
- * "Global variables can only use the qualifiers const,
- * attribute, uni form, or varying. Only one may be
- * specified.
- *
- * Local variables can only use the qualifier const."
- *
- * This is relaxed in GLSL 1.30. It is also relaxed by any extension
- * that adds the 'layout' keyword.
- */
- if ((state->language_version < 130)
- && !state->ARB_explicit_attrib_location_enable
- && !state->ARB_fragment_coord_conventions_enable) {
- if (this->type->qualifier.flags.q.out) {
- _mesa_glsl_error(& loc, state,
- "`out' qualifier in declaration of `%s' "
- "only valid for function parameters in %s.",
- decl->identifier, state->version_string);
- }
- if (this->type->qualifier.flags.q.in) {
- _mesa_glsl_error(& loc, state,
- "`in' qualifier in declaration of `%s' "
- "only valid for function parameters in %s.",
- decl->identifier, state->version_string);
- }
- /* FINISHME: Test for other invalid qualifiers. */
- }
-
- apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
- & loc);
-
- if (this->type->qualifier.flags.q.invariant) {
- if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
- var->mode == ir_var_inout)) {
- /* FINISHME: Note that this doesn't work for invariant on
- * a function signature outval
- */
- _mesa_glsl_error(& loc, state,
- "`%s' cannot be marked invariant, vertex shader "
- "outputs only\n", var->name);
- } else if ((state->target == fragment_shader) &&
- !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
- /* FINISHME: Note that this doesn't work for invariant on
- * a function signature inval
- */
- _mesa_glsl_error(& loc, state,
- "`%s' cannot be marked invariant, fragment shader "
- "inputs only\n", var->name);
- }
- }
-
- if (state->current_function != NULL) {
- const char *mode = NULL;
- const char *extra = "";
-
- /* There is no need to check for 'inout' here because the parser will
- * only allow that in function parameter lists.
- */
- if (this->type->qualifier.flags.q.attribute) {
- mode = "attribute";
- } else if (this->type->qualifier.flags.q.uniform) {
- mode = "uniform";
- } else if (this->type->qualifier.flags.q.varying) {
- mode = "varying";
- } else if (this->type->qualifier.flags.q.in) {
- mode = "in";
- extra = " or in function parameter list";
- } else if (this->type->qualifier.flags.q.out) {
- mode = "out";
- extra = " or in function parameter list";
- }
-
- if (mode) {
- _mesa_glsl_error(& loc, state,
- "%s variable `%s' must be declared at "
- "global scope%s",
- mode, var->name, extra);
- }
- } else if (var->mode == ir_var_in) {
- var->read_only = true;
-
- if (state->target == vertex_shader) {
- bool error_emitted = false;
-
- /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
- *
- * "Vertex shader inputs can only be float, floating-point
- * vectors, matrices, signed and unsigned integers and integer
- * vectors. Vertex shader inputs can also form arrays of these
- * types, but not structures."
- *
- * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
- *
- * "Vertex shader inputs can only be float, floating-point
- * vectors, matrices, signed and unsigned integers and integer
- * vectors. They cannot be arrays or structures."
- *
- * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
- *
- * "The attribute qualifier can be used only with float,
- * floating-point vectors, and matrices. Attribute variables
- * cannot be declared as arrays or structures."
- */
- const glsl_type *check_type = var->type->is_array()
- ? var->type->fields.array : var->type;
-
- switch (check_type->base_type) {
- case GLSL_TYPE_FLOAT:
- break;
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT:
- if (state->language_version > 120)
- break;
- /* FALLTHROUGH */
- default:
- _mesa_glsl_error(& loc, state,
- "vertex shader input / attribute cannot have "
- "type %s`%s'",
- var->type->is_array() ? "array of " : "",
- check_type->name);
- error_emitted = true;
- }
-
- if (!error_emitted && (state->language_version <= 130)
- && var->type->is_array()) {
- _mesa_glsl_error(& loc, state,
- "vertex shader input / attribute cannot have "
- "array type");
- error_emitted = true;
- }
- }
- }
-
- /* Integer vertex outputs must be qualified with 'flat'.
- *
- * From section 4.3.6 of the GLSL 1.30 spec:
- * "If a vertex output is a signed or unsigned integer or integer
- * vector, then it must be qualified with the interpolation qualifier
- * flat."
- */
- if (state->language_version >= 130
- && state->target == vertex_shader
- && state->current_function == NULL
- && var->type->is_integer()
- && var->mode == ir_var_out
- && var->interpolation != ir_var_flat) {
-
- _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
- "then it must be qualified with 'flat'");
- }
-
-
- /* Interpolation qualifiers cannot be applied to 'centroid' and
- * 'centroid varying'.
- *
- * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
- * "interpolation qualifiers may only precede the qualifiers in,
- * centroid in, out, or centroid out in a declaration. They do not apply
- * to the deprecated storage qualifiers varying or centroid varying."
- */
- if (state->language_version >= 130
- && this->type->qualifier.has_interpolation()
- && this->type->qualifier.flags.q.varying) {
-
- const char *i = this->type->qualifier.interpolation_string();
- assert(i != NULL);
- const char *s;
- if (this->type->qualifier.flags.q.centroid)
- s = "centroid varying";
- else
- s = "varying";
-
- _mesa_glsl_error(&loc, state,
- "qualifier '%s' cannot be applied to the "
- "deprecated storage qualifier '%s'", i, s);
- }
-
-
- /* Interpolation qualifiers can only apply to vertex shader outputs and
- * fragment shader inputs.
- *
- * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
- * "Outputs from a vertex shader (out) and inputs to a fragment
- * shader (in) can be further qualified with one or more of these
- * interpolation qualifiers"
- */
- if (state->language_version >= 130
- && this->type->qualifier.has_interpolation()) {
-
- const char *i = this->type->qualifier.interpolation_string();
- assert(i != NULL);
-
- switch (state->target) {
- case vertex_shader:
- if (this->type->qualifier.flags.q.in) {
- _mesa_glsl_error(&loc, state,
- "qualifier '%s' cannot be applied to vertex "
- "shader inputs", i);
- }
- break;
- case fragment_shader:
- if (this->type->qualifier.flags.q.out) {
- _mesa_glsl_error(&loc, state,
- "qualifier '%s' cannot be applied to fragment "
- "shader outputs", i);
- }
- break;
- default:
- assert(0);
- }
- }
-
-
- /* From section 4.3.4 of the GLSL 1.30 spec:
- * "It is an error to use centroid in in a vertex shader."
- */
- if (state->language_version >= 130
- && this->type->qualifier.flags.q.centroid
- && this->type->qualifier.flags.q.in
- && state->target == vertex_shader) {
-
- _mesa_glsl_error(&loc, state,
- "'centroid in' cannot be used in a vertex shader");
- }
-
-
- /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
- */
- if (this->type->specifier->precision != ast_precision_none
- && state->language_version != 100
- && state->language_version < 130) {
-
- _mesa_glsl_error(&loc, state,
- "precision qualifiers are supported only in GLSL ES "
- "1.00, and GLSL 1.30 and later");
- }
-
-
- /* Precision qualifiers only apply to floating point and integer types.
- *
- * From section 4.5.2 of the GLSL 1.30 spec:
- * "Any floating point or any integer declaration can have the type
- * preceded by one of these precision qualifiers [...] Literal
- * constants do not have precision qualifiers. Neither do Boolean
- * variables.
- */
- if (this->type->specifier->precision != ast_precision_none
- && !var->type->is_float()
- && !var->type->is_integer()
- && !(var->type->is_array()
- && (var->type->fields.array->is_float()
- || var->type->fields.array->is_integer()))) {
-
- _mesa_glsl_error(&loc, state,
- "precision qualifiers apply only to floating point "
- "and integer types");
- }
-
- /* Process the initializer and add its instructions to a temporary
- * list. This list will be added to the instruction stream (below) after
- * the declaration is added. This is done because in some cases (such as
- * redeclarations) the declaration may not actually be added to the
- * instruction stream.
- */
- exec_list initializer_instructions;
- if (decl->initializer != NULL) {
- YYLTYPE initializer_loc = decl->initializer->get_location();
-
- /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
- *
- * "All uniform variables are read-only and are initialized either
- * directly by an application via API commands, or indirectly by
- * OpenGL."
- */
- if ((state->language_version <= 110)
- && (var->mode == ir_var_uniform)) {
- _mesa_glsl_error(& initializer_loc, state,
- "cannot initialize uniforms in GLSL 1.10");
- }
-
- if (var->type->is_sampler()) {
- _mesa_glsl_error(& initializer_loc, state,
- "cannot initialize samplers");
- }
-
- if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
- _mesa_glsl_error(& initializer_loc, state,
- "cannot initialize %s shader input / %s",
- _mesa_glsl_shader_target_name(state->target),
- (state->target == vertex_shader)
- ? "attribute" : "varying");
- }
-
- ir_dereference *const lhs = new(ctx) ir_dereference_variable(var);
- ir_rvalue *rhs = decl->initializer->hir(&initializer_instructions,
- state);
-
- /* Calculate the constant value if this is a const or uniform
- * declaration.
- */
- if (this->type->qualifier.flags.q.constant
- || this->type->qualifier.flags.q.uniform) {
- ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs);
- if (new_rhs != NULL) {
- rhs = new_rhs;
-
- ir_constant *constant_value = rhs->constant_expression_value();
- if (!constant_value) {
- _mesa_glsl_error(& initializer_loc, state,
- "initializer of %s variable `%s' must be a "
- "constant expression",
- (this->type->qualifier.flags.q.constant)
- ? "const" : "uniform",
- decl->identifier);
- if (var->type->is_numeric()) {
- /* Reduce cascading errors. */
- var->constant_value = ir_constant::zero(ctx, var->type);
- }
- } else {
- rhs = constant_value;
- var->constant_value = constant_value;
- }
- } else {
- _mesa_glsl_error(&initializer_loc, state,
- "initializer of type %s cannot be assigned to "
- "variable of type %s",
- rhs->type->name, var->type->name);
- if (var->type->is_numeric()) {
- /* Reduce cascading errors. */
- var->constant_value = ir_constant::zero(ctx, var->type);
- }
- }
- }
-
- if (rhs && !rhs->type->is_error()) {
- bool temp = var->read_only;
- if (this->type->qualifier.flags.q.constant)
- var->read_only = false;
-
- /* Never emit code to initialize a uniform.
- */
- const glsl_type *initializer_type;
- if (!this->type->qualifier.flags.q.uniform) {
- result = do_assignment(&initializer_instructions, state,
- lhs, rhs,
- this->get_location());
- initializer_type = result->type;
- } else
- initializer_type = rhs->type;
-
- /* If the declared variable is an unsized array, it must inherrit
- * its full type from the initializer. A declaration such as
- *
- * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
- *
- * becomes
- *
- * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
- *
- * The assignment generated in the if-statement (below) will also
- * automatically handle this case for non-uniforms.
- *
- * If the declared variable is not an array, the types must
- * already match exactly. As a result, the type assignment
- * here can be done unconditionally. For non-uniforms the call
- * to do_assignment can change the type of the initializer (via
- * the implicit conversion rules). For uniforms the initializer
- * must be a constant expression, and the type of that expression
- * was validated above.
- */
- var->type = initializer_type;
-
- var->read_only = temp;
- }
- }
-
- /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
- *
- * "It is an error to write to a const variable outside of
- * its declaration, so they must be initialized when
- * declared."
- */
- if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
- _mesa_glsl_error(& loc, state,
- "const declaration of `%s' must be initialized",
- decl->identifier);
- }
-
- /* Check if this declaration is actually a re-declaration, either to
- * resize an array or add qualifiers to an existing variable.
- *
- * This is allowed for variables in the current scope, or when at
- * global scope (for built-ins in the implicit outer scope).
- */
- ir_variable *earlier = state->symbols->get_variable(decl->identifier);
- if (earlier != NULL && (state->current_function == NULL ||
- state->symbols->name_declared_this_scope(decl->identifier))) {
-
- /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
- *
- * "It is legal to declare an array without a size and then
- * later re-declare the same name as an array of the same
- * type and specify a size."
- */
- if ((earlier->type->array_size() == 0)
- && var->type->is_array()
- && (var->type->element_type() == earlier->type->element_type())) {
- /* FINISHME: This doesn't match the qualifiers on the two
- * FINISHME: declarations. It's not 100% clear whether this is
- * FINISHME: required or not.
- */
-
- /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
- *
- * "The size [of gl_TexCoord] can be at most
- * gl_MaxTextureCoords."
- */
- const unsigned size = unsigned(var->type->array_size());
- if ((strcmp("gl_TexCoord", var->name) == 0)
- && (size > state->Const.MaxTextureCoords)) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "`gl_TexCoord' array size cannot "
- "be larger than gl_MaxTextureCoords (%u)\n",
- state->Const.MaxTextureCoords);
- } else if ((size > 0) && (size <= earlier->max_array_access)) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "array size must be > %u due to "
- "previous access",
- earlier->max_array_access);
- }
-
- earlier->type = var->type;
- delete var;
- var = NULL;
- } else if (state->ARB_fragment_coord_conventions_enable
- && strcmp(var->name, "gl_FragCoord") == 0
- && earlier->type == var->type
- && earlier->mode == var->mode) {
- /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
- * qualifiers.
- */
- earlier->origin_upper_left = var->origin_upper_left;
- earlier->pixel_center_integer = var->pixel_center_integer;
-
- /* According to section 4.3.7 of the GLSL 1.30 spec,
- * the following built-in varaibles can be redeclared with an
- * interpolation qualifier:
- * * gl_FrontColor
- * * gl_BackColor
- * * gl_FrontSecondaryColor
- * * gl_BackSecondaryColor
- * * gl_Color
- * * gl_SecondaryColor
- */
- } else if (state->language_version >= 130
- && (strcmp(var->name, "gl_FrontColor") == 0
- || strcmp(var->name, "gl_BackColor") == 0
- || strcmp(var->name, "gl_FrontSecondaryColor") == 0
- || strcmp(var->name, "gl_BackSecondaryColor") == 0
- || strcmp(var->name, "gl_Color") == 0
- || strcmp(var->name, "gl_SecondaryColor") == 0)
- && earlier->type == var->type
- && earlier->mode == var->mode) {
- earlier->interpolation = var->interpolation;
-
- /* Layout qualifiers for gl_FragDepth. */
- } else if (state->AMD_conservative_depth_enable
- && strcmp(var->name, "gl_FragDepth") == 0
- && earlier->type == var->type
- && earlier->mode == var->mode) {
-
- /** From the AMD_conservative_depth spec:
- * Within any shader, the first redeclarations of gl_FragDepth
- * must appear before any use of gl_FragDepth.
- */
- if (earlier->used) {
- _mesa_glsl_error(&loc, state,
- "the first redeclaration of gl_FragDepth "
- "must appear before any use of gl_FragDepth");
- }
-
- /* Prevent inconsistent redeclaration of depth layout qualifier. */
- if (earlier->depth_layout != ir_depth_layout_none
- && earlier->depth_layout != var->depth_layout) {
- _mesa_glsl_error(&loc, state,
- "gl_FragDepth: depth layout is declared here "
- "as '%s, but it was previously declared as "
- "'%s'",
- depth_layout_string(var->depth_layout),
- depth_layout_string(earlier->depth_layout));
- }
-
- earlier->depth_layout = var->depth_layout;
-
- } else {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
- }
-
- continue;
- }
-
- /* By now, we know it's a new variable declaration (we didn't hit the
- * above "continue").
- *
- * From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
- *
- * "Identifiers starting with "gl_" are reserved for use by
- * OpenGL, and may not be declared in a shader as either a
- * variable or a function."
- */
- if (strncmp(decl->identifier, "gl_", 3) == 0)
- _mesa_glsl_error(& loc, state,
- "identifier `%s' uses reserved `gl_' prefix",
- decl->identifier);
-
- /* Add the variable to the symbol table. Note that the initializer's
- * IR was already processed earlier (though it hasn't been emitted yet),
- * without the variable in scope.
- *
- * This differs from most C-like languages, but it follows the GLSL
- * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
- * spec:
- *
- * "Within a declaration, the scope of a name starts immediately
- * after the initializer if present or immediately after the name
- * being declared if not."
- */
- if (!state->symbols->add_variable(var)) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
- "current scope", decl->identifier);
- continue;
- }
-
- /* Push the variable declaration to the top. It means that all
- * the variable declarations will appear in a funny
- * last-to-first order, but otherwise we run into trouble if a
- * function is prototyped, a global var is decled, then the
- * function is defined with usage of the global var. See
- * glslparsertest's CorrectModule.frag.
- */
- instructions->push_head(var);
- instructions->append_list(&initializer_instructions);
- }
-
-
- /* Generally, variable declarations do not have r-values. However,
- * one is used for the declaration in
- *
- * while (bool b = some_condition()) {
- * ...
- * }
- *
- * so we return the rvalue from the last seen declaration here.
- */
- return result;
-}
-
-
-ir_rvalue *
-ast_parameter_declarator::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- const struct glsl_type *type;
- const char *name = NULL;
- YYLTYPE loc = this->get_location();
-
- type = this->type->specifier->glsl_type(& name, state);
-
- if (type == NULL) {
- if (name != NULL) {
- _mesa_glsl_error(& loc, state,
- "invalid type `%s' in declaration of `%s'",
- name, this->identifier);
- } else {
- _mesa_glsl_error(& loc, state,
- "invalid type in declaration of `%s'",
- this->identifier);
- }
-
- type = glsl_type::error_type;
- }
-
- /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
- *
- * "Functions that accept no input arguments need not use void in the
- * argument list because prototypes (or definitions) are required and
- * therefore there is no ambiguity when an empty argument list "( )" is
- * declared. The idiom "(void)" as a parameter list is provided for
- * convenience."
- *
- * Placing this check here prevents a void parameter being set up
- * for a function, which avoids tripping up checks for main taking
- * parameters and lookups of an unnamed symbol.
- */
- if (type->is_void()) {
- if (this->identifier != NULL)
- _mesa_glsl_error(& loc, state,
- "named parameter cannot have type `void'");
-
- is_void = true;
- return NULL;
- }
-
- if (formal_parameter && (this->identifier == NULL)) {
- _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
- return NULL;
- }
-
- /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
- * call already handled the "vec4[..] foo" case.
- */
- if (this->is_array) {
- type = process_array_type(&loc, type, this->array_size, state);
- }
-
- if (type->array_size() == 0) {
- _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
- "a declared size.");
- type = glsl_type::error_type;
- }
-
- is_void = false;
- ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
-
- /* Apply any specified qualifiers to the parameter declaration. Note that
- * for function parameters the default mode is 'in'.
- */
- apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
-
- instructions->push_tail(var);
-
- /* Parameter declarations do not have r-values.
- */
- return NULL;
-}
-
-
-void
-ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
- bool formal,
- exec_list *ir_parameters,
- _mesa_glsl_parse_state *state)
-{
- ast_parameter_declarator *void_param = NULL;
- unsigned count = 0;
-
- foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
- param->formal_parameter = formal;
- param->hir(ir_parameters, state);
-
- if (param->is_void)
- void_param = param;
-
- count++;
- }
-
- if ((void_param != NULL) && (count > 1)) {
- YYLTYPE loc = void_param->get_location();
-
- _mesa_glsl_error(& loc, state,
- "`void' parameter must be only parameter");
- }
-}
-
-
-void
-emit_function(_mesa_glsl_parse_state *state, exec_list *instructions,
- ir_function *f)
-{
- /* Emit the new function header */
- if (state->current_function == NULL) {
- instructions->push_tail(f);
- } else {
- /* IR invariants disallow function declarations or definitions nested
- * within other function definitions. Insert the new ir_function
- * block in the instruction sequence before the ir_function block
- * containing the current ir_function_signature.
- */
- ir_function *const curr =
- const_cast<ir_function *>(state->current_function->function());
-
- curr->insert_before(f);
- }
-}
-
-
-ir_rvalue *
-ast_function::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- ir_function *f = NULL;
- ir_function_signature *sig = NULL;
- exec_list hir_parameters;
-
- const char *const name = identifier;
-
- /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
- *
- * "Function declarations (prototypes) cannot occur inside of functions;
- * they must be at global scope, or for the built-in functions, outside
- * the global scope."
- *
- * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
- *
- * "User defined functions may only be defined within the global scope."
- *
- * Note that this language does not appear in GLSL 1.10.
- */
- if ((state->current_function != NULL) && (state->language_version != 110)) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state,
- "declaration of function `%s' not allowed within "
- "function body", name);
- }
-
- /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
- *
- * "Identifiers starting with "gl_" are reserved for use by
- * OpenGL, and may not be declared in a shader as either a
- * variable or a function."
- */
- if (strncmp(name, "gl_", 3) == 0) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state,
- "identifier `%s' uses reserved `gl_' prefix", name);
- }
-
- /* Convert the list of function parameters to HIR now so that they can be
- * used below to compare this function's signature with previously seen
- * signatures for functions with the same name.
- */
- ast_parameter_declarator::parameters_to_hir(& this->parameters,
- is_definition,
- & hir_parameters, state);
-
- const char *return_type_name;
- const glsl_type *return_type =
- this->return_type->specifier->glsl_type(& return_type_name, state);
-
- if (!return_type) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state,
- "function `%s' has undeclared return type `%s'",
- name, return_type_name);
- return_type = glsl_type::error_type;
- }
-
- /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
- * "No qualifier is allowed on the return type of a function."
- */
- if (this->return_type->has_qualifiers()) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(& loc, state,
- "function `%s' return type has qualifiers", name);
- }
-
- /* Verify that this function's signature either doesn't match a previously
- * seen signature for a function with the same name, or, if a match is found,
- * that the previously seen signature does not have an associated definition.
- */
- f = state->symbols->get_function(name);
- if (f != NULL && (state->es_shader || f->has_user_signature())) {
- sig = f->exact_matching_signature(&hir_parameters);
- if (sig != NULL) {
- const char *badvar = sig->qualifiers_match(&hir_parameters);
- if (badvar != NULL) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
- "qualifiers don't match prototype", name, badvar);
- }
-
- if (sig->return_type != return_type) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
- "match prototype", name);
- }
-
- if (is_definition && sig->is_defined) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
- }
- }
- } else {
- f = new(ctx) ir_function(name);
- if (!state->symbols->add_function(f)) {
- /* This function name shadows a non-function use of the same name. */
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
- "non-function", name);
- return NULL;
- }
-
- emit_function(state, instructions, f);
- }
-
- /* Verify the return type of main() */
- if (strcmp(name, "main") == 0) {
- if (! return_type->is_void()) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "main() must return void");
- }
-
- if (!hir_parameters.is_empty()) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "main() must not take any parameters");
- }
- }
-
- /* Finish storing the information about this new function in its signature.
- */
- if (sig == NULL) {
- sig = new(ctx) ir_function_signature(return_type);
- f->add_signature(sig);
- }
-
- sig->replace_parameters(&hir_parameters);
- signature = sig;
-
- /* Function declarations (prototypes) do not have r-values.
- */
- return NULL;
-}
-
-
-ir_rvalue *
-ast_function_definition::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- prototype->is_definition = true;
- prototype->hir(instructions, state);
-
- ir_function_signature *signature = prototype->signature;
- if (signature == NULL)
- return NULL;
-
- assert(state->current_function == NULL);
- state->current_function = signature;
- state->found_return = false;
-
- /* Duplicate parameters declared in the prototype as concrete variables.
- * Add these to the symbol table.
- */
- state->symbols->push_scope();
- foreach_iter(exec_list_iterator, iter, signature->parameters) {
- ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
-
- assert(var != NULL);
-
- /* The only way a parameter would "exist" is if two parameters have
- * the same name.
- */
- if (state->symbols->name_declared_this_scope(var->name)) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
- } else {
- state->symbols->add_variable(var);
- }
- }
-
- /* Convert the body of the function to HIR. */
- this->body->hir(&signature->body, state);
- signature->is_defined = true;
-
- state->symbols->pop_scope();
-
- assert(state->current_function == signature);
- state->current_function = NULL;
-
- if (!signature->return_type->is_void() && !state->found_return) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
- "%s, but no return statement",
- signature->function_name(),
- signature->return_type->name);
- }
-
- /* Function definitions do not have r-values.
- */
- return NULL;
-}
-
-
-ir_rvalue *
-ast_jump_statement::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
-
- switch (mode) {
- case ast_return: {
- ir_return *inst;
- assert(state->current_function);
-
- if (opt_return_value) {
- ir_rvalue *const ret = opt_return_value->hir(instructions, state);
-
- /* The value of the return type can be NULL if the shader says
- * 'return foo();' and foo() is a function that returns void.
- *
- * NOTE: The GLSL spec doesn't say that this is an error. The type
- * of the return value is void. If the return type of the function is
- * also void, then this should compile without error. Seriously.
- */
- const glsl_type *const ret_type =
- (ret == NULL) ? glsl_type::void_type : ret->type;
-
- /* Implicit conversions are not allowed for return values. */
- if (state->current_function->return_type != ret_type) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state,
- "`return' with wrong type %s, in function `%s' "
- "returning %s",
- ret_type->name,
- state->current_function->function_name(),
- state->current_function->return_type->name);
- }
-
- inst = new(ctx) ir_return(ret);
- } else {
- if (state->current_function->return_type->base_type !=
- GLSL_TYPE_VOID) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state,
- "`return' with no value, in function %s returning "
- "non-void",
- state->current_function->function_name());
- }
- inst = new(ctx) ir_return;
- }
-
- state->found_return = true;
- instructions->push_tail(inst);
- break;
- }
-
- case ast_discard:
- if (state->target != fragment_shader) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state,
- "`discard' may only appear in a fragment shader");
- }
- instructions->push_tail(new(ctx) ir_discard);
- break;
-
- case ast_break:
- case ast_continue:
- /* FINISHME: Handle switch-statements. They cannot contain 'continue',
- * FINISHME: and they use a different IR instruction for 'break'.
- */
- /* FINISHME: Correctly handle the nesting. If a switch-statement is
- * FINISHME: inside a loop, a 'continue' is valid and will bind to the
- * FINISHME: loop.
- */
- if (state->loop_or_switch_nesting == NULL) {
- YYLTYPE loc = this->get_location();
-
- _mesa_glsl_error(& loc, state,
- "`%s' may only appear in a loop",
- (mode == ast_break) ? "break" : "continue");
- } else {
- ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
-
- /* Inline the for loop expression again, since we don't know
- * where near the end of the loop body the normal copy of it
- * is going to be placed.
- */
- if (mode == ast_continue &&
- state->loop_or_switch_nesting_ast->rest_expression) {
- state->loop_or_switch_nesting_ast->rest_expression->hir(instructions,
- state);
- }
-
- if (loop != NULL) {
- ir_loop_jump *const jump =
- new(ctx) ir_loop_jump((mode == ast_break)
- ? ir_loop_jump::jump_break
- : ir_loop_jump::jump_continue);
- instructions->push_tail(jump);
- }
- }
-
- break;
- }
-
- /* Jump instructions do not have r-values.
- */
- return NULL;
-}
-
-
-ir_rvalue *
-ast_selection_statement::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
-
- ir_rvalue *const condition = this->condition->hir(instructions, state);
-
- /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
- *
- * "Any expression whose type evaluates to a Boolean can be used as the
- * conditional expression bool-expression. Vector types are not accepted
- * as the expression to if."
- *
- * The checks are separated so that higher quality diagnostics can be
- * generated for cases where both rules are violated.
- */
- if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
- YYLTYPE loc = this->condition->get_location();
-
- _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
- "boolean");
- }
-
- ir_if *const stmt = new(ctx) ir_if(condition);
-
- if (then_statement != NULL) {
- state->symbols->push_scope();
- then_statement->hir(& stmt->then_instructions, state);
- state->symbols->pop_scope();
- }
-
- if (else_statement != NULL) {
- state->symbols->push_scope();
- else_statement->hir(& stmt->else_instructions, state);
- state->symbols->pop_scope();
- }
-
- instructions->push_tail(stmt);
-
- /* if-statements do not have r-values.
- */
- return NULL;
-}
-
-
-void
-ast_iteration_statement::condition_to_hir(ir_loop *stmt,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
-
- if (condition != NULL) {
- ir_rvalue *const cond =
- condition->hir(& stmt->body_instructions, state);
-
- if ((cond == NULL)
- || !cond->type->is_boolean() || !cond->type->is_scalar()) {
- YYLTYPE loc = condition->get_location();
-
- _mesa_glsl_error(& loc, state,
- "loop condition must be scalar boolean");
- } else {
- /* As the first code in the loop body, generate a block that looks
- * like 'if (!condition) break;' as the loop termination condition.
- */
- ir_rvalue *const not_cond =
- new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
- NULL);
-
- ir_if *const if_stmt = new(ctx) ir_if(not_cond);
-
- ir_jump *const break_stmt =
- new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
-
- if_stmt->then_instructions.push_tail(break_stmt);
- stmt->body_instructions.push_tail(if_stmt);
- }
- }
-}
-
-
-ir_rvalue *
-ast_iteration_statement::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
-
- /* For-loops and while-loops start a new scope, but do-while loops do not.
- */
- if (mode != ast_do_while)
- state->symbols->push_scope();
-
- if (init_statement != NULL)
- init_statement->hir(instructions, state);
-
- ir_loop *const stmt = new(ctx) ir_loop();
- instructions->push_tail(stmt);
-
- /* Track the current loop and / or switch-statement nesting.
- */
- ir_instruction *const nesting = state->loop_or_switch_nesting;
- ast_iteration_statement *nesting_ast = state->loop_or_switch_nesting_ast;
-
- state->loop_or_switch_nesting = stmt;
- state->loop_or_switch_nesting_ast = this;
-
- if (mode != ast_do_while)
- condition_to_hir(stmt, state);
-
- if (body != NULL)
- body->hir(& stmt->body_instructions, state);
-
- if (rest_expression != NULL)
- rest_expression->hir(& stmt->body_instructions, state);
-
- if (mode == ast_do_while)
- condition_to_hir(stmt, state);
-
- if (mode != ast_do_while)
- state->symbols->pop_scope();
-
- /* Restore previous nesting before returning.
- */
- state->loop_or_switch_nesting = nesting;
- state->loop_or_switch_nesting_ast = nesting_ast;
-
- /* Loops do not have r-values.
- */
- return NULL;
-}
-
-
-ir_rvalue *
-ast_type_specifier::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- if (!this->is_precision_statement && this->structure == NULL)
- return NULL;
-
- YYLTYPE loc = this->get_location();
-
- if (this->precision != ast_precision_none
- && state->language_version != 100
- && state->language_version < 130) {
- _mesa_glsl_error(&loc, state,
- "precision qualifiers exist only in "
- "GLSL ES 1.00, and GLSL 1.30 and later");
- return NULL;
- }
- if (this->precision != ast_precision_none
- && this->structure != NULL) {
- _mesa_glsl_error(&loc, state,
- "precision qualifiers do not apply to structures");
- return NULL;
- }
-
- /* If this is a precision statement, check that the type to which it is
- * applied is either float or int.
- *
- * From section 4.5.3 of the GLSL 1.30 spec:
- * "The precision statement
- * precision precision-qualifier type;
- * can be used to establish a default precision qualifier. The type
- * field can be either int or float [...]. Any other types or
- * qualifiers will result in an error.
- */
- if (this->is_precision_statement) {
- assert(this->precision != ast_precision_none);
- assert(this->structure == NULL); /* The check for structures was
- * performed above. */
- if (this->is_array) {
- _mesa_glsl_error(&loc, state,
- "default precision statements do not apply to "
- "arrays");
- return NULL;
- }
- if (this->type_specifier != ast_float
- && this->type_specifier != ast_int) {
- _mesa_glsl_error(&loc, state,
- "default precision statements apply only to types "
- "float and int");
- return NULL;
- }
-
- /* FINISHME: Translate precision statements into IR. */
- return NULL;
- }
-
- if (this->structure != NULL)
- return this->structure->hir(instructions, state);
-
- return NULL;
-}
-
-
-ir_rvalue *
-ast_struct_specifier::hir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- unsigned decl_count = 0;
-
- /* Make an initial pass over the list of structure fields to determine how
- * many there are. Each element in this list is an ast_declarator_list.
- * This means that we actually need to count the number of elements in the
- * 'declarations' list in each of the elements.
- */
- foreach_list_typed (ast_declarator_list, decl_list, link,
- &this->declarations) {
- foreach_list_const (decl_ptr, & decl_list->declarations) {
- decl_count++;
- }
- }
-
- /* Allocate storage for the structure fields and process the field
- * declarations. As the declarations are processed, try to also convert
- * the types to HIR. This ensures that structure definitions embedded in
- * other structure definitions are processed.
- */
- glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
- decl_count);
-
- unsigned i = 0;
- foreach_list_typed (ast_declarator_list, decl_list, link,
- &this->declarations) {
- const char *type_name;
-
- decl_list->type->specifier->hir(instructions, state);
-
- /* Section 10.9 of the GLSL ES 1.00 specification states that
- * embedded structure definitions have been removed from the language.
- */
- if (state->es_shader && decl_list->type->specifier->structure != NULL) {
- YYLTYPE loc = this->get_location();
- _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
- "not allowed in GLSL ES 1.00.");
- }
-
- const glsl_type *decl_type =
- decl_list->type->specifier->glsl_type(& type_name, state);
-
- foreach_list_typed (ast_declaration, decl, link,
- &decl_list->declarations) {
- const struct glsl_type *field_type = decl_type;
- if (decl->is_array) {
- YYLTYPE loc = decl->get_location();
- field_type = process_array_type(&loc, decl_type, decl->array_size,
- state);
- }
- fields[i].type = (field_type != NULL)
- ? field_type : glsl_type::error_type;
- fields[i].name = decl->identifier;
- i++;
- }
- }
-
- assert(i == decl_count);
-
- const glsl_type *t =
- glsl_type::get_record_instance(fields, decl_count, this->name);
-
- YYLTYPE loc = this->get_location();
- if (!state->symbols->add_type(name, t)) {
- _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
- } else {
-
- const glsl_type **s = (const glsl_type **)
- realloc(state->user_structures,
- sizeof(state->user_structures[0]) *
- (state->num_user_structures + 1));
- if (s != NULL) {
- s[state->num_user_structures] = t;
- state->user_structures = s;
- state->num_user_structures++;
- }
- }
-
- /* Structure type definitions do not have r-values.
- */
- return NULL;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 ast_to_hir.c
+ * Convert abstract syntax to to high-level intermediate reprensentation (HIR).
+ *
+ * During the conversion to HIR, the majority of the symantic checking is
+ * preformed on the program. This includes:
+ *
+ * * Symbol table management
+ * * Type checking
+ * * Function binding
+ *
+ * The majority of this work could be done during parsing, and the parser could
+ * probably generate HIR directly. However, this results in frequent changes
+ * to the parser code. Since we do not assume that every system this complier
+ * is built on will have Flex and Bison installed, we have to store the code
+ * generated by these tools in our version control system. In other parts of
+ * the system we've seen problems where a parser was changed but the generated
+ * code was not committed, merge conflicts where created because two developers
+ * had slightly different versions of Bison installed, etc.
+ *
+ * I have also noticed that running Bison generated parsers in GDB is very
+ * irritating. When you get a segfault on '$$ = $1->foo', you can't very
+ * well 'print $1' in GDB.
+ *
+ * As a result, my preference is to put as little C code as possible in the
+ * parser (and lexer) sources.
+ */
+
+#include "main/core.h" /* for struct gl_extensions */
+#include "glsl_symbol_table.h"
+#include "glsl_parser_extras.h"
+#include "ast.h"
+#include "glsl_types.h"
+#include "ir.h"
+
+void
+_mesa_ast_to_hir(exec_list *instructions, struct _mesa_glsl_parse_state *state)
+{
+ _mesa_glsl_initialize_variables(instructions, state);
+ _mesa_glsl_initialize_functions(state);
+
+ state->symbols->language_version = state->language_version;
+
+ state->current_function = NULL;
+
+ /* Section 4.2 of the GLSL 1.20 specification states:
+ * "The built-in functions are scoped in a scope outside the global scope
+ * users declare global variables in. That is, a shader's global scope,
+ * available for user-defined functions and global variables, is nested
+ * inside the scope containing the built-in functions."
+ *
+ * Since built-in functions like ftransform() access built-in variables,
+ * it follows that those must be in the outer scope as well.
+ *
+ * We push scope here to create this nesting effect...but don't pop.
+ * This way, a shader's globals are still in the symbol table for use
+ * by the linker.
+ */
+ state->symbols->push_scope();
+
+ foreach_list_typed (ast_node, ast, link, & state->translation_unit)
+ ast->hir(instructions, state);
+}
+
+
+/**
+ * If a conversion is available, convert one operand to a different type
+ *
+ * The \c from \c ir_rvalue is converted "in place".
+ *
+ * \param to Type that the operand it to be converted to
+ * \param from Operand that is being converted
+ * \param state GLSL compiler state
+ *
+ * \return
+ * If a conversion is possible (or unnecessary), \c true is returned.
+ * Otherwise \c false is returned.
+ */
+bool
+apply_implicit_conversion(const glsl_type *to, ir_rvalue * &from,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ if (to->base_type == from->type->base_type)
+ return true;
+
+ /* This conversion was added in GLSL 1.20. If the compilation mode is
+ * GLSL 1.10, the conversion is skipped.
+ */
+ if (state->language_version < 120)
+ return false;
+
+ /* From page 27 (page 33 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "There are no implicit array or structure conversions. For
+ * example, an array of int cannot be implicitly converted to an
+ * array of float. There are no implicit conversions between
+ * signed and unsigned integers."
+ */
+ /* FINISHME: The above comment is partially a lie. There is int/uint
+ * FINISHME: conversion for immediate constants.
+ */
+ if (!to->is_float() || !from->type->is_numeric())
+ return false;
+
+ /* Convert to a floating point type with the same number of components
+ * as the original type - i.e. int to float, not int to vec4.
+ */
+ to = glsl_type::get_instance(GLSL_TYPE_FLOAT, from->type->vector_elements,
+ from->type->matrix_columns);
+
+ switch (from->type->base_type) {
+ case GLSL_TYPE_INT:
+ from = new(ctx) ir_expression(ir_unop_i2f, to, from, NULL);
+ break;
+ case GLSL_TYPE_UINT:
+ from = new(ctx) ir_expression(ir_unop_u2f, to, from, NULL);
+ break;
+ case GLSL_TYPE_BOOL:
+ from = new(ctx) ir_expression(ir_unop_b2f, to, from, NULL);
+ break;
+ default:
+ assert(0);
+ }
+
+ return true;
+}
+
+
+static const struct glsl_type *
+arithmetic_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
+ bool multiply,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ const glsl_type *type_a = value_a->type;
+ const glsl_type *type_b = value_b->type;
+
+ /* From GLSL 1.50 spec, page 56:
+ *
+ * "The arithmetic binary operators add (+), subtract (-),
+ * multiply (*), and divide (/) operate on integer and
+ * floating-point scalars, vectors, and matrices."
+ */
+ if (!type_a->is_numeric() || !type_b->is_numeric()) {
+ _mesa_glsl_error(loc, state,
+ "Operands to arithmetic operators must be numeric");
+ return glsl_type::error_type;
+ }
+
+
+ /* "If one operand is floating-point based and the other is
+ * not, then the conversions from Section 4.1.10 "Implicit
+ * Conversions" are applied to the non-floating-point-based operand."
+ */
+ if (!apply_implicit_conversion(type_a, value_b, state)
+ && !apply_implicit_conversion(type_b, value_a, state)) {
+ _mesa_glsl_error(loc, state,
+ "Could not implicitly convert operands to "
+ "arithmetic operator");
+ return glsl_type::error_type;
+ }
+ type_a = value_a->type;
+ type_b = value_b->type;
+
+ /* "If the operands are integer types, they must both be signed or
+ * both be unsigned."
+ *
+ * From this rule and the preceeding conversion it can be inferred that
+ * both types must be GLSL_TYPE_FLOAT, or GLSL_TYPE_UINT, or GLSL_TYPE_INT.
+ * The is_numeric check above already filtered out the case where either
+ * type is not one of these, so now the base types need only be tested for
+ * equality.
+ */
+ if (type_a->base_type != type_b->base_type) {
+ _mesa_glsl_error(loc, state,
+ "base type mismatch for arithmetic operator");
+ return glsl_type::error_type;
+ }
+
+ /* "All arithmetic binary operators result in the same fundamental type
+ * (signed integer, unsigned integer, or floating-point) as the
+ * operands they operate on, after operand type conversion. After
+ * conversion, the following cases are valid
+ *
+ * * The two operands are scalars. In this case the operation is
+ * applied, resulting in a scalar."
+ */
+ if (type_a->is_scalar() && type_b->is_scalar())
+ return type_a;
+
+ /* "* One operand is a scalar, and the other is a vector or matrix.
+ * In this case, the scalar operation is applied independently to each
+ * component of the vector or matrix, resulting in the same size
+ * vector or matrix."
+ */
+ if (type_a->is_scalar()) {
+ if (!type_b->is_scalar())
+ return type_b;
+ } else if (type_b->is_scalar()) {
+ return type_a;
+ }
+
+ /* All of the combinations of <scalar, scalar>, <vector, scalar>,
+ * <scalar, vector>, <scalar, matrix>, and <matrix, scalar> have been
+ * handled.
+ */
+ assert(!type_a->is_scalar());
+ assert(!type_b->is_scalar());
+
+ /* "* The two operands are vectors of the same size. In this case, the
+ * operation is done component-wise resulting in the same size
+ * vector."
+ */
+ if (type_a->is_vector() && type_b->is_vector()) {
+ if (type_a == type_b) {
+ return type_a;
+ } else {
+ _mesa_glsl_error(loc, state,
+ "vector size mismatch for arithmetic operator");
+ return glsl_type::error_type;
+ }
+ }
+
+ /* All of the combinations of <scalar, scalar>, <vector, scalar>,
+ * <scalar, vector>, <scalar, matrix>, <matrix, scalar>, and
+ * <vector, vector> have been handled. At least one of the operands must
+ * be matrix. Further, since there are no integer matrix types, the base
+ * type of both operands must be float.
+ */
+ assert(type_a->is_matrix() || type_b->is_matrix());
+ assert(type_a->base_type == GLSL_TYPE_FLOAT);
+ assert(type_b->base_type == GLSL_TYPE_FLOAT);
+
+ /* "* The operator is add (+), subtract (-), or divide (/), and the
+ * operands are matrices with the same number of rows and the same
+ * number of columns. In this case, the operation is done component-
+ * wise resulting in the same size matrix."
+ * * The operator is multiply (*), where both operands are matrices or
+ * one operand is a vector and the other a matrix. A right vector
+ * operand is treated as a column vector and a left vector operand as a
+ * row vector. In all these cases, it is required that the number of
+ * columns of the left operand is equal to the number of rows of the
+ * right operand. Then, the multiply (*) operation does a linear
+ * algebraic multiply, yielding an object that has the same number of
+ * rows as the left operand and the same number of columns as the right
+ * operand. Section 5.10 "Vector and Matrix Operations" explains in
+ * more detail how vectors and matrices are operated on."
+ */
+ if (! multiply) {
+ if (type_a == type_b)
+ return type_a;
+ } else {
+ if (type_a->is_matrix() && type_b->is_matrix()) {
+ /* Matrix multiply. The columns of A must match the rows of B. Given
+ * the other previously tested constraints, this means the vector type
+ * of a row from A must be the same as the vector type of a column from
+ * B.
+ */
+ if (type_a->row_type() == type_b->column_type()) {
+ /* The resulting matrix has the number of columns of matrix B and
+ * the number of rows of matrix A. We get the row count of A by
+ * looking at the size of a vector that makes up a column. The
+ * transpose (size of a row) is done for B.
+ */
+ const glsl_type *const type =
+ glsl_type::get_instance(type_a->base_type,
+ type_a->column_type()->vector_elements,
+ type_b->row_type()->vector_elements);
+ assert(type != glsl_type::error_type);
+
+ return type;
+ }
+ } else if (type_a->is_matrix()) {
+ /* A is a matrix and B is a column vector. Columns of A must match
+ * rows of B. Given the other previously tested constraints, this
+ * means the vector type of a row from A must be the same as the
+ * vector the type of B.
+ */
+ if (type_a->row_type() == type_b) {
+ /* The resulting vector has a number of elements equal to
+ * the number of rows of matrix A. */
+ const glsl_type *const type =
+ glsl_type::get_instance(type_a->base_type,
+ type_a->column_type()->vector_elements,
+ 1);
+ assert(type != glsl_type::error_type);
+
+ return type;
+ }
+ } else {
+ assert(type_b->is_matrix());
+
+ /* A is a row vector and B is a matrix. Columns of A must match rows
+ * of B. Given the other previously tested constraints, this means
+ * the type of A must be the same as the vector type of a column from
+ * B.
+ */
+ if (type_a == type_b->column_type()) {
+ /* The resulting vector has a number of elements equal to
+ * the number of columns of matrix B. */
+ const glsl_type *const type =
+ glsl_type::get_instance(type_a->base_type,
+ type_b->row_type()->vector_elements,
+ 1);
+ assert(type != glsl_type::error_type);
+
+ return type;
+ }
+ }
+
+ _mesa_glsl_error(loc, state, "size mismatch for matrix multiplication");
+ return glsl_type::error_type;
+ }
+
+
+ /* "All other cases are illegal."
+ */
+ _mesa_glsl_error(loc, state, "type mismatch");
+ return glsl_type::error_type;
+}
+
+
+static const struct glsl_type *
+unary_arithmetic_result_type(const struct glsl_type *type,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ /* From GLSL 1.50 spec, page 57:
+ *
+ * "The arithmetic unary operators negate (-), post- and pre-increment
+ * and decrement (-- and ++) operate on integer or floating-point
+ * values (including vectors and matrices). All unary operators work
+ * component-wise on their operands. These result with the same type
+ * they operated on."
+ */
+ if (!type->is_numeric()) {
+ _mesa_glsl_error(loc, state,
+ "Operands to arithmetic operators must be numeric");
+ return glsl_type::error_type;
+ }
+
+ return type;
+}
+
+/**
+ * \brief Return the result type of a bit-logic operation.
+ *
+ * If the given types to the bit-logic operator are invalid, return
+ * glsl_type::error_type.
+ *
+ * \param type_a Type of LHS of bit-logic op
+ * \param type_b Type of RHS of bit-logic op
+ */
+static const struct glsl_type *
+bit_logic_result_type(const struct glsl_type *type_a,
+ const struct glsl_type *type_b,
+ ast_operators op,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ if (state->language_version < 130) {
+ _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
+ return glsl_type::error_type;
+ }
+
+ /* From page 50 (page 56 of PDF) of GLSL 1.30 spec:
+ *
+ * "The bitwise operators and (&), exclusive-or (^), and inclusive-or
+ * (|). The operands must be of type signed or unsigned integers or
+ * integer vectors."
+ */
+ if (!type_a->is_integer()) {
+ _mesa_glsl_error(loc, state, "LHS of `%s' must be an integer",
+ ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+ if (!type_b->is_integer()) {
+ _mesa_glsl_error(loc, state, "RHS of `%s' must be an integer",
+ ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* "The fundamental types of the operands (signed or unsigned) must
+ * match,"
+ */
+ if (type_a->base_type != type_b->base_type) {
+ _mesa_glsl_error(loc, state, "operands of `%s' must have the same "
+ "base type", ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* "The operands cannot be vectors of differing size." */
+ if (type_a->is_vector() &&
+ type_b->is_vector() &&
+ type_a->vector_elements != type_b->vector_elements) {
+ _mesa_glsl_error(loc, state, "operands of `%s' cannot be vectors of "
+ "different sizes", ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* "If one operand is a scalar and the other a vector, the scalar is
+ * applied component-wise to the vector, resulting in the same type as
+ * the vector. The fundamental types of the operands [...] will be the
+ * resulting fundamental type."
+ */
+ if (type_a->is_scalar())
+ return type_b;
+ else
+ return type_a;
+}
+
+static const struct glsl_type *
+modulus_result_type(const struct glsl_type *type_a,
+ const struct glsl_type *type_b,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ if (state->language_version < 130) {
+ _mesa_glsl_error(loc, state,
+ "operator '%%' is reserved in %s",
+ state->version_string);
+ return glsl_type::error_type;
+ }
+
+ /* From GLSL 1.50 spec, page 56:
+ * "The operator modulus (%) operates on signed or unsigned integers or
+ * integer vectors. The operand types must both be signed or both be
+ * unsigned."
+ */
+ if (!type_a->is_integer() || !type_b->is_integer()
+ || (type_a->base_type != type_b->base_type)) {
+ _mesa_glsl_error(loc, state, "type mismatch");
+ return glsl_type::error_type;
+ }
+
+ /* "The operands cannot be vectors of differing size. If one operand is
+ * a scalar and the other vector, then the scalar is applied component-
+ * wise to the vector, resulting in the same type as the vector. If both
+ * are vectors of the same size, the result is computed component-wise."
+ */
+ if (type_a->is_vector()) {
+ if (!type_b->is_vector()
+ || (type_a->vector_elements == type_b->vector_elements))
+ return type_a;
+ } else
+ return type_b;
+
+ /* "The operator modulus (%) is not defined for any other data types
+ * (non-integer types)."
+ */
+ _mesa_glsl_error(loc, state, "type mismatch");
+ return glsl_type::error_type;
+}
+
+
+static const struct glsl_type *
+relational_result_type(ir_rvalue * &value_a, ir_rvalue * &value_b,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ const glsl_type *type_a = value_a->type;
+ const glsl_type *type_b = value_b->type;
+
+ /* From GLSL 1.50 spec, page 56:
+ * "The relational operators greater than (>), less than (<), greater
+ * than or equal (>=), and less than or equal (<=) operate only on
+ * scalar integer and scalar floating-point expressions."
+ */
+ if (!type_a->is_numeric()
+ || !type_b->is_numeric()
+ || !type_a->is_scalar()
+ || !type_b->is_scalar()) {
+ _mesa_glsl_error(loc, state,
+ "Operands to relational operators must be scalar and "
+ "numeric");
+ return glsl_type::error_type;
+ }
+
+ /* "Either the operands' types must match, or the conversions from
+ * Section 4.1.10 "Implicit Conversions" will be applied to the integer
+ * operand, after which the types must match."
+ */
+ if (!apply_implicit_conversion(type_a, value_b, state)
+ && !apply_implicit_conversion(type_b, value_a, state)) {
+ _mesa_glsl_error(loc, state,
+ "Could not implicitly convert operands to "
+ "relational operator");
+ return glsl_type::error_type;
+ }
+ type_a = value_a->type;
+ type_b = value_b->type;
+
+ if (type_a->base_type != type_b->base_type) {
+ _mesa_glsl_error(loc, state, "base type mismatch");
+ return glsl_type::error_type;
+ }
+
+ /* "The result is scalar Boolean."
+ */
+ return glsl_type::bool_type;
+}
+
+/**
+ * \brief Return the result type of a bit-shift operation.
+ *
+ * If the given types to the bit-shift operator are invalid, return
+ * glsl_type::error_type.
+ *
+ * \param type_a Type of LHS of bit-shift op
+ * \param type_b Type of RHS of bit-shift op
+ */
+static const struct glsl_type *
+shift_result_type(const struct glsl_type *type_a,
+ const struct glsl_type *type_b,
+ ast_operators op,
+ struct _mesa_glsl_parse_state *state, YYLTYPE *loc)
+{
+ if (state->language_version < 130) {
+ _mesa_glsl_error(loc, state, "bit operations require GLSL 1.30");
+ return glsl_type::error_type;
+ }
+
+ /* From page 50 (page 56 of the PDF) of the GLSL 1.30 spec:
+ *
+ * "The shift operators (<<) and (>>). For both operators, the operands
+ * must be signed or unsigned integers or integer vectors. One operand
+ * can be signed while the other is unsigned."
+ */
+ if (!type_a->is_integer()) {
+ _mesa_glsl_error(loc, state, "LHS of operator %s must be an integer or "
+ "integer vector", ast_expression::operator_string(op));
+ return glsl_type::error_type;
+
+ }
+ if (!type_b->is_integer()) {
+ _mesa_glsl_error(loc, state, "RHS of operator %s must be an integer or "
+ "integer vector", ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* "If the first operand is a scalar, the second operand has to be
+ * a scalar as well."
+ */
+ if (type_a->is_scalar() && !type_b->is_scalar()) {
+ _mesa_glsl_error(loc, state, "If the first operand of %s is scalar, the "
+ "second must be scalar as well",
+ ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* If both operands are vectors, check that they have same number of
+ * elements.
+ */
+ if (type_a->is_vector() &&
+ type_b->is_vector() &&
+ type_a->vector_elements != type_b->vector_elements) {
+ _mesa_glsl_error(loc, state, "Vector operands to operator %s must "
+ "have same number of elements",
+ ast_expression::operator_string(op));
+ return glsl_type::error_type;
+ }
+
+ /* "In all cases, the resulting type will be the same type as the left
+ * operand."
+ */
+ return type_a;
+}
+
+/**
+ * Validates that a value can be assigned to a location with a specified type
+ *
+ * Validates that \c rhs can be assigned to some location. If the types are
+ * not an exact match but an automatic conversion is possible, \c rhs will be
+ * converted.
+ *
+ * \return
+ * \c NULL if \c rhs cannot be assigned to a location with type \c lhs_type.
+ * Otherwise the actual RHS to be assigned will be returned. This may be
+ * \c rhs, or it may be \c rhs after some type conversion.
+ *
+ * \note
+ * In addition to being used for assignments, this function is used to
+ * type-check return values.
+ */
+ir_rvalue *
+validate_assignment(struct _mesa_glsl_parse_state *state,
+ const glsl_type *lhs_type, ir_rvalue *rhs)
+{
+ /* If there is already some error in the RHS, just return it. Anything
+ * else will lead to an avalanche of error message back to the user.
+ */
+ if (rhs->type->is_error())
+ return rhs;
+
+ /* If the types are identical, the assignment can trivially proceed.
+ */
+ if (rhs->type == lhs_type)
+ return rhs;
+
+ /* If the array element types are the same and the size of the LHS is zero,
+ * the assignment is okay.
+ *
+ * Note: Whole-array assignments are not permitted in GLSL 1.10, but this
+ * is handled by ir_dereference::is_lvalue.
+ */
+ if (lhs_type->is_array() && rhs->type->is_array()
+ && (lhs_type->element_type() == rhs->type->element_type())
+ && (lhs_type->array_size() == 0)) {
+ return rhs;
+ }
+
+ /* Check for implicit conversion in GLSL 1.20 */
+ if (apply_implicit_conversion(lhs_type, rhs, state)) {
+ if (rhs->type == lhs_type)
+ return rhs;
+ }
+
+ return NULL;
+}
+
+ir_rvalue *
+do_assignment(exec_list *instructions, struct _mesa_glsl_parse_state *state,
+ ir_rvalue *lhs, ir_rvalue *rhs,
+ YYLTYPE lhs_loc)
+{
+ void *ctx = state;
+ bool error_emitted = (lhs->type->is_error() || rhs->type->is_error());
+
+ if (!error_emitted) {
+ if (lhs->variable_referenced() != NULL
+ && lhs->variable_referenced()->read_only) {
+ _mesa_glsl_error(&lhs_loc, state,
+ "assignment to read-only variable '%s'",
+ lhs->variable_referenced()->name);
+ error_emitted = true;
+
+ } else if (!lhs->is_lvalue()) {
+ _mesa_glsl_error(& lhs_loc, state, "non-lvalue in assignment");
+ error_emitted = true;
+ }
+
+ if (state->es_shader && lhs->type->is_array()) {
+ _mesa_glsl_error(&lhs_loc, state, "whole array assignment is not "
+ "allowed in GLSL ES 1.00.");
+ error_emitted = true;
+ }
+ }
+
+ ir_rvalue *new_rhs = validate_assignment(state, lhs->type, rhs);
+ if (new_rhs == NULL) {
+ _mesa_glsl_error(& lhs_loc, state, "type mismatch");
+ } else {
+ rhs = new_rhs;
+
+ /* If the LHS array was not declared with a size, it takes it size from
+ * the RHS. If the LHS is an l-value and a whole array, it must be a
+ * dereference of a variable. Any other case would require that the LHS
+ * is either not an l-value or not a whole array.
+ */
+ if (lhs->type->array_size() == 0) {
+ ir_dereference *const d = lhs->as_dereference();
+
+ assert(d != NULL);
+
+ ir_variable *const var = d->variable_referenced();
+
+ assert(var != NULL);
+
+ if (var->max_array_access >= unsigned(rhs->type->array_size())) {
+ /* FINISHME: This should actually log the location of the RHS. */
+ _mesa_glsl_error(& lhs_loc, state, "array size must be > %u due to "
+ "previous access",
+ var->max_array_access);
+ }
+
+ var->type = glsl_type::get_array_instance(lhs->type->element_type(),
+ rhs->type->array_size());
+ d->type = var->type;
+ }
+ }
+
+ /* Most callers of do_assignment (assign, add_assign, pre_inc/dec,
+ * but not post_inc) need the converted assigned value as an rvalue
+ * to handle things like:
+ *
+ * i = j += 1;
+ *
+ * So we always just store the computed value being assigned to a
+ * temporary and return a deref of that temporary. If the rvalue
+ * ends up not being used, the temp will get copy-propagated out.
+ */
+ ir_variable *var = new(ctx) ir_variable(rhs->type, "assignment_tmp",
+ ir_var_temporary);
+ ir_dereference_variable *deref_var = new(ctx) ir_dereference_variable(var);
+ instructions->push_tail(var);
+ instructions->push_tail(new(ctx) ir_assignment(deref_var,
+ rhs,
+ NULL));
+ deref_var = new(ctx) ir_dereference_variable(var);
+
+ if (!error_emitted)
+ instructions->push_tail(new(ctx) ir_assignment(lhs, deref_var, NULL));
+
+ return new(ctx) ir_dereference_variable(var);
+}
+
+static ir_rvalue *
+get_lvalue_copy(exec_list *instructions, ir_rvalue *lvalue)
+{
+ void *ctx = ralloc_parent(lvalue);
+ ir_variable *var;
+
+ var = new(ctx) ir_variable(lvalue->type, "_post_incdec_tmp",
+ ir_var_temporary);
+ instructions->push_tail(var);
+ var->mode = ir_var_auto;
+
+ instructions->push_tail(new(ctx) ir_assignment(new(ctx) ir_dereference_variable(var),
+ lvalue, NULL));
+
+ /* Once we've created this temporary, mark it read only so it's no
+ * longer considered an lvalue.
+ */
+ var->read_only = true;
+
+ return new(ctx) ir_dereference_variable(var);
+}
+
+
+ir_rvalue *
+ast_node::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ (void) instructions;
+ (void) state;
+
+ return NULL;
+}
+
+static void
+mark_whole_array_access(ir_rvalue *access)
+{
+ ir_dereference_variable *deref = access->as_dereference_variable();
+
+ if (deref) {
+ deref->var->max_array_access = deref->type->length - 1;
+ }
+}
+
+static ir_rvalue *
+do_comparison(void *mem_ctx, int operation, ir_rvalue *op0, ir_rvalue *op1)
+{
+ int join_op;
+ ir_rvalue *cmp = NULL;
+
+ if (operation == ir_binop_all_equal)
+ join_op = ir_binop_logic_and;
+ else
+ join_op = ir_binop_logic_or;
+
+ switch (op0->type->base_type) {
+ case GLSL_TYPE_FLOAT:
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT:
+ case GLSL_TYPE_BOOL:
+ return new(mem_ctx) ir_expression(operation, op0, op1);
+
+ case GLSL_TYPE_ARRAY: {
+ for (unsigned int i = 0; i < op0->type->length; i++) {
+ ir_rvalue *e0, *e1, *result;
+
+ e0 = new(mem_ctx) ir_dereference_array(op0->clone(mem_ctx, NULL),
+ new(mem_ctx) ir_constant(i));
+ e1 = new(mem_ctx) ir_dereference_array(op1->clone(mem_ctx, NULL),
+ new(mem_ctx) ir_constant(i));
+ result = do_comparison(mem_ctx, operation, e0, e1);
+
+ if (cmp) {
+ cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
+ } else {
+ cmp = result;
+ }
+ }
+
+ mark_whole_array_access(op0);
+ mark_whole_array_access(op1);
+ break;
+ }
+
+ case GLSL_TYPE_STRUCT: {
+ for (unsigned int i = 0; i < op0->type->length; i++) {
+ ir_rvalue *e0, *e1, *result;
+ const char *field_name = op0->type->fields.structure[i].name;
+
+ e0 = new(mem_ctx) ir_dereference_record(op0->clone(mem_ctx, NULL),
+ field_name);
+ e1 = new(mem_ctx) ir_dereference_record(op1->clone(mem_ctx, NULL),
+ field_name);
+ result = do_comparison(mem_ctx, operation, e0, e1);
+
+ if (cmp) {
+ cmp = new(mem_ctx) ir_expression(join_op, cmp, result);
+ } else {
+ cmp = result;
+ }
+ }
+ break;
+ }
+
+ case GLSL_TYPE_ERROR:
+ case GLSL_TYPE_VOID:
+ case GLSL_TYPE_SAMPLER:
+ /* I assume a comparison of a struct containing a sampler just
+ * ignores the sampler present in the type.
+ */
+ break;
+
+ default:
+ assert(!"Should not get here.");
+ break;
+ }
+
+ if (cmp == NULL)
+ cmp = new(mem_ctx) ir_constant(true);
+
+ return cmp;
+}
+
+ir_rvalue *
+ast_expression::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ static const int operations[AST_NUM_OPERATORS] = {
+ -1, /* ast_assign doesn't convert to ir_expression. */
+ -1, /* ast_plus doesn't convert to ir_expression. */
+ ir_unop_neg,
+ ir_binop_add,
+ ir_binop_sub,
+ ir_binop_mul,
+ ir_binop_div,
+ ir_binop_mod,
+ ir_binop_lshift,
+ ir_binop_rshift,
+ ir_binop_less,
+ ir_binop_greater,
+ ir_binop_lequal,
+ ir_binop_gequal,
+ ir_binop_all_equal,
+ ir_binop_any_nequal,
+ ir_binop_bit_and,
+ ir_binop_bit_xor,
+ ir_binop_bit_or,
+ ir_unop_bit_not,
+ ir_binop_logic_and,
+ ir_binop_logic_xor,
+ ir_binop_logic_or,
+ ir_unop_logic_not,
+
+ /* Note: The following block of expression types actually convert
+ * to multiple IR instructions.
+ */
+ ir_binop_mul, /* ast_mul_assign */
+ ir_binop_div, /* ast_div_assign */
+ ir_binop_mod, /* ast_mod_assign */
+ ir_binop_add, /* ast_add_assign */
+ ir_binop_sub, /* ast_sub_assign */
+ ir_binop_lshift, /* ast_ls_assign */
+ ir_binop_rshift, /* ast_rs_assign */
+ ir_binop_bit_and, /* ast_and_assign */
+ ir_binop_bit_xor, /* ast_xor_assign */
+ ir_binop_bit_or, /* ast_or_assign */
+
+ -1, /* ast_conditional doesn't convert to ir_expression. */
+ ir_binop_add, /* ast_pre_inc. */
+ ir_binop_sub, /* ast_pre_dec. */
+ ir_binop_add, /* ast_post_inc. */
+ ir_binop_sub, /* ast_post_dec. */
+ -1, /* ast_field_selection doesn't conv to ir_expression. */
+ -1, /* ast_array_index doesn't convert to ir_expression. */
+ -1, /* ast_function_call doesn't conv to ir_expression. */
+ -1, /* ast_identifier doesn't convert to ir_expression. */
+ -1, /* ast_int_constant doesn't convert to ir_expression. */
+ -1, /* ast_uint_constant doesn't conv to ir_expression. */
+ -1, /* ast_float_constant doesn't conv to ir_expression. */
+ -1, /* ast_bool_constant doesn't conv to ir_expression. */
+ -1, /* ast_sequence doesn't convert to ir_expression. */
+ };
+ ir_rvalue *result = NULL;
+ ir_rvalue *op[3];
+ const struct glsl_type *type = glsl_type::error_type;
+ bool error_emitted = false;
+ YYLTYPE loc;
+
+ loc = this->get_location();
+
+ switch (this->oper) {
+ case ast_assign: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ result = do_assignment(instructions, state, op[0], op[1],
+ this->subexpressions[0]->get_location());
+ error_emitted = result->type->is_error();
+ type = result->type;
+ break;
+ }
+
+ case ast_plus:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ type = unary_arithmetic_result_type(op[0]->type, state, & loc);
+
+ error_emitted = type->is_error();
+
+ result = op[0];
+ break;
+
+ case ast_neg:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ type = unary_arithmetic_result_type(op[0]->type, state, & loc);
+
+ error_emitted = type->is_error();
+
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], NULL);
+ break;
+
+ case ast_add:
+ case ast_sub:
+ case ast_mul:
+ case ast_div:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ type = arithmetic_result_type(op[0], op[1],
+ (this->oper == ast_mul),
+ state, & loc);
+ error_emitted = type->is_error();
+
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+ break;
+
+ case ast_mod:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
+
+ assert(operations[this->oper] == ir_binop_mod);
+
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+ error_emitted = type->is_error();
+ break;
+
+ case ast_lshift:
+ case ast_rshift:
+ if (state->language_version < 130) {
+ _mesa_glsl_error(&loc, state, "operator %s requires GLSL 1.30",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+ type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
+ &loc);
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+ break;
+
+ case ast_less:
+ case ast_greater:
+ case ast_lequal:
+ case ast_gequal:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ type = relational_result_type(op[0], op[1], state, & loc);
+
+ /* The relational operators must either generate an error or result
+ * in a scalar boolean. See page 57 of the GLSL 1.50 spec.
+ */
+ assert(type->is_error()
+ || ((type->base_type == GLSL_TYPE_BOOL)
+ && type->is_scalar()));
+
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+ error_emitted = type->is_error();
+ break;
+
+ case ast_nequal:
+ case ast_equal:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ /* From page 58 (page 64 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "The equality operators equal (==), and not equal (!=)
+ * operate on all types. They result in a scalar Boolean. If
+ * the operand types do not match, then there must be a
+ * conversion from Section 4.1.10 "Implicit Conversions"
+ * applied to one operand that can make them match, in which
+ * case this conversion is done."
+ */
+ if ((!apply_implicit_conversion(op[0]->type, op[1], state)
+ && !apply_implicit_conversion(op[1]->type, op[0], state))
+ || (op[0]->type != op[1]->type)) {
+ _mesa_glsl_error(& loc, state, "operands of `%s' must have the same "
+ "type", (this->oper == ast_equal) ? "==" : "!=");
+ error_emitted = true;
+ } else if ((state->language_version <= 110)
+ && (op[0]->type->is_array() || op[1]->type->is_array())) {
+ _mesa_glsl_error(& loc, state, "array comparisons forbidden in "
+ "GLSL 1.10");
+ error_emitted = true;
+ }
+
+ result = do_comparison(ctx, operations[this->oper], op[0], op[1]);
+ type = glsl_type::bool_type;
+
+ assert(error_emitted || (result->type == glsl_type::bool_type));
+ break;
+
+ case ast_bit_and:
+ case ast_bit_xor:
+ case ast_bit_or:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+ type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
+ state, &loc);
+ result = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+ break;
+
+ case ast_bit_not:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ if (state->language_version < 130) {
+ _mesa_glsl_error(&loc, state, "bit-wise operations require GLSL 1.30");
+ error_emitted = true;
+ }
+
+ if (!op[0]->type->is_integer()) {
+ _mesa_glsl_error(&loc, state, "operand of `~' must be an integer");
+ error_emitted = true;
+ }
+
+ type = op[0]->type;
+ result = new(ctx) ir_expression(ir_unop_bit_not, type, op[0], NULL);
+ break;
+
+ case ast_logic_and: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[0]->get_location();
+
+ _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+
+ ir_constant *op0_const = op[0]->constant_expression_value();
+ if (op0_const) {
+ if (op0_const->value.b[0]) {
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[1]->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "RHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+ result = op[1];
+ } else {
+ result = op0_const;
+ }
+ type = glsl_type::bool_type;
+ } else {
+ ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
+ "and_tmp",
+ ir_var_temporary);
+ instructions->push_tail(tmp);
+
+ ir_if *const stmt = new(ctx) ir_if(op[0]);
+ instructions->push_tail(stmt);
+
+ op[1] = this->subexpressions[1]->hir(&stmt->then_instructions, state);
+
+ if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[1]->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "RHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+
+ ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const then_assign =
+ new(ctx) ir_assignment(then_deref, op[1], NULL);
+ stmt->then_instructions.push_tail(then_assign);
+
+ ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const else_assign =
+ new(ctx) ir_assignment(else_deref, new(ctx) ir_constant(false), NULL);
+ stmt->else_instructions.push_tail(else_assign);
+
+ result = new(ctx) ir_dereference_variable(tmp);
+ type = tmp->type;
+ }
+ break;
+ }
+
+ case ast_logic_or: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[0]->get_location();
+
+ _mesa_glsl_error(& loc, state, "LHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+
+ ir_constant *op0_const = op[0]->constant_expression_value();
+ if (op0_const) {
+ if (op0_const->value.b[0]) {
+ result = op0_const;
+ } else {
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[1]->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "RHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+ result = op[1];
+ }
+ type = glsl_type::bool_type;
+ } else {
+ ir_variable *const tmp = new(ctx) ir_variable(glsl_type::bool_type,
+ "or_tmp",
+ ir_var_temporary);
+ instructions->push_tail(tmp);
+
+ ir_if *const stmt = new(ctx) ir_if(op[0]);
+ instructions->push_tail(stmt);
+
+ op[1] = this->subexpressions[1]->hir(&stmt->else_instructions, state);
+
+ if (!op[1]->type->is_boolean() || !op[1]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[1]->get_location();
+
+ _mesa_glsl_error(& loc, state, "RHS of `%s' must be scalar boolean",
+ operator_string(this->oper));
+ error_emitted = true;
+ }
+
+ ir_dereference *const then_deref = new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const then_assign =
+ new(ctx) ir_assignment(then_deref, new(ctx) ir_constant(true), NULL);
+ stmt->then_instructions.push_tail(then_assign);
+
+ ir_dereference *const else_deref = new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const else_assign =
+ new(ctx) ir_assignment(else_deref, op[1], NULL);
+ stmt->else_instructions.push_tail(else_assign);
+
+ result = new(ctx) ir_dereference_variable(tmp);
+ type = tmp->type;
+ }
+ break;
+ }
+
+ case ast_logic_xor:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+
+ result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
+ op[0], op[1]);
+ type = glsl_type::bool_type;
+ break;
+
+ case ast_logic_not:
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[0]->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "operand of `!' must be scalar boolean");
+ error_emitted = true;
+ }
+
+ result = new(ctx) ir_expression(operations[this->oper], glsl_type::bool_type,
+ op[0], NULL);
+ type = glsl_type::bool_type;
+ break;
+
+ case ast_mul_assign:
+ case ast_div_assign:
+ case ast_add_assign:
+ case ast_sub_assign: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ type = arithmetic_result_type(op[0], op[1],
+ (this->oper == ast_mul_assign),
+ state, & loc);
+
+ ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+
+ result = do_assignment(instructions, state,
+ op[0]->clone(ctx, NULL), temp_rhs,
+ this->subexpressions[0]->get_location());
+ type = result->type;
+ error_emitted = (op[0]->type->is_error());
+
+ /* GLSL 1.10 does not allow array assignment. However, we don't have to
+ * explicitly test for this because none of the binary expression
+ * operators allow array operands either.
+ */
+
+ break;
+ }
+
+ case ast_mod_assign: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+
+ type = modulus_result_type(op[0]->type, op[1]->type, state, & loc);
+
+ assert(operations[this->oper] == ir_binop_mod);
+
+ ir_rvalue *temp_rhs;
+ temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+
+ result = do_assignment(instructions, state,
+ op[0]->clone(ctx, NULL), temp_rhs,
+ this->subexpressions[0]->get_location());
+ type = result->type;
+ error_emitted = type->is_error();
+ break;
+ }
+
+ case ast_ls_assign:
+ case ast_rs_assign: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+ type = shift_result_type(op[0]->type, op[1]->type, this->oper, state,
+ &loc);
+ ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
+ type, op[0], op[1]);
+ result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
+ temp_rhs,
+ this->subexpressions[0]->get_location());
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+ break;
+ }
+
+ case ast_and_assign:
+ case ast_xor_assign:
+ case ast_or_assign: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ op[1] = this->subexpressions[1]->hir(instructions, state);
+ type = bit_logic_result_type(op[0]->type, op[1]->type, this->oper,
+ state, &loc);
+ ir_rvalue *temp_rhs = new(ctx) ir_expression(operations[this->oper],
+ type, op[0], op[1]);
+ result = do_assignment(instructions, state, op[0]->clone(ctx, NULL),
+ temp_rhs,
+ this->subexpressions[0]->get_location());
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+ break;
+ }
+
+ case ast_conditional: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+
+ /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "The ternary selection operator (?:). It operates on three
+ * expressions (exp1 ? exp2 : exp3). This operator evaluates the
+ * first expression, which must result in a scalar Boolean."
+ */
+ if (!op[0]->type->is_boolean() || !op[0]->type->is_scalar()) {
+ YYLTYPE loc = this->subexpressions[0]->get_location();
+
+ _mesa_glsl_error(& loc, state, "?: condition must be scalar boolean");
+ error_emitted = true;
+ }
+
+ /* The :? operator is implemented by generating an anonymous temporary
+ * followed by an if-statement. The last instruction in each branch of
+ * the if-statement assigns a value to the anonymous temporary. This
+ * temporary is the r-value of the expression.
+ */
+ exec_list then_instructions;
+ exec_list else_instructions;
+
+ op[1] = this->subexpressions[1]->hir(&then_instructions, state);
+ op[2] = this->subexpressions[2]->hir(&else_instructions, state);
+
+ /* From page 59 (page 65 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "The second and third expressions can be any type, as
+ * long their types match, or there is a conversion in
+ * Section 4.1.10 "Implicit Conversions" that can be applied
+ * to one of the expressions to make their types match. This
+ * resulting matching type is the type of the entire
+ * expression."
+ */
+ if ((!apply_implicit_conversion(op[1]->type, op[2], state)
+ && !apply_implicit_conversion(op[2]->type, op[1], state))
+ || (op[1]->type != op[2]->type)) {
+ YYLTYPE loc = this->subexpressions[1]->get_location();
+
+ _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
+ "operator must have matching types.");
+ error_emitted = true;
+ type = glsl_type::error_type;
+ } else {
+ type = op[1]->type;
+ }
+
+ /* From page 33 (page 39 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "The second and third expressions must be the same type, but can
+ * be of any type other than an array."
+ */
+ if ((state->language_version <= 110) && type->is_array()) {
+ _mesa_glsl_error(& loc, state, "Second and third operands of ?: "
+ "operator must not be arrays.");
+ error_emitted = true;
+ }
+
+ ir_constant *cond_val = op[0]->constant_expression_value();
+ ir_constant *then_val = op[1]->constant_expression_value();
+ ir_constant *else_val = op[2]->constant_expression_value();
+
+ if (then_instructions.is_empty()
+ && else_instructions.is_empty()
+ && (cond_val != NULL) && (then_val != NULL) && (else_val != NULL)) {
+ result = (cond_val->value.b[0]) ? then_val : else_val;
+ } else {
+ ir_variable *const tmp =
+ new(ctx) ir_variable(type, "conditional_tmp", ir_var_temporary);
+ instructions->push_tail(tmp);
+
+ ir_if *const stmt = new(ctx) ir_if(op[0]);
+ instructions->push_tail(stmt);
+
+ then_instructions.move_nodes_to(& stmt->then_instructions);
+ ir_dereference *const then_deref =
+ new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const then_assign =
+ new(ctx) ir_assignment(then_deref, op[1], NULL);
+ stmt->then_instructions.push_tail(then_assign);
+
+ else_instructions.move_nodes_to(& stmt->else_instructions);
+ ir_dereference *const else_deref =
+ new(ctx) ir_dereference_variable(tmp);
+ ir_assignment *const else_assign =
+ new(ctx) ir_assignment(else_deref, op[2], NULL);
+ stmt->else_instructions.push_tail(else_assign);
+
+ result = new(ctx) ir_dereference_variable(tmp);
+ }
+ break;
+ }
+
+ case ast_pre_inc:
+ case ast_pre_dec: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
+ op[1] = new(ctx) ir_constant(1.0f);
+ else
+ op[1] = new(ctx) ir_constant(1);
+
+ type = arithmetic_result_type(op[0], op[1], false, state, & loc);
+
+ ir_rvalue *temp_rhs;
+ temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+
+ result = do_assignment(instructions, state,
+ op[0]->clone(ctx, NULL), temp_rhs,
+ this->subexpressions[0]->get_location());
+ type = result->type;
+ error_emitted = op[0]->type->is_error();
+ break;
+ }
+
+ case ast_post_inc:
+ case ast_post_dec: {
+ op[0] = this->subexpressions[0]->hir(instructions, state);
+ if (op[0]->type->base_type == GLSL_TYPE_FLOAT)
+ op[1] = new(ctx) ir_constant(1.0f);
+ else
+ op[1] = new(ctx) ir_constant(1);
+
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+
+ type = arithmetic_result_type(op[0], op[1], false, state, & loc);
+
+ ir_rvalue *temp_rhs;
+ temp_rhs = new(ctx) ir_expression(operations[this->oper], type,
+ op[0], op[1]);
+
+ /* Get a temporary of a copy of the lvalue before it's modified.
+ * This may get thrown away later.
+ */
+ result = get_lvalue_copy(instructions, op[0]->clone(ctx, NULL));
+
+ (void)do_assignment(instructions, state,
+ op[0]->clone(ctx, NULL), temp_rhs,
+ this->subexpressions[0]->get_location());
+
+ type = result->type;
+ error_emitted = op[0]->type->is_error();
+ break;
+ }
+
+ case ast_field_selection:
+ result = _mesa_ast_field_selection_to_hir(this, instructions, state);
+ type = result->type;
+ break;
+
+ case ast_array_index: {
+ YYLTYPE index_loc = subexpressions[1]->get_location();
+
+ op[0] = subexpressions[0]->hir(instructions, state);
+ op[1] = subexpressions[1]->hir(instructions, state);
+
+ error_emitted = op[0]->type->is_error() || op[1]->type->is_error();
+
+ ir_rvalue *const array = op[0];
+
+ result = new(ctx) ir_dereference_array(op[0], op[1]);
+
+ /* Do not use op[0] after this point. Use array.
+ */
+ op[0] = NULL;
+
+
+ if (error_emitted)
+ break;
+
+ if (!array->type->is_array()
+ && !array->type->is_matrix()
+ && !array->type->is_vector()) {
+ _mesa_glsl_error(& index_loc, state,
+ "cannot dereference non-array / non-matrix / "
+ "non-vector");
+ error_emitted = true;
+ }
+
+ if (!op[1]->type->is_integer()) {
+ _mesa_glsl_error(& index_loc, state,
+ "array index must be integer type");
+ error_emitted = true;
+ } else if (!op[1]->type->is_scalar()) {
+ _mesa_glsl_error(& index_loc, state,
+ "array index must be scalar");
+ error_emitted = true;
+ }
+
+ /* If the array index is a constant expression and the array has a
+ * declared size, ensure that the access is in-bounds. If the array
+ * index is not a constant expression, ensure that the array has a
+ * declared size.
+ */
+ ir_constant *const const_index = op[1]->constant_expression_value();
+ if (const_index != NULL) {
+ const int idx = const_index->value.i[0];
+ const char *type_name;
+ unsigned bound = 0;
+
+ if (array->type->is_matrix()) {
+ type_name = "matrix";
+ } else if (array->type->is_vector()) {
+ type_name = "vector";
+ } else {
+ type_name = "array";
+ }
+
+ /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "It is illegal to declare an array with a size, and then
+ * later (in the same shader) index the same array with an
+ * integral constant expression greater than or equal to the
+ * declared size. It is also illegal to index an array with a
+ * negative constant expression."
+ */
+ if (array->type->is_matrix()) {
+ if (array->type->row_type()->vector_elements <= idx) {
+ bound = array->type->row_type()->vector_elements;
+ }
+ } else if (array->type->is_vector()) {
+ if (array->type->vector_elements <= idx) {
+ bound = array->type->vector_elements;
+ }
+ } else {
+ if ((array->type->array_size() > 0)
+ && (array->type->array_size() <= idx)) {
+ bound = array->type->array_size();
+ }
+ }
+
+ if (bound > 0) {
+ _mesa_glsl_error(& loc, state, "%s index must be < %u",
+ type_name, bound);
+ error_emitted = true;
+ } else if (idx < 0) {
+ _mesa_glsl_error(& loc, state, "%s index must be >= 0",
+ type_name);
+ error_emitted = true;
+ }
+
+ if (array->type->is_array()) {
+ /* If the array is a variable dereference, it dereferences the
+ * whole array, by definition. Use this to get the variable.
+ *
+ * FINISHME: Should some methods for getting / setting / testing
+ * FINISHME: array access limits be added to ir_dereference?
+ */
+ ir_variable *const v = array->whole_variable_referenced();
+ if ((v != NULL) && (unsigned(idx) > v->max_array_access))
+ v->max_array_access = idx;
+ }
+ } else if (array->type->array_size() == 0) {
+ _mesa_glsl_error(&loc, state, "unsized array index must be constant");
+ } else {
+ if (array->type->is_array()) {
+ /* whole_variable_referenced can return NULL if the array is a
+ * member of a structure. In this case it is safe to not update
+ * the max_array_access field because it is never used for fields
+ * of structures.
+ */
+ ir_variable *v = array->whole_variable_referenced();
+ if (v != NULL)
+ v->max_array_access = array->type->array_size();
+ }
+ }
+
+ /* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
+ *
+ * "Samplers aggregated into arrays within a shader (using square
+ * brackets [ ]) can only be indexed with integral constant
+ * expressions [...]."
+ *
+ * This restriction was added in GLSL 1.30. Shaders using earlier version
+ * of the language should not be rejected by the compiler front-end for
+ * using this construct. This allows useful things such as using a loop
+ * counter as the index to an array of samplers. If the loop in unrolled,
+ * the code should compile correctly. Instead, emit a warning.
+ */
+ if (array->type->is_array() &&
+ array->type->element_type()->is_sampler() &&
+ const_index == NULL) {
+
+ if (state->language_version == 100) {
+ _mesa_glsl_warning(&loc, state,
+ "sampler arrays indexed with non-constant "
+ "expressions is optional in GLSL ES 1.00");
+ } else if (state->language_version < 130) {
+ _mesa_glsl_warning(&loc, state,
+ "sampler arrays indexed with non-constant "
+ "expressions is forbidden in GLSL 1.30 and "
+ "later");
+ } else {
+ _mesa_glsl_error(&loc, state,
+ "sampler arrays indexed with non-constant "
+ "expressions is forbidden in GLSL 1.30 and "
+ "later");
+ error_emitted = true;
+ }
+ }
+
+ if (error_emitted)
+ result->type = glsl_type::error_type;
+
+ type = result->type;
+ break;
+ }
+
+ case ast_function_call:
+ /* Should *NEVER* get here. ast_function_call should always be handled
+ * by ast_function_expression::hir.
+ */
+ assert(0);
+ break;
+
+ case ast_identifier: {
+ /* ast_identifier can appear several places in a full abstract syntax
+ * tree. This particular use must be at location specified in the grammar
+ * as 'variable_identifier'.
+ */
+ ir_variable *var =
+ state->symbols->get_variable(this->primary_expression.identifier);
+
+ result = new(ctx) ir_dereference_variable(var);
+
+ if (var != NULL) {
+ var->used = true;
+ type = result->type;
+ } else {
+ _mesa_glsl_error(& loc, state, "`%s' undeclared",
+ this->primary_expression.identifier);
+
+ error_emitted = true;
+ }
+ break;
+ }
+
+ case ast_int_constant:
+ type = glsl_type::int_type;
+ result = new(ctx) ir_constant(this->primary_expression.int_constant);
+ break;
+
+ case ast_uint_constant:
+ type = glsl_type::uint_type;
+ result = new(ctx) ir_constant(this->primary_expression.uint_constant);
+ break;
+
+ case ast_float_constant:
+ type = glsl_type::float_type;
+ result = new(ctx) ir_constant(this->primary_expression.float_constant);
+ break;
+
+ case ast_bool_constant:
+ type = glsl_type::bool_type;
+ result = new(ctx) ir_constant(bool(this->primary_expression.bool_constant));
+ break;
+
+ case ast_sequence: {
+ /* It should not be possible to generate a sequence in the AST without
+ * any expressions in it.
+ */
+ assert(!this->expressions.is_empty());
+
+ /* The r-value of a sequence is the last expression in the sequence. If
+ * the other expressions in the sequence do not have side-effects (and
+ * therefore add instructions to the instruction list), they get dropped
+ * on the floor.
+ */
+ foreach_list_typed (ast_node, ast, link, &this->expressions)
+ result = ast->hir(instructions, state);
+
+ type = result->type;
+
+ /* Any errors should have already been emitted in the loop above.
+ */
+ error_emitted = true;
+ break;
+ }
+ }
+
+ if (type->is_error() && !error_emitted)
+ _mesa_glsl_error(& loc, state, "type mismatch");
+
+ return result;
+}
+
+
+ir_rvalue *
+ast_expression_statement::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ /* It is possible to have expression statements that don't have an
+ * expression. This is the solitary semicolon:
+ *
+ * for (i = 0; i < 5; i++)
+ * ;
+ *
+ * In this case the expression will be NULL. Test for NULL and don't do
+ * anything in that case.
+ */
+ if (expression != NULL)
+ expression->hir(instructions, state);
+
+ /* Statements do not have r-values.
+ */
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_compound_statement::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ if (new_scope)
+ state->symbols->push_scope();
+
+ foreach_list_typed (ast_node, ast, link, &this->statements)
+ ast->hir(instructions, state);
+
+ if (new_scope)
+ state->symbols->pop_scope();
+
+ /* Compound statements do not have r-values.
+ */
+ return NULL;
+}
+
+
+static const glsl_type *
+process_array_type(YYLTYPE *loc, const glsl_type *base, ast_node *array_size,
+ struct _mesa_glsl_parse_state *state)
+{
+ unsigned length = 0;
+
+ /* FINISHME: Reject delcarations of multidimensional arrays. */
+
+ if (array_size != NULL) {
+ exec_list dummy_instructions;
+ ir_rvalue *const ir = array_size->hir(& dummy_instructions, state);
+ YYLTYPE loc = array_size->get_location();
+
+ /* FINISHME: Verify that the grammar forbids side-effects in array
+ * FINISHME: sizes. i.e., 'vec4 [x = 12] data'
+ */
+ assert(dummy_instructions.is_empty());
+
+ if (ir != NULL) {
+ if (!ir->type->is_integer()) {
+ _mesa_glsl_error(& loc, state, "array size must be integer type");
+ } else if (!ir->type->is_scalar()) {
+ _mesa_glsl_error(& loc, state, "array size must be scalar type");
+ } else {
+ ir_constant *const size = ir->constant_expression_value();
+
+ if (size == NULL) {
+ _mesa_glsl_error(& loc, state, "array size must be a "
+ "constant valued expression");
+ } else if (size->value.i[0] <= 0) {
+ _mesa_glsl_error(& loc, state, "array size must be > 0");
+ } else {
+ assert(size->type == ir->type);
+ length = size->value.u[0];
+ }
+ }
+ }
+ } else if (state->es_shader) {
+ /* Section 10.17 of the GLSL ES 1.00 specification states that unsized
+ * array declarations have been removed from the language.
+ */
+ _mesa_glsl_error(loc, state, "unsized array declarations are not "
+ "allowed in GLSL ES 1.00.");
+ }
+
+ return glsl_type::get_array_instance(base, length);
+}
+
+
+const glsl_type *
+ast_type_specifier::glsl_type(const char **name,
+ struct _mesa_glsl_parse_state *state) const
+{
+ const struct glsl_type *type;
+
+ type = state->symbols->get_type(this->type_name);
+ *name = this->type_name;
+
+ if (this->is_array) {
+ YYLTYPE loc = this->get_location();
+ type = process_array_type(&loc, type, this->array_size, state);
+ }
+
+ return type;
+}
+
+
+static void
+apply_type_qualifier_to_variable(const struct ast_type_qualifier *qual,
+ ir_variable *var,
+ struct _mesa_glsl_parse_state *state,
+ YYLTYPE *loc)
+{
+ if (qual->flags.q.invariant) {
+ if (var->used) {
+ _mesa_glsl_error(loc, state,
+ "variable `%s' may not be redeclared "
+ "`invariant' after being used",
+ var->name);
+ } else {
+ var->invariant = 1;
+ }
+ }
+
+ if (qual->flags.q.constant || qual->flags.q.attribute
+ || qual->flags.q.uniform
+ || (qual->flags.q.varying && (state->target == fragment_shader)))
+ var->read_only = 1;
+
+ if (qual->flags.q.centroid)
+ var->centroid = 1;
+
+ if (qual->flags.q.attribute && state->target != vertex_shader) {
+ var->type = glsl_type::error_type;
+ _mesa_glsl_error(loc, state,
+ "`attribute' variables may not be declared in the "
+ "%s shader",
+ _mesa_glsl_shader_target_name(state->target));
+ }
+
+ /* From page 25 (page 31 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "The varying qualifier can be used only with the data types
+ * float, vec2, vec3, vec4, mat2, mat3, and mat4, or arrays of
+ * these."
+ */
+ if (qual->flags.q.varying) {
+ const glsl_type *non_array_type;
+
+ if (var->type && var->type->is_array())
+ non_array_type = var->type->fields.array;
+ else
+ non_array_type = var->type;
+
+ if (non_array_type && non_array_type->base_type != GLSL_TYPE_FLOAT) {
+ var->type = glsl_type::error_type;
+ _mesa_glsl_error(loc, state,
+ "varying variables must be of base type float");
+ }
+ }
+
+ /* If there is no qualifier that changes the mode of the variable, leave
+ * the setting alone.
+ */
+ if (qual->flags.q.in && qual->flags.q.out)
+ var->mode = ir_var_inout;
+ else if (qual->flags.q.attribute || qual->flags.q.in
+ || (qual->flags.q.varying && (state->target == fragment_shader)))
+ var->mode = ir_var_in;
+ else if (qual->flags.q.out
+ || (qual->flags.q.varying && (state->target == vertex_shader)))
+ var->mode = ir_var_out;
+ else if (qual->flags.q.uniform)
+ var->mode = ir_var_uniform;
+
+ if (state->all_invariant && (state->current_function == NULL)) {
+ switch (state->target) {
+ case vertex_shader:
+ if (var->mode == ir_var_out)
+ var->invariant = true;
+ break;
+ case geometry_shader:
+ if ((var->mode == ir_var_in) || (var->mode == ir_var_out))
+ var->invariant = true;
+ break;
+ case fragment_shader:
+ if (var->mode == ir_var_in)
+ var->invariant = true;
+ break;
+ }
+ }
+
+ if (qual->flags.q.flat)
+ var->interpolation = ir_var_flat;
+ else if (qual->flags.q.noperspective)
+ var->interpolation = ir_var_noperspective;
+ else
+ var->interpolation = ir_var_smooth;
+
+ var->pixel_center_integer = qual->flags.q.pixel_center_integer;
+ var->origin_upper_left = qual->flags.q.origin_upper_left;
+ if ((qual->flags.q.origin_upper_left || qual->flags.q.pixel_center_integer)
+ && (strcmp(var->name, "gl_FragCoord") != 0)) {
+ const char *const qual_string = (qual->flags.q.origin_upper_left)
+ ? "origin_upper_left" : "pixel_center_integer";
+
+ _mesa_glsl_error(loc, state,
+ "layout qualifier `%s' can only be applied to "
+ "fragment shader input `gl_FragCoord'",
+ qual_string);
+ }
+
+ if (qual->flags.q.explicit_location) {
+ const bool global_scope = (state->current_function == NULL);
+ bool fail = false;
+ const char *string = "";
+
+ /* In the vertex shader only shader inputs can be given explicit
+ * locations.
+ *
+ * In the fragment shader only shader outputs can be given explicit
+ * locations.
+ */
+ switch (state->target) {
+ case vertex_shader:
+ if (!global_scope || (var->mode != ir_var_in)) {
+ fail = true;
+ string = "input";
+ }
+ break;
+
+ case geometry_shader:
+ _mesa_glsl_error(loc, state,
+ "geometry shader variables cannot be given "
+ "explicit locations\n");
+ break;
+
+ case fragment_shader:
+ if (!global_scope || (var->mode != ir_var_in)) {
+ fail = true;
+ string = "output";
+ }
+ break;
+ };
+
+ if (fail) {
+ _mesa_glsl_error(loc, state,
+ "only %s shader %s variables can be given an "
+ "explicit location\n",
+ _mesa_glsl_shader_target_name(state->target),
+ string);
+ } else {
+ var->explicit_location = true;
+
+ /* This bit of silliness is needed because invalid explicit locations
+ * are supposed to be flagged during linking. Small negative values
+ * biased by VERT_ATTRIB_GENERIC0 or FRAG_RESULT_DATA0 could alias
+ * built-in values (e.g., -16+VERT_ATTRIB_GENERIC0 = VERT_ATTRIB_POS).
+ * The linker needs to be able to differentiate these cases. This
+ * ensures that negative values stay negative.
+ */
+ if (qual->location >= 0) {
+ var->location = (state->target == vertex_shader)
+ ? (qual->location + VERT_ATTRIB_GENERIC0)
+ : (qual->location + FRAG_RESULT_DATA0);
+ } else {
+ var->location = qual->location;
+ }
+ }
+ }
+
+ /* Does the declaration use the 'layout' keyword?
+ */
+ const bool uses_layout = qual->flags.q.pixel_center_integer
+ || qual->flags.q.origin_upper_left
+ || qual->flags.q.explicit_location;
+
+ /* Does the declaration use the deprecated 'attribute' or 'varying'
+ * keywords?
+ */
+ const bool uses_deprecated_qualifier = qual->flags.q.attribute
+ || qual->flags.q.varying;
+
+ /* Is the 'layout' keyword used with parameters that allow relaxed checking.
+ * Many implementations of GL_ARB_fragment_coord_conventions_enable and some
+ * implementations (only Mesa?) GL_ARB_explicit_attrib_location_enable
+ * allowed the layout qualifier to be used with 'varying' and 'attribute'.
+ * These extensions and all following extensions that add the 'layout'
+ * keyword have been modified to require the use of 'in' or 'out'.
+ *
+ * The following extension do not allow the deprecated keywords:
+ *
+ * GL_AMD_conservative_depth
+ * GL_ARB_gpu_shader5
+ * GL_ARB_separate_shader_objects
+ * GL_ARB_tesselation_shader
+ * GL_ARB_transform_feedback3
+ * GL_ARB_uniform_buffer_object
+ *
+ * It is unknown whether GL_EXT_shader_image_load_store or GL_NV_gpu_shader5
+ * allow layout with the deprecated keywords.
+ */
+ const bool relaxed_layout_qualifier_checking =
+ state->ARB_fragment_coord_conventions_enable;
+
+ if (uses_layout && uses_deprecated_qualifier) {
+ if (relaxed_layout_qualifier_checking) {
+ _mesa_glsl_warning(loc, state,
+ "`layout' qualifier may not be used with "
+ "`attribute' or `varying'");
+ } else {
+ _mesa_glsl_error(loc, state,
+ "`layout' qualifier may not be used with "
+ "`attribute' or `varying'");
+ }
+ }
+
+ /* Layout qualifiers for gl_FragDepth, which are enabled by extension
+ * AMD_conservative_depth.
+ */
+ int depth_layout_count = qual->flags.q.depth_any
+ + qual->flags.q.depth_greater
+ + qual->flags.q.depth_less
+ + qual->flags.q.depth_unchanged;
+ if (depth_layout_count > 0
+ && !state->AMD_conservative_depth_enable) {
+ _mesa_glsl_error(loc, state,
+ "extension GL_AMD_conservative_depth must be enabled "
+ "to use depth layout qualifiers");
+ } else if (depth_layout_count > 0
+ && strcmp(var->name, "gl_FragDepth") != 0) {
+ _mesa_glsl_error(loc, state,
+ "depth layout qualifiers can be applied only to "
+ "gl_FragDepth");
+ } else if (depth_layout_count > 1
+ && strcmp(var->name, "gl_FragDepth") == 0) {
+ _mesa_glsl_error(loc, state,
+ "at most one depth layout qualifier can be applied to "
+ "gl_FragDepth");
+ }
+ if (qual->flags.q.depth_any)
+ var->depth_layout = ir_depth_layout_any;
+ else if (qual->flags.q.depth_greater)
+ var->depth_layout = ir_depth_layout_greater;
+ else if (qual->flags.q.depth_less)
+ var->depth_layout = ir_depth_layout_less;
+ else if (qual->flags.q.depth_unchanged)
+ var->depth_layout = ir_depth_layout_unchanged;
+ else
+ var->depth_layout = ir_depth_layout_none;
+
+ if (var->type->is_array() && state->language_version != 110) {
+ var->array_lvalue = true;
+ }
+}
+
+
+ir_rvalue *
+ast_declarator_list::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ const struct glsl_type *decl_type;
+ const char *type_name = NULL;
+ ir_rvalue *result = NULL;
+ YYLTYPE loc = this->get_location();
+
+ /* From page 46 (page 52 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "To ensure that a particular output variable is invariant, it is
+ * necessary to use the invariant qualifier. It can either be used to
+ * qualify a previously declared variable as being invariant
+ *
+ * invariant gl_Position; // make existing gl_Position be invariant"
+ *
+ * In these cases the parser will set the 'invariant' flag in the declarator
+ * list, and the type will be NULL.
+ */
+ if (this->invariant) {
+ assert(this->type == NULL);
+
+ if (state->current_function != NULL) {
+ _mesa_glsl_error(& loc, state,
+ "All uses of `invariant' keyword must be at global "
+ "scope\n");
+ }
+
+ foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
+ assert(!decl->is_array);
+ assert(decl->array_size == NULL);
+ assert(decl->initializer == NULL);
+
+ ir_variable *const earlier =
+ state->symbols->get_variable(decl->identifier);
+ if (earlier == NULL) {
+ _mesa_glsl_error(& loc, state,
+ "Undeclared variable `%s' cannot be marked "
+ "invariant\n", decl->identifier);
+ } else if ((state->target == vertex_shader)
+ && (earlier->mode != ir_var_out)) {
+ _mesa_glsl_error(& loc, state,
+ "`%s' cannot be marked invariant, vertex shader "
+ "outputs only\n", decl->identifier);
+ } else if ((state->target == fragment_shader)
+ && (earlier->mode != ir_var_in)) {
+ _mesa_glsl_error(& loc, state,
+ "`%s' cannot be marked invariant, fragment shader "
+ "inputs only\n", decl->identifier);
+ } else if (earlier->used) {
+ _mesa_glsl_error(& loc, state,
+ "variable `%s' may not be redeclared "
+ "`invariant' after being used",
+ earlier->name);
+ } else {
+ earlier->invariant = true;
+ }
+ }
+
+ /* Invariant redeclarations do not have r-values.
+ */
+ return NULL;
+ }
+
+ assert(this->type != NULL);
+ assert(!this->invariant);
+
+ /* The type specifier may contain a structure definition. Process that
+ * before any of the variable declarations.
+ */
+ (void) this->type->specifier->hir(instructions, state);
+
+ decl_type = this->type->specifier->glsl_type(& type_name, state);
+ if (this->declarations.is_empty()) {
+ /* The only valid case where the declaration list can be empty is when
+ * the declaration is setting the default precision of a built-in type
+ * (e.g., 'precision highp vec4;').
+ */
+
+ if (decl_type != NULL) {
+ } else {
+ _mesa_glsl_error(& loc, state, "incomplete declaration");
+ }
+ }
+
+ foreach_list_typed (ast_declaration, decl, link, &this->declarations) {
+ const struct glsl_type *var_type;
+ ir_variable *var;
+
+ /* FINISHME: Emit a warning if a variable declaration shadows a
+ * FINISHME: declaration at a higher scope.
+ */
+
+ if ((decl_type == NULL) || decl_type->is_void()) {
+ if (type_name != NULL) {
+ _mesa_glsl_error(& loc, state,
+ "invalid type `%s' in declaration of `%s'",
+ type_name, decl->identifier);
+ } else {
+ _mesa_glsl_error(& loc, state,
+ "invalid type in declaration of `%s'",
+ decl->identifier);
+ }
+ continue;
+ }
+
+ if (decl->is_array) {
+ var_type = process_array_type(&loc, decl_type, decl->array_size,
+ state);
+ } else {
+ var_type = decl_type;
+ }
+
+ var = new(ctx) ir_variable(var_type, decl->identifier, ir_var_auto);
+
+ /* From page 22 (page 28 of the PDF) of the GLSL 1.10 specification;
+ *
+ * "Global variables can only use the qualifiers const,
+ * attribute, uni form, or varying. Only one may be
+ * specified.
+ *
+ * Local variables can only use the qualifier const."
+ *
+ * This is relaxed in GLSL 1.30. It is also relaxed by any extension
+ * that adds the 'layout' keyword.
+ */
+ if ((state->language_version < 130)
+ && !state->ARB_explicit_attrib_location_enable
+ && !state->ARB_fragment_coord_conventions_enable) {
+ if (this->type->qualifier.flags.q.out) {
+ _mesa_glsl_error(& loc, state,
+ "`out' qualifier in declaration of `%s' "
+ "only valid for function parameters in %s.",
+ decl->identifier, state->version_string);
+ }
+ if (this->type->qualifier.flags.q.in) {
+ _mesa_glsl_error(& loc, state,
+ "`in' qualifier in declaration of `%s' "
+ "only valid for function parameters in %s.",
+ decl->identifier, state->version_string);
+ }
+ /* FINISHME: Test for other invalid qualifiers. */
+ }
+
+ apply_type_qualifier_to_variable(& this->type->qualifier, var, state,
+ & loc);
+
+ if (this->type->qualifier.flags.q.invariant) {
+ if ((state->target == vertex_shader) && !(var->mode == ir_var_out ||
+ var->mode == ir_var_inout)) {
+ /* FINISHME: Note that this doesn't work for invariant on
+ * a function signature outval
+ */
+ _mesa_glsl_error(& loc, state,
+ "`%s' cannot be marked invariant, vertex shader "
+ "outputs only\n", var->name);
+ } else if ((state->target == fragment_shader) &&
+ !(var->mode == ir_var_in || var->mode == ir_var_inout)) {
+ /* FINISHME: Note that this doesn't work for invariant on
+ * a function signature inval
+ */
+ _mesa_glsl_error(& loc, state,
+ "`%s' cannot be marked invariant, fragment shader "
+ "inputs only\n", var->name);
+ }
+ }
+
+ if (state->current_function != NULL) {
+ const char *mode = NULL;
+ const char *extra = "";
+
+ /* There is no need to check for 'inout' here because the parser will
+ * only allow that in function parameter lists.
+ */
+ if (this->type->qualifier.flags.q.attribute) {
+ mode = "attribute";
+ } else if (this->type->qualifier.flags.q.uniform) {
+ mode = "uniform";
+ } else if (this->type->qualifier.flags.q.varying) {
+ mode = "varying";
+ } else if (this->type->qualifier.flags.q.in) {
+ mode = "in";
+ extra = " or in function parameter list";
+ } else if (this->type->qualifier.flags.q.out) {
+ mode = "out";
+ extra = " or in function parameter list";
+ }
+
+ if (mode) {
+ _mesa_glsl_error(& loc, state,
+ "%s variable `%s' must be declared at "
+ "global scope%s",
+ mode, var->name, extra);
+ }
+ } else if (var->mode == ir_var_in) {
+ var->read_only = true;
+
+ if (state->target == vertex_shader) {
+ bool error_emitted = false;
+
+ /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "Vertex shader inputs can only be float, floating-point
+ * vectors, matrices, signed and unsigned integers and integer
+ * vectors. Vertex shader inputs can also form arrays of these
+ * types, but not structures."
+ *
+ * From page 31 (page 27 of the PDF) of the GLSL 1.30 spec:
+ *
+ * "Vertex shader inputs can only be float, floating-point
+ * vectors, matrices, signed and unsigned integers and integer
+ * vectors. They cannot be arrays or structures."
+ *
+ * From page 23 (page 29 of the PDF) of the GLSL 1.20 spec:
+ *
+ * "The attribute qualifier can be used only with float,
+ * floating-point vectors, and matrices. Attribute variables
+ * cannot be declared as arrays or structures."
+ */
+ const glsl_type *check_type = var->type->is_array()
+ ? var->type->fields.array : var->type;
+
+ switch (check_type->base_type) {
+ case GLSL_TYPE_FLOAT:
+ break;
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT:
+ if (state->language_version > 120)
+ break;
+ /* FALLTHROUGH */
+ default:
+ _mesa_glsl_error(& loc, state,
+ "vertex shader input / attribute cannot have "
+ "type %s`%s'",
+ var->type->is_array() ? "array of " : "",
+ check_type->name);
+ error_emitted = true;
+ }
+
+ if (!error_emitted && (state->language_version <= 130)
+ && var->type->is_array()) {
+ _mesa_glsl_error(& loc, state,
+ "vertex shader input / attribute cannot have "
+ "array type");
+ error_emitted = true;
+ }
+ }
+ }
+
+ /* Integer vertex outputs must be qualified with 'flat'.
+ *
+ * From section 4.3.6 of the GLSL 1.30 spec:
+ * "If a vertex output is a signed or unsigned integer or integer
+ * vector, then it must be qualified with the interpolation qualifier
+ * flat."
+ */
+ if (state->language_version >= 130
+ && state->target == vertex_shader
+ && state->current_function == NULL
+ && var->type->is_integer()
+ && var->mode == ir_var_out
+ && var->interpolation != ir_var_flat) {
+
+ _mesa_glsl_error(&loc, state, "If a vertex output is an integer, "
+ "then it must be qualified with 'flat'");
+ }
+
+
+ /* Interpolation qualifiers cannot be applied to 'centroid' and
+ * 'centroid varying'.
+ *
+ * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
+ * "interpolation qualifiers may only precede the qualifiers in,
+ * centroid in, out, or centroid out in a declaration. They do not apply
+ * to the deprecated storage qualifiers varying or centroid varying."
+ */
+ if (state->language_version >= 130
+ && this->type->qualifier.has_interpolation()
+ && this->type->qualifier.flags.q.varying) {
+
+ const char *i = this->type->qualifier.interpolation_string();
+ assert(i != NULL);
+ const char *s;
+ if (this->type->qualifier.flags.q.centroid)
+ s = "centroid varying";
+ else
+ s = "varying";
+
+ _mesa_glsl_error(&loc, state,
+ "qualifier '%s' cannot be applied to the "
+ "deprecated storage qualifier '%s'", i, s);
+ }
+
+
+ /* Interpolation qualifiers can only apply to vertex shader outputs and
+ * fragment shader inputs.
+ *
+ * From page 29 (page 35 of the PDF) of the GLSL 1.30 spec:
+ * "Outputs from a vertex shader (out) and inputs to a fragment
+ * shader (in) can be further qualified with one or more of these
+ * interpolation qualifiers"
+ */
+ if (state->language_version >= 130
+ && this->type->qualifier.has_interpolation()) {
+
+ const char *i = this->type->qualifier.interpolation_string();
+ assert(i != NULL);
+
+ switch (state->target) {
+ case vertex_shader:
+ if (this->type->qualifier.flags.q.in) {
+ _mesa_glsl_error(&loc, state,
+ "qualifier '%s' cannot be applied to vertex "
+ "shader inputs", i);
+ }
+ break;
+ case fragment_shader:
+ if (this->type->qualifier.flags.q.out) {
+ _mesa_glsl_error(&loc, state,
+ "qualifier '%s' cannot be applied to fragment "
+ "shader outputs", i);
+ }
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+
+ /* From section 4.3.4 of the GLSL 1.30 spec:
+ * "It is an error to use centroid in in a vertex shader."
+ */
+ if (state->language_version >= 130
+ && this->type->qualifier.flags.q.centroid
+ && this->type->qualifier.flags.q.in
+ && state->target == vertex_shader) {
+
+ _mesa_glsl_error(&loc, state,
+ "'centroid in' cannot be used in a vertex shader");
+ }
+
+
+ /* Precision qualifiers exists only in GLSL versions 1.00 and >= 1.30.
+ */
+ if (this->type->specifier->precision != ast_precision_none
+ && state->language_version != 100
+ && state->language_version < 130) {
+
+ _mesa_glsl_error(&loc, state,
+ "precision qualifiers are supported only in GLSL ES "
+ "1.00, and GLSL 1.30 and later");
+ }
+
+
+ /* Precision qualifiers only apply to floating point and integer types.
+ *
+ * From section 4.5.2 of the GLSL 1.30 spec:
+ * "Any floating point or any integer declaration can have the type
+ * preceded by one of these precision qualifiers [...] Literal
+ * constants do not have precision qualifiers. Neither do Boolean
+ * variables.
+ */
+ if (this->type->specifier->precision != ast_precision_none
+ && !var->type->is_float()
+ && !var->type->is_integer()
+ && !(var->type->is_array()
+ && (var->type->fields.array->is_float()
+ || var->type->fields.array->is_integer()))) {
+
+ _mesa_glsl_error(&loc, state,
+ "precision qualifiers apply only to floating point "
+ "and integer types");
+ }
+
+ /* Process the initializer and add its instructions to a temporary
+ * list. This list will be added to the instruction stream (below) after
+ * the declaration is added. This is done because in some cases (such as
+ * redeclarations) the declaration may not actually be added to the
+ * instruction stream.
+ */
+ exec_list initializer_instructions;
+ if (decl->initializer != NULL) {
+ YYLTYPE initializer_loc = decl->initializer->get_location();
+
+ /* From page 24 (page 30 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "All uniform variables are read-only and are initialized either
+ * directly by an application via API commands, or indirectly by
+ * OpenGL."
+ */
+ if ((state->language_version <= 110)
+ && (var->mode == ir_var_uniform)) {
+ _mesa_glsl_error(& initializer_loc, state,
+ "cannot initialize uniforms in GLSL 1.10");
+ }
+
+ if (var->type->is_sampler()) {
+ _mesa_glsl_error(& initializer_loc, state,
+ "cannot initialize samplers");
+ }
+
+ if ((var->mode == ir_var_in) && (state->current_function == NULL)) {
+ _mesa_glsl_error(& initializer_loc, state,
+ "cannot initialize %s shader input / %s",
+ _mesa_glsl_shader_target_name(state->target),
+ (state->target == vertex_shader)
+ ? "attribute" : "varying");
+ }
+
+ ir_dereference *const lhs = new(ctx) ir_dereference_variable(var);
+ ir_rvalue *rhs = decl->initializer->hir(&initializer_instructions,
+ state);
+
+ /* Calculate the constant value if this is a const or uniform
+ * declaration.
+ */
+ if (this->type->qualifier.flags.q.constant
+ || this->type->qualifier.flags.q.uniform) {
+ ir_rvalue *new_rhs = validate_assignment(state, var->type, rhs);
+ if (new_rhs != NULL) {
+ rhs = new_rhs;
+
+ ir_constant *constant_value = rhs->constant_expression_value();
+ if (!constant_value) {
+ _mesa_glsl_error(& initializer_loc, state,
+ "initializer of %s variable `%s' must be a "
+ "constant expression",
+ (this->type->qualifier.flags.q.constant)
+ ? "const" : "uniform",
+ decl->identifier);
+ if (var->type->is_numeric()) {
+ /* Reduce cascading errors. */
+ var->constant_value = ir_constant::zero(ctx, var->type);
+ }
+ } else {
+ rhs = constant_value;
+ var->constant_value = constant_value;
+ }
+ } else {
+ _mesa_glsl_error(&initializer_loc, state,
+ "initializer of type %s cannot be assigned to "
+ "variable of type %s",
+ rhs->type->name, var->type->name);
+ if (var->type->is_numeric()) {
+ /* Reduce cascading errors. */
+ var->constant_value = ir_constant::zero(ctx, var->type);
+ }
+ }
+ }
+
+ if (rhs && !rhs->type->is_error()) {
+ bool temp = var->read_only;
+ if (this->type->qualifier.flags.q.constant)
+ var->read_only = false;
+
+ /* Never emit code to initialize a uniform.
+ */
+ const glsl_type *initializer_type;
+ if (!this->type->qualifier.flags.q.uniform) {
+ result = do_assignment(&initializer_instructions, state,
+ lhs, rhs,
+ this->get_location());
+ initializer_type = result->type;
+ } else
+ initializer_type = rhs->type;
+
+ /* If the declared variable is an unsized array, it must inherrit
+ * its full type from the initializer. A declaration such as
+ *
+ * uniform float a[] = float[](1.0, 2.0, 3.0, 3.0);
+ *
+ * becomes
+ *
+ * uniform float a[4] = float[](1.0, 2.0, 3.0, 3.0);
+ *
+ * The assignment generated in the if-statement (below) will also
+ * automatically handle this case for non-uniforms.
+ *
+ * If the declared variable is not an array, the types must
+ * already match exactly. As a result, the type assignment
+ * here can be done unconditionally. For non-uniforms the call
+ * to do_assignment can change the type of the initializer (via
+ * the implicit conversion rules). For uniforms the initializer
+ * must be a constant expression, and the type of that expression
+ * was validated above.
+ */
+ var->type = initializer_type;
+
+ var->read_only = temp;
+ }
+ }
+
+ /* From page 23 (page 29 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "It is an error to write to a const variable outside of
+ * its declaration, so they must be initialized when
+ * declared."
+ */
+ if (this->type->qualifier.flags.q.constant && decl->initializer == NULL) {
+ _mesa_glsl_error(& loc, state,
+ "const declaration of `%s' must be initialized",
+ decl->identifier);
+ }
+
+ /* Check if this declaration is actually a re-declaration, either to
+ * resize an array or add qualifiers to an existing variable.
+ *
+ * This is allowed for variables in the current scope, or when at
+ * global scope (for built-ins in the implicit outer scope).
+ */
+ ir_variable *earlier = state->symbols->get_variable(decl->identifier);
+ if (earlier != NULL && (state->current_function == NULL ||
+ state->symbols->name_declared_this_scope(decl->identifier))) {
+
+ /* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec,
+ *
+ * "It is legal to declare an array without a size and then
+ * later re-declare the same name as an array of the same
+ * type and specify a size."
+ */
+ if ((earlier->type->array_size() == 0)
+ && var->type->is_array()
+ && (var->type->element_type() == earlier->type->element_type())) {
+ /* FINISHME: This doesn't match the qualifiers on the two
+ * FINISHME: declarations. It's not 100% clear whether this is
+ * FINISHME: required or not.
+ */
+
+ /* From page 54 (page 60 of the PDF) of the GLSL 1.20 spec:
+ *
+ * "The size [of gl_TexCoord] can be at most
+ * gl_MaxTextureCoords."
+ */
+ const unsigned size = unsigned(var->type->array_size());
+ if ((strcmp("gl_TexCoord", var->name) == 0)
+ && (size > state->Const.MaxTextureCoords)) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "`gl_TexCoord' array size cannot "
+ "be larger than gl_MaxTextureCoords (%u)\n",
+ state->Const.MaxTextureCoords);
+ } else if ((size > 0) && (size <= earlier->max_array_access)) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "array size must be > %u due to "
+ "previous access",
+ earlier->max_array_access);
+ }
+
+ earlier->type = var->type;
+ delete var;
+ var = NULL;
+ } else if (state->ARB_fragment_coord_conventions_enable
+ && strcmp(var->name, "gl_FragCoord") == 0
+ && earlier->type == var->type
+ && earlier->mode == var->mode) {
+ /* Allow redeclaration of gl_FragCoord for ARB_fcc layout
+ * qualifiers.
+ */
+ earlier->origin_upper_left = var->origin_upper_left;
+ earlier->pixel_center_integer = var->pixel_center_integer;
+
+ /* According to section 4.3.7 of the GLSL 1.30 spec,
+ * the following built-in varaibles can be redeclared with an
+ * interpolation qualifier:
+ * * gl_FrontColor
+ * * gl_BackColor
+ * * gl_FrontSecondaryColor
+ * * gl_BackSecondaryColor
+ * * gl_Color
+ * * gl_SecondaryColor
+ */
+ } else if (state->language_version >= 130
+ && (strcmp(var->name, "gl_FrontColor") == 0
+ || strcmp(var->name, "gl_BackColor") == 0
+ || strcmp(var->name, "gl_FrontSecondaryColor") == 0
+ || strcmp(var->name, "gl_BackSecondaryColor") == 0
+ || strcmp(var->name, "gl_Color") == 0
+ || strcmp(var->name, "gl_SecondaryColor") == 0)
+ && earlier->type == var->type
+ && earlier->mode == var->mode) {
+ earlier->interpolation = var->interpolation;
+
+ /* Layout qualifiers for gl_FragDepth. */
+ } else if (state->AMD_conservative_depth_enable
+ && strcmp(var->name, "gl_FragDepth") == 0
+ && earlier->type == var->type
+ && earlier->mode == var->mode) {
+
+ /** From the AMD_conservative_depth spec:
+ * Within any shader, the first redeclarations of gl_FragDepth
+ * must appear before any use of gl_FragDepth.
+ */
+ if (earlier->used) {
+ _mesa_glsl_error(&loc, state,
+ "the first redeclaration of gl_FragDepth "
+ "must appear before any use of gl_FragDepth");
+ }
+
+ /* Prevent inconsistent redeclaration of depth layout qualifier. */
+ if (earlier->depth_layout != ir_depth_layout_none
+ && earlier->depth_layout != var->depth_layout) {
+ _mesa_glsl_error(&loc, state,
+ "gl_FragDepth: depth layout is declared here "
+ "as '%s, but it was previously declared as "
+ "'%s'",
+ depth_layout_string(var->depth_layout),
+ depth_layout_string(earlier->depth_layout));
+ }
+
+ earlier->depth_layout = var->depth_layout;
+
+ } else {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state, "`%s' redeclared", decl->identifier);
+ }
+
+ continue;
+ }
+
+ /* By now, we know it's a new variable declaration (we didn't hit the
+ * above "continue").
+ *
+ * From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
+ *
+ * "Identifiers starting with "gl_" are reserved for use by
+ * OpenGL, and may not be declared in a shader as either a
+ * variable or a function."
+ */
+ if (strncmp(decl->identifier, "gl_", 3) == 0)
+ _mesa_glsl_error(& loc, state,
+ "identifier `%s' uses reserved `gl_' prefix",
+ decl->identifier);
+
+ /* Add the variable to the symbol table. Note that the initializer's
+ * IR was already processed earlier (though it hasn't been emitted yet),
+ * without the variable in scope.
+ *
+ * This differs from most C-like languages, but it follows the GLSL
+ * specification. From page 28 (page 34 of the PDF) of the GLSL 1.50
+ * spec:
+ *
+ * "Within a declaration, the scope of a name starts immediately
+ * after the initializer if present or immediately after the name
+ * being declared if not."
+ */
+ if (!state->symbols->add_variable(var)) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state, "name `%s' already taken in the "
+ "current scope", decl->identifier);
+ continue;
+ }
+
+ /* Push the variable declaration to the top. It means that all
+ * the variable declarations will appear in a funny
+ * last-to-first order, but otherwise we run into trouble if a
+ * function is prototyped, a global var is decled, then the
+ * function is defined with usage of the global var. See
+ * glslparsertest's CorrectModule.frag.
+ */
+ instructions->push_head(var);
+ instructions->append_list(&initializer_instructions);
+ }
+
+
+ /* Generally, variable declarations do not have r-values. However,
+ * one is used for the declaration in
+ *
+ * while (bool b = some_condition()) {
+ * ...
+ * }
+ *
+ * so we return the rvalue from the last seen declaration here.
+ */
+ return result;
+}
+
+
+ir_rvalue *
+ast_parameter_declarator::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ const struct glsl_type *type;
+ const char *name = NULL;
+ YYLTYPE loc = this->get_location();
+
+ type = this->type->specifier->glsl_type(& name, state);
+
+ if (type == NULL) {
+ if (name != NULL) {
+ _mesa_glsl_error(& loc, state,
+ "invalid type `%s' in declaration of `%s'",
+ name, this->identifier);
+ } else {
+ _mesa_glsl_error(& loc, state,
+ "invalid type in declaration of `%s'",
+ this->identifier);
+ }
+
+ type = glsl_type::error_type;
+ }
+
+ /* From page 62 (page 68 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "Functions that accept no input arguments need not use void in the
+ * argument list because prototypes (or definitions) are required and
+ * therefore there is no ambiguity when an empty argument list "( )" is
+ * declared. The idiom "(void)" as a parameter list is provided for
+ * convenience."
+ *
+ * Placing this check here prevents a void parameter being set up
+ * for a function, which avoids tripping up checks for main taking
+ * parameters and lookups of an unnamed symbol.
+ */
+ if (type->is_void()) {
+ if (this->identifier != NULL)
+ _mesa_glsl_error(& loc, state,
+ "named parameter cannot have type `void'");
+
+ is_void = true;
+ return NULL;
+ }
+
+ if (formal_parameter && (this->identifier == NULL)) {
+ _mesa_glsl_error(& loc, state, "formal parameter lacks a name");
+ return NULL;
+ }
+
+ /* This only handles "vec4 foo[..]". The earlier specifier->glsl_type(...)
+ * call already handled the "vec4[..] foo" case.
+ */
+ if (this->is_array) {
+ type = process_array_type(&loc, type, this->array_size, state);
+ }
+
+ if (type->array_size() == 0) {
+ _mesa_glsl_error(&loc, state, "arrays passed as parameters must have "
+ "a declared size.");
+ type = glsl_type::error_type;
+ }
+
+ is_void = false;
+ ir_variable *var = new(ctx) ir_variable(type, this->identifier, ir_var_in);
+
+ /* Apply any specified qualifiers to the parameter declaration. Note that
+ * for function parameters the default mode is 'in'.
+ */
+ apply_type_qualifier_to_variable(& this->type->qualifier, var, state, & loc);
+
+ instructions->push_tail(var);
+
+ /* Parameter declarations do not have r-values.
+ */
+ return NULL;
+}
+
+
+void
+ast_parameter_declarator::parameters_to_hir(exec_list *ast_parameters,
+ bool formal,
+ exec_list *ir_parameters,
+ _mesa_glsl_parse_state *state)
+{
+ ast_parameter_declarator *void_param = NULL;
+ unsigned count = 0;
+
+ foreach_list_typed (ast_parameter_declarator, param, link, ast_parameters) {
+ param->formal_parameter = formal;
+ param->hir(ir_parameters, state);
+
+ if (param->is_void)
+ void_param = param;
+
+ count++;
+ }
+
+ if ((void_param != NULL) && (count > 1)) {
+ YYLTYPE loc = void_param->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "`void' parameter must be only parameter");
+ }
+}
+
+
+void
+emit_function(_mesa_glsl_parse_state *state, exec_list *instructions,
+ ir_function *f)
+{
+ /* Emit the new function header */
+ if (state->current_function == NULL) {
+ instructions->push_tail(f);
+ } else {
+ /* IR invariants disallow function declarations or definitions nested
+ * within other function definitions. Insert the new ir_function
+ * block in the instruction sequence before the ir_function block
+ * containing the current ir_function_signature.
+ */
+ ir_function *const curr =
+ const_cast<ir_function *>(state->current_function->function());
+
+ curr->insert_before(f);
+ }
+}
+
+
+ir_rvalue *
+ast_function::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ ir_function *f = NULL;
+ ir_function_signature *sig = NULL;
+ exec_list hir_parameters;
+
+ const char *const name = identifier;
+
+ /* From page 21 (page 27 of the PDF) of the GLSL 1.20 spec,
+ *
+ * "Function declarations (prototypes) cannot occur inside of functions;
+ * they must be at global scope, or for the built-in functions, outside
+ * the global scope."
+ *
+ * From page 27 (page 33 of the PDF) of the GLSL ES 1.00.16 spec,
+ *
+ * "User defined functions may only be defined within the global scope."
+ *
+ * Note that this language does not appear in GLSL 1.10.
+ */
+ if ((state->current_function != NULL) && (state->language_version != 110)) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state,
+ "declaration of function `%s' not allowed within "
+ "function body", name);
+ }
+
+ /* From page 15 (page 21 of the PDF) of the GLSL 1.10 spec,
+ *
+ * "Identifiers starting with "gl_" are reserved for use by
+ * OpenGL, and may not be declared in a shader as either a
+ * variable or a function."
+ */
+ if (strncmp(name, "gl_", 3) == 0) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state,
+ "identifier `%s' uses reserved `gl_' prefix", name);
+ }
+
+ /* Convert the list of function parameters to HIR now so that they can be
+ * used below to compare this function's signature with previously seen
+ * signatures for functions with the same name.
+ */
+ ast_parameter_declarator::parameters_to_hir(& this->parameters,
+ is_definition,
+ & hir_parameters, state);
+
+ const char *return_type_name;
+ const glsl_type *return_type =
+ this->return_type->specifier->glsl_type(& return_type_name, state);
+
+ if (!return_type) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state,
+ "function `%s' has undeclared return type `%s'",
+ name, return_type_name);
+ return_type = glsl_type::error_type;
+ }
+
+ /* From page 56 (page 62 of the PDF) of the GLSL 1.30 spec:
+ * "No qualifier is allowed on the return type of a function."
+ */
+ if (this->return_type->has_qualifiers()) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(& loc, state,
+ "function `%s' return type has qualifiers", name);
+ }
+
+ /* Verify that this function's signature either doesn't match a previously
+ * seen signature for a function with the same name, or, if a match is found,
+ * that the previously seen signature does not have an associated definition.
+ */
+ f = state->symbols->get_function(name);
+ if (f != NULL && (state->es_shader || f->has_user_signature())) {
+ sig = f->exact_matching_signature(&hir_parameters);
+ if (sig != NULL) {
+ const char *badvar = sig->qualifiers_match(&hir_parameters);
+ if (badvar != NULL) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(&loc, state, "function `%s' parameter `%s' "
+ "qualifiers don't match prototype", name, badvar);
+ }
+
+ if (sig->return_type != return_type) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(&loc, state, "function `%s' return type doesn't "
+ "match prototype", name);
+ }
+
+ if (is_definition && sig->is_defined) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "function `%s' redefined", name);
+ }
+ }
+ } else {
+ f = new(ctx) ir_function(name);
+ if (!state->symbols->add_function(f)) {
+ /* This function name shadows a non-function use of the same name. */
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(&loc, state, "function name `%s' conflicts with "
+ "non-function", name);
+ return NULL;
+ }
+
+ emit_function(state, instructions, f);
+ }
+
+ /* Verify the return type of main() */
+ if (strcmp(name, "main") == 0) {
+ if (! return_type->is_void()) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "main() must return void");
+ }
+
+ if (!hir_parameters.is_empty()) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "main() must not take any parameters");
+ }
+ }
+
+ /* Finish storing the information about this new function in its signature.
+ */
+ if (sig == NULL) {
+ sig = new(ctx) ir_function_signature(return_type);
+ f->add_signature(sig);
+ }
+
+ sig->replace_parameters(&hir_parameters);
+ signature = sig;
+
+ /* Function declarations (prototypes) do not have r-values.
+ */
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_function_definition::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ prototype->is_definition = true;
+ prototype->hir(instructions, state);
+
+ ir_function_signature *signature = prototype->signature;
+ if (signature == NULL)
+ return NULL;
+
+ assert(state->current_function == NULL);
+ state->current_function = signature;
+ state->found_return = false;
+
+ /* Duplicate parameters declared in the prototype as concrete variables.
+ * Add these to the symbol table.
+ */
+ state->symbols->push_scope();
+ foreach_iter(exec_list_iterator, iter, signature->parameters) {
+ ir_variable *const var = ((ir_instruction *) iter.get())->as_variable();
+
+ assert(var != NULL);
+
+ /* The only way a parameter would "exist" is if two parameters have
+ * the same name.
+ */
+ if (state->symbols->name_declared_this_scope(var->name)) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state, "parameter `%s' redeclared", var->name);
+ } else {
+ state->symbols->add_variable(var);
+ }
+ }
+
+ /* Convert the body of the function to HIR. */
+ this->body->hir(&signature->body, state);
+ signature->is_defined = true;
+
+ state->symbols->pop_scope();
+
+ assert(state->current_function == signature);
+ state->current_function = NULL;
+
+ if (!signature->return_type->is_void() && !state->found_return) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(& loc, state, "function `%s' has non-void return type "
+ "%s, but no return statement",
+ signature->function_name(),
+ signature->return_type->name);
+ }
+
+ /* Function definitions do not have r-values.
+ */
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_jump_statement::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+
+ switch (mode) {
+ case ast_return: {
+ ir_return *inst;
+ assert(state->current_function);
+
+ if (opt_return_value) {
+ ir_rvalue *const ret = opt_return_value->hir(instructions, state);
+
+ /* The value of the return type can be NULL if the shader says
+ * 'return foo();' and foo() is a function that returns void.
+ *
+ * NOTE: The GLSL spec doesn't say that this is an error. The type
+ * of the return value is void. If the return type of the function is
+ * also void, then this should compile without error. Seriously.
+ */
+ const glsl_type *const ret_type =
+ (ret == NULL) ? glsl_type::void_type : ret->type;
+
+ /* Implicit conversions are not allowed for return values. */
+ if (state->current_function->return_type != ret_type) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "`return' with wrong type %s, in function `%s' "
+ "returning %s",
+ ret_type->name,
+ state->current_function->function_name(),
+ state->current_function->return_type->name);
+ }
+
+ inst = new(ctx) ir_return(ret);
+ } else {
+ if (state->current_function->return_type->base_type !=
+ GLSL_TYPE_VOID) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "`return' with no value, in function %s returning "
+ "non-void",
+ state->current_function->function_name());
+ }
+ inst = new(ctx) ir_return;
+ }
+
+ state->found_return = true;
+ instructions->push_tail(inst);
+ break;
+ }
+
+ case ast_discard:
+ if (state->target != fragment_shader) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "`discard' may only appear in a fragment shader");
+ }
+ instructions->push_tail(new(ctx) ir_discard);
+ break;
+
+ case ast_break:
+ case ast_continue:
+ /* FINISHME: Handle switch-statements. They cannot contain 'continue',
+ * FINISHME: and they use a different IR instruction for 'break'.
+ */
+ /* FINISHME: Correctly handle the nesting. If a switch-statement is
+ * FINISHME: inside a loop, a 'continue' is valid and will bind to the
+ * FINISHME: loop.
+ */
+ if (state->loop_or_switch_nesting == NULL) {
+ YYLTYPE loc = this->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "`%s' may only appear in a loop",
+ (mode == ast_break) ? "break" : "continue");
+ } else {
+ ir_loop *const loop = state->loop_or_switch_nesting->as_loop();
+
+ /* Inline the for loop expression again, since we don't know
+ * where near the end of the loop body the normal copy of it
+ * is going to be placed.
+ */
+ if (mode == ast_continue &&
+ state->loop_or_switch_nesting_ast->rest_expression) {
+ state->loop_or_switch_nesting_ast->rest_expression->hir(instructions,
+ state);
+ }
+
+ if (loop != NULL) {
+ ir_loop_jump *const jump =
+ new(ctx) ir_loop_jump((mode == ast_break)
+ ? ir_loop_jump::jump_break
+ : ir_loop_jump::jump_continue);
+ instructions->push_tail(jump);
+ }
+ }
+
+ break;
+ }
+
+ /* Jump instructions do not have r-values.
+ */
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_selection_statement::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+
+ ir_rvalue *const condition = this->condition->hir(instructions, state);
+
+ /* From page 66 (page 72 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "Any expression whose type evaluates to a Boolean can be used as the
+ * conditional expression bool-expression. Vector types are not accepted
+ * as the expression to if."
+ *
+ * The checks are separated so that higher quality diagnostics can be
+ * generated for cases where both rules are violated.
+ */
+ if (!condition->type->is_boolean() || !condition->type->is_scalar()) {
+ YYLTYPE loc = this->condition->get_location();
+
+ _mesa_glsl_error(& loc, state, "if-statement condition must be scalar "
+ "boolean");
+ }
+
+ ir_if *const stmt = new(ctx) ir_if(condition);
+
+ if (then_statement != NULL) {
+ state->symbols->push_scope();
+ then_statement->hir(& stmt->then_instructions, state);
+ state->symbols->pop_scope();
+ }
+
+ if (else_statement != NULL) {
+ state->symbols->push_scope();
+ else_statement->hir(& stmt->else_instructions, state);
+ state->symbols->pop_scope();
+ }
+
+ instructions->push_tail(stmt);
+
+ /* if-statements do not have r-values.
+ */
+ return NULL;
+}
+
+
+void
+ast_iteration_statement::condition_to_hir(ir_loop *stmt,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+
+ if (condition != NULL) {
+ ir_rvalue *const cond =
+ condition->hir(& stmt->body_instructions, state);
+
+ if ((cond == NULL)
+ || !cond->type->is_boolean() || !cond->type->is_scalar()) {
+ YYLTYPE loc = condition->get_location();
+
+ _mesa_glsl_error(& loc, state,
+ "loop condition must be scalar boolean");
+ } else {
+ /* As the first code in the loop body, generate a block that looks
+ * like 'if (!condition) break;' as the loop termination condition.
+ */
+ ir_rvalue *const not_cond =
+ new(ctx) ir_expression(ir_unop_logic_not, glsl_type::bool_type, cond,
+ NULL);
+
+ ir_if *const if_stmt = new(ctx) ir_if(not_cond);
+
+ ir_jump *const break_stmt =
+ new(ctx) ir_loop_jump(ir_loop_jump::jump_break);
+
+ if_stmt->then_instructions.push_tail(break_stmt);
+ stmt->body_instructions.push_tail(if_stmt);
+ }
+ }
+}
+
+
+ir_rvalue *
+ast_iteration_statement::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+
+ /* For-loops and while-loops start a new scope, but do-while loops do not.
+ */
+ if (mode != ast_do_while)
+ state->symbols->push_scope();
+
+ if (init_statement != NULL)
+ init_statement->hir(instructions, state);
+
+ ir_loop *const stmt = new(ctx) ir_loop();
+ instructions->push_tail(stmt);
+
+ /* Track the current loop and / or switch-statement nesting.
+ */
+ ir_instruction *const nesting = state->loop_or_switch_nesting;
+ ast_iteration_statement *nesting_ast = state->loop_or_switch_nesting_ast;
+
+ state->loop_or_switch_nesting = stmt;
+ state->loop_or_switch_nesting_ast = this;
+
+ if (mode != ast_do_while)
+ condition_to_hir(stmt, state);
+
+ if (body != NULL)
+ body->hir(& stmt->body_instructions, state);
+
+ if (rest_expression != NULL)
+ rest_expression->hir(& stmt->body_instructions, state);
+
+ if (mode == ast_do_while)
+ condition_to_hir(stmt, state);
+
+ if (mode != ast_do_while)
+ state->symbols->pop_scope();
+
+ /* Restore previous nesting before returning.
+ */
+ state->loop_or_switch_nesting = nesting;
+ state->loop_or_switch_nesting_ast = nesting_ast;
+
+ /* Loops do not have r-values.
+ */
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_type_specifier::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ if (!this->is_precision_statement && this->structure == NULL)
+ return NULL;
+
+ YYLTYPE loc = this->get_location();
+
+ if (this->precision != ast_precision_none
+ && state->language_version != 100
+ && state->language_version < 130) {
+ _mesa_glsl_error(&loc, state,
+ "precision qualifiers exist only in "
+ "GLSL ES 1.00, and GLSL 1.30 and later");
+ return NULL;
+ }
+ if (this->precision != ast_precision_none
+ && this->structure != NULL) {
+ _mesa_glsl_error(&loc, state,
+ "precision qualifiers do not apply to structures");
+ return NULL;
+ }
+
+ /* If this is a precision statement, check that the type to which it is
+ * applied is either float or int.
+ *
+ * From section 4.5.3 of the GLSL 1.30 spec:
+ * "The precision statement
+ * precision precision-qualifier type;
+ * can be used to establish a default precision qualifier. The type
+ * field can be either int or float [...]. Any other types or
+ * qualifiers will result in an error.
+ */
+ if (this->is_precision_statement) {
+ assert(this->precision != ast_precision_none);
+ assert(this->structure == NULL); /* The check for structures was
+ * performed above. */
+ if (this->is_array) {
+ _mesa_glsl_error(&loc, state,
+ "default precision statements do not apply to "
+ "arrays");
+ return NULL;
+ }
+ if (this->type_specifier != ast_float
+ && this->type_specifier != ast_int) {
+ _mesa_glsl_error(&loc, state,
+ "default precision statements apply only to types "
+ "float and int");
+ return NULL;
+ }
+
+ /* FINISHME: Translate precision statements into IR. */
+ return NULL;
+ }
+
+ if (this->structure != NULL)
+ return this->structure->hir(instructions, state);
+
+ return NULL;
+}
+
+
+ir_rvalue *
+ast_struct_specifier::hir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ unsigned decl_count = 0;
+
+ /* Make an initial pass over the list of structure fields to determine how
+ * many there are. Each element in this list is an ast_declarator_list.
+ * This means that we actually need to count the number of elements in the
+ * 'declarations' list in each of the elements.
+ */
+ foreach_list_typed (ast_declarator_list, decl_list, link,
+ &this->declarations) {
+ foreach_list_const (decl_ptr, & decl_list->declarations) {
+ decl_count++;
+ }
+ }
+
+ /* Allocate storage for the structure fields and process the field
+ * declarations. As the declarations are processed, try to also convert
+ * the types to HIR. This ensures that structure definitions embedded in
+ * other structure definitions are processed.
+ */
+ glsl_struct_field *const fields = ralloc_array(state, glsl_struct_field,
+ decl_count);
+
+ unsigned i = 0;
+ foreach_list_typed (ast_declarator_list, decl_list, link,
+ &this->declarations) {
+ const char *type_name;
+
+ decl_list->type->specifier->hir(instructions, state);
+
+ /* Section 10.9 of the GLSL ES 1.00 specification states that
+ * embedded structure definitions have been removed from the language.
+ */
+ if (state->es_shader && decl_list->type->specifier->structure != NULL) {
+ YYLTYPE loc = this->get_location();
+ _mesa_glsl_error(&loc, state, "Embedded structure definitions are "
+ "not allowed in GLSL ES 1.00.");
+ }
+
+ const glsl_type *decl_type =
+ decl_list->type->specifier->glsl_type(& type_name, state);
+
+ foreach_list_typed (ast_declaration, decl, link,
+ &decl_list->declarations) {
+ const struct glsl_type *field_type = decl_type;
+ if (decl->is_array) {
+ YYLTYPE loc = decl->get_location();
+ field_type = process_array_type(&loc, decl_type, decl->array_size,
+ state);
+ }
+ fields[i].type = (field_type != NULL)
+ ? field_type : glsl_type::error_type;
+ fields[i].name = decl->identifier;
+ i++;
+ }
+ }
+
+ assert(i == decl_count);
+
+ const glsl_type *t =
+ glsl_type::get_record_instance(fields, decl_count, this->name);
+
+ YYLTYPE loc = this->get_location();
+ if (!state->symbols->add_type(name, t)) {
+ _mesa_glsl_error(& loc, state, "struct `%s' previously defined", name);
+ } else {
+
+ const glsl_type **s = (const glsl_type **)
+ realloc(state->user_structures,
+ sizeof(state->user_structures[0]) *
+ (state->num_user_structures + 1));
+ if (s != NULL) {
+ s[state->num_user_structures] = t;
+ state->user_structures = s;
+ state->num_user_structures++;
+ }
+ }
+
+ /* Structure type definitions do not have r-values.
+ */
+ return NULL;
+}
diff --git a/mesalib/src/glsl/ast_type.cpp b/mesalib/src/glsl/ast_type.cpp
index c680ae5f6..8e49bef8a 100644
--- a/mesalib/src/glsl/ast_type.cpp
+++ b/mesalib/src/glsl/ast_type.cpp
@@ -1,138 +1,138 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include "ast.h"
-extern "C" {
-#include "program/symbol_table.h"
-}
-
-void
-ast_type_specifier::print(void) const
-{
- if (type_specifier == ast_struct) {
- structure->print();
- } else {
- printf("%s ", type_name);
- }
-
- if (is_array) {
- printf("[ ");
-
- if (array_size) {
- array_size->print();
- }
-
- printf("] ");
- }
-}
-
-ast_type_specifier::ast_type_specifier(int specifier)
- : type_specifier(ast_types(specifier)), type_name(NULL), structure(NULL),
- is_array(false), array_size(NULL), precision(ast_precision_none),
- is_precision_statement(false)
-{
- static const char *const names[] = {
- "void",
- "float",
- "int",
- "uint",
- "bool",
- "vec2",
- "vec3",
- "vec4",
- "bvec2",
- "bvec3",
- "bvec4",
- "ivec2",
- "ivec3",
- "ivec4",
- "uvec2",
- "uvec3",
- "uvec4",
- "mat2",
- "mat2x3",
- "mat2x4",
- "mat3x2",
- "mat3",
- "mat3x4",
- "mat4x2",
- "mat4x3",
- "mat4",
- "sampler1D",
- "sampler2D",
- "sampler2DRect",
- "sampler3D",
- "samplerCube",
- "sampler1DShadow",
- "sampler2DShadow",
- "sampler2DRectShadow",
- "samplerCubeShadow",
- "sampler1DArray",
- "sampler2DArray",
- "sampler1DArrayShadow",
- "sampler2DArrayShadow",
- "isampler1D",
- "isampler2D",
- "isampler3D",
- "isamplerCube",
- "isampler1DArray",
- "isampler2DArray",
- "usampler1D",
- "usampler2D",
- "usampler3D",
- "usamplerCube",
- "usampler1DArray",
- "usampler2DArray",
-
- NULL, /* ast_struct */
- NULL /* ast_type_name */
- };
-
- type_name = names[specifier];
-}
-
-bool
-ast_fully_specified_type::has_qualifiers() const
-{
- return this->qualifier.flags.i != 0;
-}
-
-bool ast_type_qualifier::has_interpolation() const
-{
- return this->flags.q.smooth
- || this->flags.q.flat
- || this->flags.q.noperspective;
-}
-
-const char*
-ast_type_qualifier::interpolation_string() const
-{
- if (this->flags.q.smooth)
- return "smooth";
- else if (this->flags.q.flat)
- return "flat";
- else if (this->flags.q.noperspective)
- return "noperspective";
- else
- return NULL;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include "ast.h"
+extern "C" {
+#include "program/symbol_table.h"
+}
+
+void
+ast_type_specifier::print(void) const
+{
+ if (type_specifier == ast_struct) {
+ structure->print();
+ } else {
+ printf("%s ", type_name);
+ }
+
+ if (is_array) {
+ printf("[ ");
+
+ if (array_size) {
+ array_size->print();
+ }
+
+ printf("] ");
+ }
+}
+
+ast_type_specifier::ast_type_specifier(int specifier)
+ : type_specifier(ast_types(specifier)), type_name(NULL), structure(NULL),
+ is_array(false), array_size(NULL), precision(ast_precision_none),
+ is_precision_statement(false)
+{
+ static const char *const names[] = {
+ "void",
+ "float",
+ "int",
+ "uint",
+ "bool",
+ "vec2",
+ "vec3",
+ "vec4",
+ "bvec2",
+ "bvec3",
+ "bvec4",
+ "ivec2",
+ "ivec3",
+ "ivec4",
+ "uvec2",
+ "uvec3",
+ "uvec4",
+ "mat2",
+ "mat2x3",
+ "mat2x4",
+ "mat3x2",
+ "mat3",
+ "mat3x4",
+ "mat4x2",
+ "mat4x3",
+ "mat4",
+ "sampler1D",
+ "sampler2D",
+ "sampler2DRect",
+ "sampler3D",
+ "samplerCube",
+ "sampler1DShadow",
+ "sampler2DShadow",
+ "sampler2DRectShadow",
+ "samplerCubeShadow",
+ "sampler1DArray",
+ "sampler2DArray",
+ "sampler1DArrayShadow",
+ "sampler2DArrayShadow",
+ "isampler1D",
+ "isampler2D",
+ "isampler3D",
+ "isamplerCube",
+ "isampler1DArray",
+ "isampler2DArray",
+ "usampler1D",
+ "usampler2D",
+ "usampler3D",
+ "usamplerCube",
+ "usampler1DArray",
+ "usampler2DArray",
+
+ NULL, /* ast_struct */
+ NULL /* ast_type_name */
+ };
+
+ type_name = names[specifier];
+}
+
+bool
+ast_fully_specified_type::has_qualifiers() const
+{
+ return this->qualifier.flags.i != 0;
+}
+
+bool ast_type_qualifier::has_interpolation() const
+{
+ return this->flags.q.smooth
+ || this->flags.q.flat
+ || this->flags.q.noperspective;
+}
+
+const char*
+ast_type_qualifier::interpolation_string() const
+{
+ if (this->flags.q.smooth)
+ return "smooth";
+ else if (this->flags.q.flat)
+ return "flat";
+ else if (this->flags.q.noperspective)
+ return "noperspective";
+ else
+ return NULL;
+}
diff --git a/mesalib/src/glsl/getopt.cpp b/mesalib/src/glsl/getopt.cpp
new file mode 100644
index 000000000..ea5dd3927
--- /dev/null
+++ b/mesalib/src/glsl/getopt.cpp
@@ -0,0 +1,552 @@
+/* $OpenBSD: getopt_long.c,v 1.20 2005/10/25 15:49:37 jmc Exp $ */
+/* $NetBSD: getopt_long.c,v 1.15 2002/01/31 22:43:40 tv Exp $ */
+// Adapted for Box Backup by Chris Wilson <chris+boxbackup@qwirx.com>
+
+/*
+ * Copyright (c) 2002 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ *
+ * Sponsored in part by the Defense Advanced Research Projects
+ * Agency (DARPA) and Air Force Research Laboratory, Air Force
+ * Materiel Command, USAF, under agreement number F39502-99-1-0512.
+ */
+/*-
+ * Copyright (c) 2000 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Dieter Baron and Thomas Klausner.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. All advertising materials mentioning features or use of this software
+ * must display the following acknowledgement:
+ * This product includes software developed by the NetBSD
+ * Foundation, Inc. and its contributors.
+ * 4. Neither the name of The NetBSD Foundation nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+ * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// #include "Box.h"
+
+#include <errno.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+#define __STDC__ 1
+
+#include "getopt.h"
+
+#if defined _MSC_VER || defined __MINGW32__
+#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */
+
+#ifdef REPLACE_GETOPT
+int opterr = 1; /* if error message should be printed */
+int optind = 1; /* index into parent argv vector */
+int optopt = '?'; /* character checked for validity */
+int optreset; /* reset getopt */
+char *optarg; /* argument associated with option */
+#endif
+
+#define PRINT_ERROR ((opterr) && (*options != ':'))
+
+#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */
+#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */
+#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */
+
+/* return values */
+#define BADCH (int)'?'
+#define BADARG ((*options == ':') ? (int)':' : (int)'?')
+#define INORDER (int)1
+
+#define EMSG ""
+
+static void warnx(const char* fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fprintf(stderr, "\n");
+ }
+
+ static int getopt_internal(int, char * const *, const char *,
+ const struct option *, int *, int);
+ static int parse_long_options(char * const *, const char *,
+ const struct option *, int *, int);
+ static int gcd(int, int);
+ static void permute_args(int, int, int, char * const *);
+
+ static char *place = EMSG; /* option letter processing */
+
+ /* XXX: set optreset to 1 rather than these two */
+ static int nonopt_start = -1; /* first non option argument (for permute) */
+ static int nonopt_end = -1; /* first option after non options (for permute) */
+
+ /* Error messages */
+ static const char recargchar[] = "option requires an argument -- %c";
+ static const char recargstring[] = "option requires an argument -- %s";
+ static const char ambig[] = "ambiguous option -- %.*s";
+ static const char noarg[] = "option doesn't take an argument -- %.*s";
+ static const char illoptchar[] = "unknown option -- %c";
+ static const char illoptstring[] = "unknown option -- %s";
+
+ /*
+ * Compute the greatest common divisor of a and b.
+ */
+ static int
+ gcd(int a, int b)
+ {
+ int c;
+
+ c = a % b;
+ while (c != 0) {
+ a = b;
+ b = c;
+ c = a % b;
+ }
+
+ return (b);
+ }
+
+ /*
+ * Exchange the block from nonopt_start to nonopt_end with the block
+ * from nonopt_end to opt_end (keeping the same order of arguments
+ * in each block).
+ */
+ static void
+ permute_args(int panonopt_start, int panonopt_end, int opt_end,
+ char * const *nargv)
+ {
+ int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
+ char *swap;
+
+ /*
+ * compute lengths of blocks and number and size of cycles
+ */
+ nnonopts = panonopt_end - panonopt_start;
+ nopts = opt_end - panonopt_end;
+ ncycle = gcd(nnonopts, nopts);
+ cyclelen = (opt_end - panonopt_start) / ncycle;
+
+ for (i = 0; i < ncycle; i++) {
+ cstart = panonopt_end+i;
+ pos = cstart;
+ for (j = 0; j < cyclelen; j++) {
+ if (pos >= panonopt_end)
+ pos -= nnonopts;
+ else
+ pos += nopts;
+ swap = nargv[pos];
+ /* LINTED const cast */
+ ((char **) nargv)[pos] = nargv[cstart];
+ /* LINTED const cast */
+ ((char **)nargv)[cstart] = swap;
+ }
+ }
+ }
+
+ /*
+ * parse_long_options --
+ * Parse long options in argc/argv argument vector.
+ * Returns -1 if short_too is set and the option does not match long_options.
+ */
+ static int
+ parse_long_options(char * const *nargv, const char *options,
+ const struct option *long_options, int *idx, int short_too)
+ {
+ char *current_argv, *has_equal;
+ size_t current_argv_len;
+ int i, match;
+
+ current_argv = place;
+ match = -1;
+
+ optind++;
+
+ if ((has_equal = strchr(current_argv, '=')) != NULL) {
+ /* argument found (--option=arg) */
+ current_argv_len = has_equal - current_argv;
+ has_equal++;
+ } else
+ current_argv_len = strlen(current_argv);
+
+ for (i = 0; long_options[i].name; i++) {
+ /* find matching long option */
+ if (strncmp(current_argv, long_options[i].name,
+ current_argv_len))
+ continue;
+
+ if (strlen(long_options[i].name) == current_argv_len) {
+ /* exact match */
+ match = i;
+ break;
+ }
+ /*
+ * If this is a known short option, don't allow
+ * a partial match of a single character.
+ */
+ if (short_too && current_argv_len == 1)
+ continue;
+
+ if (match == -1) /* partial match */
+ match = i;
+ else {
+ /* ambiguous abbreviation */
+ if (PRINT_ERROR)
+ warnx(ambig, (int)current_argv_len,
+ current_argv);
+ optopt = 0;
+ return (BADCH);
+ }
+ }
+ if (match != -1) { /* option found */
+ if (long_options[match].has_arg == no_argument
+ && has_equal) {
+ if (PRINT_ERROR)
+ warnx(noarg, (int)current_argv_len,
+ current_argv);
+ /*
+ * XXX: GNU sets optopt to val regardless of flag
+ */
+ if (long_options[match].flag == NULL)
+ optopt = long_options[match].val;
+ else
+ optopt = 0;
+ return (BADARG);
+ }
+ if (long_options[match].has_arg == required_argument ||
+ long_options[match].has_arg == optional_argument) {
+ if (has_equal)
+ optarg = has_equal;
+ else if (long_options[match].has_arg ==
+ required_argument) {
+ /*
+ * optional argument doesn't use next nargv
+ */
+ optarg = nargv[optind++];
+ }
+ }
+ if ((long_options[match].has_arg == required_argument)
+ && (optarg == NULL)) {
+ /*
+ * Missing argument; leading ':' indicates no error
+ * should be generated.
+ */
+ if (PRINT_ERROR)
+ warnx(recargstring,
+ current_argv);
+ /*
+ * XXX: GNU sets optopt to val regardless of flag
+ */
+ if (long_options[match].flag == NULL)
+ optopt = long_options[match].val;
+ else
+ optopt = 0;
+ --optind;
+ return (BADARG);
+ }
+ } else { /* unknown option */
+ if (short_too) {
+ --optind;
+ return (-1);
+ }
+ if (PRINT_ERROR)
+ warnx(illoptstring, current_argv);
+ optopt = 0;
+ return (BADCH);
+ }
+ if (idx)
+ *idx = match;
+ if (long_options[match].flag) {
+ *long_options[match].flag = long_options[match].val;
+ return (0);
+ } else
+ return (long_options[match].val);
+ }
+
+ /*
+ * getopt_internal --
+ * Parse argc/argv argument vector. Called by user level routines.
+ */
+ static int
+ getopt_internal(int nargc, char * const *nargv, const char *options,
+ const struct option *long_options, int *idx, int flags)
+ {
+ const char * oli; /* option letter list index */
+ int optchar, short_too;
+ static int posixly_correct = -1;
+
+ if (options == NULL)
+ return (-1);
+
+ /*
+ * Disable GNU extensions if POSIXLY_CORRECT is set or options
+ * string begins with a '+'.
+ */
+ if (posixly_correct == -1)
+ posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
+ if (posixly_correct || *options == '+')
+ flags &= ~FLAG_PERMUTE;
+ else if (*options == '-')
+ flags |= FLAG_ALLARGS;
+ if (*options == '+' || *options == '-')
+ options++;
+
+ /*
+ * XXX Some GNU programs (like cvs) set optind to 0 instead of
+ * XXX using optreset. Work around this braindamage.
+ */
+ if (optind == 0)
+ optind = optreset = 1;
+
+ optarg = NULL;
+ if (optreset)
+ nonopt_start = nonopt_end = -1;
+ start:
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc) { /* end of argument vector */
+ place = EMSG;
+ if (nonopt_end != -1) {
+ /* do permutation, if we have to */
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ optind -= nonopt_end - nonopt_start;
+ }
+ else if (nonopt_start != -1) {
+ /*
+ * If we skipped non-options, set optind
+ * to the first of them.
+ */
+ optind = nonopt_start;
+ }
+ nonopt_start = nonopt_end = -1;
+ return (-1);
+ }
+ if (*(place = nargv[optind]) != '-' ||
+ (place[1] == '\0' && strchr(options, '-') == NULL)) {
+ place = EMSG; /* found non-option */
+ if (flags & FLAG_ALLARGS) {
+ /*
+ * GNU extension:
+ * return non-option as argument to option 1
+ */
+ optarg = nargv[optind++];
+ return (INORDER);
+ }
+ if (!(flags & FLAG_PERMUTE)) {
+ /*
+ * If no permutation wanted, stop parsing
+ * at first non-option.
+ */
+ return (-1);
+ }
+ /* do permutation */
+ if (nonopt_start == -1)
+ nonopt_start = optind;
+ else if (nonopt_end != -1) {
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ nonopt_start = optind -
+ (nonopt_end - nonopt_start);
+ nonopt_end = -1;
+ }
+ optind++;
+ /* process next argument */
+ goto start;
+ }
+ if (nonopt_start != -1 && nonopt_end == -1)
+ nonopt_end = optind;
+
+ /*
+ * If we have "-" do nothing, if "--" we are done.
+ */
+ if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
+ optind++;
+ place = EMSG;
+ /*
+ * We found an option (--), so if we skipped
+ * non-options, we have to permute.
+ */
+ if (nonopt_end != -1) {
+ permute_args(nonopt_start, nonopt_end,
+ optind, nargv);
+ optind -= nonopt_end - nonopt_start;
+ }
+ nonopt_start = nonopt_end = -1;
+ return (-1);
+ }
+ }
+
+ /*
+ * Check long options if:
+ * 1) we were passed some
+ * 2) the arg is not just "-"
+ * 3) either the arg starts with -- we are getopt_long_only()
+ */
+ if (long_options != NULL && place != nargv[optind] &&
+ (*place == '-' || (flags & FLAG_LONGONLY))) {
+ short_too = 0;
+ if (*place == '-')
+ place++; /* --foo long option */
+ else if (*place != ':' && strchr(options, *place) != NULL)
+ short_too = 1; /* could be short option too */
+
+ optchar = parse_long_options(nargv, options, long_options,
+ idx, short_too);
+ if (optchar != -1) {
+ place = EMSG;
+ return (optchar);
+ }
+ }
+
+ if ((optchar = (int)*place++) == (int)':' ||
+ optchar == (int)'-' && *place != '\0' ||
+ (oli = strchr(options, optchar)) == NULL) {
+ /*
+ * If the user specified "-" and '-' isn't listed in
+ * options, return -1 (non-option) as per POSIX.
+ * Otherwise, it is an unknown option character (or ':').
+ */
+ if (optchar == (int)'-' && *place == '\0')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (PRINT_ERROR)
+ warnx(illoptchar, optchar);
+ optopt = optchar;
+ return (BADCH);
+ }
+ if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
+ /* -W long-option */
+ if (*place) /* no space */
+ /* NOTHING */;
+ else if (++optind >= nargc) { /* no arg */
+ place = EMSG;
+ if (PRINT_ERROR)
+ warnx(recargchar, optchar);
+ optopt = optchar;
+ return (BADARG);
+ } else /* white space */
+ place = nargv[optind];
+ optchar = parse_long_options(nargv, options, long_options,
+ idx, 0);
+ place = EMSG;
+ return (optchar);
+ }
+ if (*++oli != ':') { /* doesn't take argument */
+ if (!*place)
+ ++optind;
+ } else { /* takes (optional) argument */
+ optarg = NULL;
+ if (*place) /* no white space */
+ optarg = place;
+ /* XXX: disable test for :: if PC? (GNU doesn't) */
+ else if (oli[1] != ':') { /* arg not optional */
+ if (++optind >= nargc) { /* no arg */
+ place = EMSG;
+ if (PRINT_ERROR)
+ warnx(recargchar, optchar);
+ optopt = optchar;
+ return (BADARG);
+ } else
+ optarg = nargv[optind];
+ } else if (!(flags & FLAG_PERMUTE)) {
+ /*
+ * If permutation is disabled, we can accept an
+ * optional arg separated by whitespace so long
+ * as it does not start with a dash (-).
+ */
+ if (optind + 1 < nargc && *nargv[optind + 1] != '-')
+ optarg = nargv[++optind];
+ }
+ place = EMSG;
+ ++optind;
+ }
+ /* dump back option letter */
+ return (optchar);
+ }
+
+ #ifdef REPLACE_GETOPT
+ /*
+ * getopt --
+ * Parse argc/argv argument vector.
+ *
+ * [eventually this will replace the BSD getopt]
+ */
+ int
+ getopt(int nargc, char * const *nargv, const char *options)
+ {
+
+ /*
+ * We don't pass FLAG_PERMUTE to getopt_internal() since
+ * the BSD getopt(3) (unlike GNU) has never done this.
+ *
+ * Furthermore, since many privileged programs call getopt()
+ * before dropping privileges it makes sense to keep things
+ * as simple (and bug-free) as possible.
+ */
+ return (getopt_internal(nargc, nargv, options, NULL, NULL, 0));
+ }
+ #endif /* REPLACE_GETOPT */
+
+ /*
+ * getopt_long --
+ * Parse argc/argv argument vector.
+ */
+ int
+ getopt_long(int nargc, char * const *nargv, const char *options,
+ const struct option *long_options, int *idx)
+ {
+
+ return (getopt_internal(nargc, nargv, options, long_options, idx,
+ FLAG_PERMUTE));
+ }
+
+ /*
+ * getopt_long_only --
+ * Parse argc/argv argument vector.
+ */
+ int
+ getopt_long_only(int nargc, char * const *nargv, const char *options,
+ const struct option *long_options, int *idx)
+ {
+
+ return (getopt_internal(nargc, nargv, options, long_options, idx,
+ FLAG_PERMUTE|FLAG_LONGONLY));
+ }
+
+#endif // defined _MSC_VER || defined __MINGW32__ \ No newline at end of file
diff --git a/mesalib/src/glsl/glcpp/glcpp.c b/mesalib/src/glsl/glcpp/glcpp.c
index 564194caa..62065481c 100644
--- a/mesalib/src/glsl/glcpp/glcpp.c
+++ b/mesalib/src/glsl/glcpp/glcpp.c
@@ -31,6 +31,14 @@
#include "main/mtypes.h"
#include "main/shaderobj.h"
+#ifdef _MSC_VER
+#include <io.h>
+#define STDIN_FILENO 0
+#define read _read
+#define open _open
+#define close _close
+#endif
+
extern int yydebug;
void
diff --git a/mesalib/src/glsl/glsl_parser_extras.cpp b/mesalib/src/glsl/glsl_parser_extras.cpp
index d7a37aef4..81065640e 100644
--- a/mesalib/src/glsl/glsl_parser_extras.cpp
+++ b/mesalib/src/glsl/glsl_parser_extras.cpp
@@ -1,826 +1,826 @@
-/*
- * Copyright © 2008, 2009 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-#include <stdio.h>
-#include <stdarg.h>
-#include <string.h>
-#include <assert.h>
-
-extern "C" {
-#include "main/core.h" /* for struct gl_context */
-}
-
-#include "ralloc.h"
-#include "ast.h"
-#include "glsl_parser_extras.h"
-#include "glsl_parser.h"
-#include "ir_optimization.h"
-#include "loop_analysis.h"
-
-_mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *ctx,
- GLenum target, void *mem_ctx)
-{
- switch (target) {
- case GL_VERTEX_SHADER: this->target = vertex_shader; break;
- case GL_FRAGMENT_SHADER: this->target = fragment_shader; break;
- case GL_GEOMETRY_SHADER: this->target = geometry_shader; break;
- }
-
- this->scanner = NULL;
- this->translation_unit.make_empty();
- this->symbols = new(mem_ctx) glsl_symbol_table;
- this->info_log = ralloc_strdup(mem_ctx, "");
- this->error = false;
- this->loop_or_switch_nesting = NULL;
-
- /* Set default language version and extensions */
- this->language_version = 110;
- this->es_shader = false;
- this->ARB_texture_rectangle_enable = true;
-
- /* OpenGL ES 2.0 has different defaults from desktop GL. */
- if (ctx->API == API_OPENGLES2) {
- this->language_version = 100;
- this->es_shader = true;
- this->ARB_texture_rectangle_enable = false;
- }
-
- this->extensions = &ctx->Extensions;
-
- this->Const.MaxLights = ctx->Const.MaxLights;
- this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
- this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
- this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
- this->Const.MaxVertexAttribs = ctx->Const.VertexProgram.MaxAttribs;
- this->Const.MaxVertexUniformComponents = ctx->Const.VertexProgram.MaxUniformComponents;
- this->Const.MaxVaryingFloats = ctx->Const.MaxVarying * 4;
- this->Const.MaxVertexTextureImageUnits = ctx->Const.MaxVertexTextureImageUnits;
- this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
- this->Const.MaxTextureImageUnits = ctx->Const.MaxTextureImageUnits;
- this->Const.MaxFragmentUniformComponents = ctx->Const.FragmentProgram.MaxUniformComponents;
-
- this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
-
- /* Note: Once the OpenGL 3.0 'forward compatible' context or the OpenGL 3.2
- * Core context is supported, this logic will need change. Older versions of
- * GLSL are no longer supported outside the compatibility contexts of 3.x.
- */
- this->Const.GLSL_100ES = (ctx->API == API_OPENGLES2)
- || ctx->Extensions.ARB_ES2_compatibility;
- this->Const.GLSL_110 = (ctx->API == API_OPENGL);
- this->Const.GLSL_120 = (ctx->API == API_OPENGL)
- && (ctx->Const.GLSLVersion >= 120);
- this->Const.GLSL_130 = (ctx->API == API_OPENGL)
- && (ctx->Const.GLSLVersion >= 130);
-
- const unsigned lowest_version =
- (ctx->API == API_OPENGLES2) || ctx->Extensions.ARB_ES2_compatibility
- ? 100 : 110;
- const unsigned highest_version =
- (ctx->API == API_OPENGL) ? ctx->Const.GLSLVersion : 100;
- char *supported = ralloc_strdup(this, "");
-
- for (unsigned ver = lowest_version; ver <= highest_version; ver += 10) {
- const char *const prefix = (ver == lowest_version)
- ? ""
- : ((ver == highest_version) ? ", and " : ", ");
-
- ralloc_asprintf_append(& supported, "%s%d.%02d%s",
- prefix,
- ver / 100, ver % 100,
- (ver == 100) ? " ES" : "");
- }
-
- this->supported_version_string = supported;
-}
-
-const char *
-_mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target)
-{
- switch (target) {
- case vertex_shader: return "vertex";
- case fragment_shader: return "fragment";
- case geometry_shader: return "geometry";
- }
-
- assert(!"Should not get here.");
- return "unknown";
-}
-
-
-void
-_mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
- const char *fmt, ...)
-{
- va_list ap;
-
- state->error = true;
-
- assert(state->info_log != NULL);
- ralloc_asprintf_append(&state->info_log, "%u:%u(%u): error: ",
- locp->source,
- locp->first_line,
- locp->first_column);
- va_start(ap, fmt);
- ralloc_vasprintf_append(&state->info_log, fmt, ap);
- va_end(ap);
- ralloc_strcat(&state->info_log, "\n");
-}
-
-
-void
-_mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
- const char *fmt, ...)
-{
- va_list ap;
-
- assert(state->info_log != NULL);
- ralloc_asprintf_append(&state->info_log, "%u:%u(%u): warning: ",
- locp->source,
- locp->first_line,
- locp->first_column);
- va_start(ap, fmt);
- ralloc_vasprintf_append(&state->info_log, fmt, ap);
- va_end(ap);
- ralloc_strcat(&state->info_log, "\n");
-}
-
-
-bool
-_mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
- const char *behavior, YYLTYPE *behavior_locp,
- _mesa_glsl_parse_state *state)
-{
- enum {
- extension_disable,
- extension_enable,
- extension_require,
- extension_warn
- } ext_mode;
-
- if (strcmp(behavior, "warn") == 0) {
- ext_mode = extension_warn;
- } else if (strcmp(behavior, "require") == 0) {
- ext_mode = extension_require;
- } else if (strcmp(behavior, "enable") == 0) {
- ext_mode = extension_enable;
- } else if (strcmp(behavior, "disable") == 0) {
- ext_mode = extension_disable;
- } else {
- _mesa_glsl_error(behavior_locp, state,
- "Unknown extension behavior `%s'",
- behavior);
- return false;
- }
-
- bool unsupported = false;
-
- if (strcmp(name, "all") == 0) {
- if ((ext_mode == extension_enable) || (ext_mode == extension_require)) {
- _mesa_glsl_error(name_locp, state, "Cannot %s all extensions",
- (ext_mode == extension_enable)
- ? "enable" : "require");
- return false;
- }
- } else if (strcmp(name, "GL_ARB_draw_buffers") == 0) {
- /* This extension is only supported in fragment shaders.
- */
- if (state->target != fragment_shader) {
- unsupported = true;
- } else {
- state->ARB_draw_buffers_enable = (ext_mode != extension_disable);
- state->ARB_draw_buffers_warn = (ext_mode == extension_warn);
- }
- } else if (strcmp(name, "GL_ARB_draw_instanced") == 0) {
- /* This extension is only supported in vertex shaders.
- */
- if (state->target != vertex_shader) {
- unsupported = true;
- } else {
- state->ARB_draw_instanced_enable = (ext_mode != extension_disable);
- state->ARB_draw_instanced_warn = (ext_mode == extension_warn);
- }
- } else if (strcmp(name, "GL_ARB_explicit_attrib_location") == 0) {
- state->ARB_explicit_attrib_location_enable =
- (ext_mode != extension_disable);
- state->ARB_explicit_attrib_location_warn =
- (ext_mode == extension_warn);
-
- unsupported = !state->extensions->ARB_explicit_attrib_location;
- } else if (strcmp(name, "GL_ARB_fragment_coord_conventions") == 0) {
- state->ARB_fragment_coord_conventions_enable =
- (ext_mode != extension_disable);
- state->ARB_fragment_coord_conventions_warn =
- (ext_mode == extension_warn);
-
- unsupported = !state->extensions->ARB_fragment_coord_conventions;
- } else if (strcmp(name, "GL_ARB_texture_rectangle") == 0) {
- state->ARB_texture_rectangle_enable = (ext_mode != extension_disable);
- state->ARB_texture_rectangle_warn = (ext_mode == extension_warn);
- } else if (strcmp(name, "GL_EXT_texture_array") == 0) {
- state->EXT_texture_array_enable = (ext_mode != extension_disable);
- state->EXT_texture_array_warn = (ext_mode == extension_warn);
-
- unsupported = !state->extensions->EXT_texture_array;
- } else if (strcmp(name, "GL_ARB_shader_stencil_export") == 0) {
- if (state->target != fragment_shader) {
- unsupported = true;
- } else {
- state->ARB_shader_stencil_export_enable = (ext_mode != extension_disable);
- state->ARB_shader_stencil_export_warn = (ext_mode == extension_warn);
- unsupported = !state->extensions->ARB_shader_stencil_export;
- }
- } else if (strcmp(name, "GL_AMD_conservative_depth") == 0) {
- /* The AMD_conservative spec does not forbid requiring the extension in
- * the vertex shader.
- */
- state->AMD_conservative_depth_enable = (ext_mode != extension_disable);
- state->AMD_conservative_depth_warn = (ext_mode == extension_warn);
- unsupported = !state->extensions->AMD_conservative_depth;
- } else {
- unsupported = true;
- }
-
- if (unsupported) {
- static const char *const fmt = "extension `%s' unsupported in %s shader";
-
- if (ext_mode == extension_require) {
- _mesa_glsl_error(name_locp, state, fmt,
- name, _mesa_glsl_shader_target_name(state->target));
- return false;
- } else {
- _mesa_glsl_warning(name_locp, state, fmt,
- name, _mesa_glsl_shader_target_name(state->target));
- }
- }
-
- return true;
-}
-
-void
-_mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
-{
- if (q->flags.q.constant)
- printf("const ");
-
- if (q->flags.q.invariant)
- printf("invariant ");
-
- if (q->flags.q.attribute)
- printf("attribute ");
-
- if (q->flags.q.varying)
- printf("varying ");
-
- if (q->flags.q.in && q->flags.q.out)
- printf("inout ");
- else {
- if (q->flags.q.in)
- printf("in ");
-
- if (q->flags.q.out)
- printf("out ");
- }
-
- if (q->flags.q.centroid)
- printf("centroid ");
- if (q->flags.q.uniform)
- printf("uniform ");
- if (q->flags.q.smooth)
- printf("smooth ");
- if (q->flags.q.flat)
- printf("flat ");
- if (q->flags.q.noperspective)
- printf("noperspective ");
-}
-
-
-void
-ast_node::print(void) const
-{
- printf("unhandled node ");
-}
-
-
-ast_node::ast_node(void)
-{
- this->location.source = 0;
- this->location.line = 0;
- this->location.column = 0;
-}
-
-
-static void
-ast_opt_array_size_print(bool is_array, const ast_expression *array_size)
-{
- if (is_array) {
- printf("[ ");
-
- if (array_size)
- array_size->print();
-
- printf("] ");
- }
-}
-
-
-void
-ast_compound_statement::print(void) const
-{
- printf("{\n");
-
- foreach_list_const(n, &this->statements) {
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
-
- printf("}\n");
-}
-
-
-ast_compound_statement::ast_compound_statement(int new_scope,
- ast_node *statements)
-{
- this->new_scope = new_scope;
-
- if (statements != NULL) {
- this->statements.push_degenerate_list_at_head(&statements->link);
- }
-}
-
-
-void
-ast_expression::print(void) const
-{
- switch (oper) {
- case ast_assign:
- case ast_mul_assign:
- case ast_div_assign:
- case ast_mod_assign:
- case ast_add_assign:
- case ast_sub_assign:
- case ast_ls_assign:
- case ast_rs_assign:
- case ast_and_assign:
- case ast_xor_assign:
- case ast_or_assign:
- subexpressions[0]->print();
- printf("%s ", operator_string(oper));
- subexpressions[1]->print();
- break;
-
- case ast_field_selection:
- subexpressions[0]->print();
- printf(". %s ", primary_expression.identifier);
- break;
-
- case ast_plus:
- case ast_neg:
- case ast_bit_not:
- case ast_logic_not:
- case ast_pre_inc:
- case ast_pre_dec:
- printf("%s ", operator_string(oper));
- subexpressions[0]->print();
- break;
-
- case ast_post_inc:
- case ast_post_dec:
- subexpressions[0]->print();
- printf("%s ", operator_string(oper));
- break;
-
- case ast_conditional:
- subexpressions[0]->print();
- printf("? ");
- subexpressions[1]->print();
- printf(": ");
- subexpressions[1]->print();
- break;
-
- case ast_array_index:
- subexpressions[0]->print();
- printf("[ ");
- subexpressions[1]->print();
- printf("] ");
- break;
-
- case ast_function_call: {
- subexpressions[0]->print();
- printf("( ");
-
- foreach_list_const (n, &this->expressions) {
- if (n != this->expressions.get_head())
- printf(", ");
-
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
-
- printf(") ");
- break;
- }
-
- case ast_identifier:
- printf("%s ", primary_expression.identifier);
- break;
-
- case ast_int_constant:
- printf("%d ", primary_expression.int_constant);
- break;
-
- case ast_uint_constant:
- printf("%u ", primary_expression.uint_constant);
- break;
-
- case ast_float_constant:
- printf("%f ", primary_expression.float_constant);
- break;
-
- case ast_bool_constant:
- printf("%s ",
- primary_expression.bool_constant
- ? "true" : "false");
- break;
-
- case ast_sequence: {
- printf("( ");
- foreach_list_const(n, & this->expressions) {
- if (n != this->expressions.get_head())
- printf(", ");
-
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
- printf(") ");
- break;
- }
-
- default:
- assert(0);
- break;
- }
-}
-
-ast_expression::ast_expression(int oper,
- ast_expression *ex0,
- ast_expression *ex1,
- ast_expression *ex2)
-{
- this->oper = ast_operators(oper);
- this->subexpressions[0] = ex0;
- this->subexpressions[1] = ex1;
- this->subexpressions[2] = ex2;
-}
-
-
-void
-ast_expression_statement::print(void) const
-{
- if (expression)
- expression->print();
-
- printf("; ");
-}
-
-
-ast_expression_statement::ast_expression_statement(ast_expression *ex) :
- expression(ex)
-{
- /* empty */
-}
-
-
-void
-ast_function::print(void) const
-{
- return_type->print();
- printf(" %s (", identifier);
-
- foreach_list_const(n, & this->parameters) {
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
-
- printf(")");
-}
-
-
-ast_function::ast_function(void)
- : is_definition(false), signature(NULL)
-{
- /* empty */
-}
-
-
-void
-ast_fully_specified_type::print(void) const
-{
- _mesa_ast_type_qualifier_print(& qualifier);
- specifier->print();
-}
-
-
-void
-ast_parameter_declarator::print(void) const
-{
- type->print();
- if (identifier)
- printf("%s ", identifier);
- ast_opt_array_size_print(is_array, array_size);
-}
-
-
-void
-ast_function_definition::print(void) const
-{
- prototype->print();
- body->print();
-}
-
-
-void
-ast_declaration::print(void) const
-{
- printf("%s ", identifier);
- ast_opt_array_size_print(is_array, array_size);
-
- if (initializer) {
- printf("= ");
- initializer->print();
- }
-}
-
-
-ast_declaration::ast_declaration(char *identifier, int is_array,
- ast_expression *array_size,
- ast_expression *initializer)
-{
- this->identifier = identifier;
- this->is_array = is_array;
- this->array_size = array_size;
- this->initializer = initializer;
-}
-
-
-void
-ast_declarator_list::print(void) const
-{
- assert(type || invariant);
-
- if (type)
- type->print();
- else
- printf("invariant ");
-
- foreach_list_const (ptr, & this->declarations) {
- if (ptr != this->declarations.get_head())
- printf(", ");
-
- ast_node *ast = exec_node_data(ast_node, ptr, link);
- ast->print();
- }
-
- printf("; ");
-}
-
-
-ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
-{
- this->type = type;
- this->invariant = false;
-}
-
-void
-ast_jump_statement::print(void) const
-{
- switch (mode) {
- case ast_continue:
- printf("continue; ");
- break;
- case ast_break:
- printf("break; ");
- break;
- case ast_return:
- printf("return ");
- if (opt_return_value)
- opt_return_value->print();
-
- printf("; ");
- break;
- case ast_discard:
- printf("discard; ");
- break;
- }
-}
-
-
-ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
-{
- this->mode = ast_jump_modes(mode);
-
- if (mode == ast_return)
- opt_return_value = return_value;
-}
-
-
-void
-ast_selection_statement::print(void) const
-{
- printf("if ( ");
- condition->print();
- printf(") ");
-
- then_statement->print();
-
- if (else_statement) {
- printf("else ");
- else_statement->print();
- }
-
-}
-
-
-ast_selection_statement::ast_selection_statement(ast_expression *condition,
- ast_node *then_statement,
- ast_node *else_statement)
-{
- this->condition = condition;
- this->then_statement = then_statement;
- this->else_statement = else_statement;
-}
-
-
-void
-ast_iteration_statement::print(void) const
-{
- switch (mode) {
- case ast_for:
- printf("for( ");
- if (init_statement)
- init_statement->print();
- printf("; ");
-
- if (condition)
- condition->print();
- printf("; ");
-
- if (rest_expression)
- rest_expression->print();
- printf(") ");
-
- body->print();
- break;
-
- case ast_while:
- printf("while ( ");
- if (condition)
- condition->print();
- printf(") ");
- body->print();
- break;
-
- case ast_do_while:
- printf("do ");
- body->print();
- printf("while ( ");
- if (condition)
- condition->print();
- printf("); ");
- break;
- }
-}
-
-
-ast_iteration_statement::ast_iteration_statement(int mode,
- ast_node *init,
- ast_node *condition,
- ast_expression *rest_expression,
- ast_node *body)
-{
- this->mode = ast_iteration_modes(mode);
- this->init_statement = init;
- this->condition = condition;
- this->rest_expression = rest_expression;
- this->body = body;
-}
-
-
-void
-ast_struct_specifier::print(void) const
-{
- printf("struct %s { ", name);
- foreach_list_const(n, &this->declarations) {
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
- printf("} ");
-}
-
-
-ast_struct_specifier::ast_struct_specifier(char *identifier,
- ast_node *declarator_list)
-{
- if (identifier == NULL) {
- static unsigned anon_count = 1;
- identifier = ralloc_asprintf(this, "#anon_struct_%04x", anon_count);
- anon_count++;
- }
- name = identifier;
- this->declarations.push_degenerate_list_at_head(&declarator_list->link);
-}
-
-bool
-do_common_optimization(exec_list *ir, bool linked, unsigned max_unroll_iterations)
-{
- GLboolean progress = GL_FALSE;
-
- progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
-
- if (linked) {
- progress = do_function_inlining(ir) || progress;
- progress = do_dead_functions(ir) || progress;
- }
- progress = do_structure_splitting(ir) || progress;
- progress = do_if_simplification(ir) || progress;
- progress = do_discard_simplification(ir) || progress;
- progress = do_copy_propagation(ir) || progress;
- /*progress = do_copy_propagation_elements(ir) || progress;*/
- if (linked)
- progress = do_dead_code(ir) || progress;
- else
- progress = do_dead_code_unlinked(ir) || progress;
- progress = do_dead_code_local(ir) || progress;
- progress = do_tree_grafting(ir) || progress;
- progress = do_constant_propagation(ir) || progress;
- if (linked)
- progress = do_constant_variable(ir) || progress;
- else
- progress = do_constant_variable_unlinked(ir) || progress;
- progress = do_constant_folding(ir) || progress;
- progress = do_algebraic(ir) || progress;
- progress = do_lower_jumps(ir) || progress;
- progress = do_vec_index_to_swizzle(ir) || progress;
- progress = do_swizzle_swizzle(ir) || progress;
- progress = do_noop_swizzle(ir) || progress;
-
- progress = optimize_redundant_jumps(ir) || progress;
-
- loop_state *ls = analyze_loop_variables(ir);
- if (ls->loop_found) {
- progress = set_loop_controls(ir, ls) || progress;
- progress = unroll_loops(ir, ls, max_unroll_iterations) || progress;
- }
- delete ls;
-
- return progress;
-}
-
-extern "C" {
-
-/**
- * To be called at GL teardown time, this frees compiler datastructures.
- *
- * After calling this, any previously compiled shaders and shader
- * programs would be invalid. So this should happen at approximately
- * program exit.
- */
-void
-_mesa_destroy_shader_compiler(void)
-{
- _mesa_destroy_shader_compiler_caches();
-
- _mesa_glsl_release_types();
-}
-
-/**
- * Releases compiler caches to trade off performance for memory.
- *
- * Intended to be used with glReleaseShaderCompiler().
- */
-void
-_mesa_destroy_shader_compiler_caches(void)
-{
- _mesa_glsl_release_functions();
-}
-
-}
+/*
+ * Copyright © 2008, 2009 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <assert.h>
+
+extern "C" {
+#include "main/core.h" /* for struct gl_context */
+}
+
+#include "ralloc.h"
+#include "ast.h"
+#include "glsl_parser_extras.h"
+#include "glsl_parser.h"
+#include "ir_optimization.h"
+#include "loop_analysis.h"
+
+_mesa_glsl_parse_state::_mesa_glsl_parse_state(struct gl_context *ctx,
+ GLenum target, void *mem_ctx)
+{
+ switch (target) {
+ case GL_VERTEX_SHADER: this->target = vertex_shader; break;
+ case GL_FRAGMENT_SHADER: this->target = fragment_shader; break;
+ case GL_GEOMETRY_SHADER: this->target = geometry_shader; break;
+ }
+
+ this->scanner = NULL;
+ this->translation_unit.make_empty();
+ this->symbols = new(mem_ctx) glsl_symbol_table;
+ this->info_log = ralloc_strdup(mem_ctx, "");
+ this->error = false;
+ this->loop_or_switch_nesting = NULL;
+
+ /* Set default language version and extensions */
+ this->language_version = 110;
+ this->es_shader = false;
+ this->ARB_texture_rectangle_enable = true;
+
+ /* OpenGL ES 2.0 has different defaults from desktop GL. */
+ if (ctx->API == API_OPENGLES2) {
+ this->language_version = 100;
+ this->es_shader = true;
+ this->ARB_texture_rectangle_enable = false;
+ }
+
+ this->extensions = &ctx->Extensions;
+
+ this->Const.MaxLights = ctx->Const.MaxLights;
+ this->Const.MaxClipPlanes = ctx->Const.MaxClipPlanes;
+ this->Const.MaxTextureUnits = ctx->Const.MaxTextureUnits;
+ this->Const.MaxTextureCoords = ctx->Const.MaxTextureCoordUnits;
+ this->Const.MaxVertexAttribs = ctx->Const.VertexProgram.MaxAttribs;
+ this->Const.MaxVertexUniformComponents = ctx->Const.VertexProgram.MaxUniformComponents;
+ this->Const.MaxVaryingFloats = ctx->Const.MaxVarying * 4;
+ this->Const.MaxVertexTextureImageUnits = ctx->Const.MaxVertexTextureImageUnits;
+ this->Const.MaxCombinedTextureImageUnits = ctx->Const.MaxCombinedTextureImageUnits;
+ this->Const.MaxTextureImageUnits = ctx->Const.MaxTextureImageUnits;
+ this->Const.MaxFragmentUniformComponents = ctx->Const.FragmentProgram.MaxUniformComponents;
+
+ this->Const.MaxDrawBuffers = ctx->Const.MaxDrawBuffers;
+
+ /* Note: Once the OpenGL 3.0 'forward compatible' context or the OpenGL 3.2
+ * Core context is supported, this logic will need change. Older versions of
+ * GLSL are no longer supported outside the compatibility contexts of 3.x.
+ */
+ this->Const.GLSL_100ES = (ctx->API == API_OPENGLES2)
+ || ctx->Extensions.ARB_ES2_compatibility;
+ this->Const.GLSL_110 = (ctx->API == API_OPENGL);
+ this->Const.GLSL_120 = (ctx->API == API_OPENGL)
+ && (ctx->Const.GLSLVersion >= 120);
+ this->Const.GLSL_130 = (ctx->API == API_OPENGL)
+ && (ctx->Const.GLSLVersion >= 130);
+
+ const unsigned lowest_version =
+ (ctx->API == API_OPENGLES2) || ctx->Extensions.ARB_ES2_compatibility
+ ? 100 : 110;
+ const unsigned highest_version =
+ (ctx->API == API_OPENGL) ? ctx->Const.GLSLVersion : 100;
+ char *supported = ralloc_strdup(this, "");
+
+ for (unsigned ver = lowest_version; ver <= highest_version; ver += 10) {
+ const char *const prefix = (ver == lowest_version)
+ ? ""
+ : ((ver == highest_version) ? ", and " : ", ");
+
+ ralloc_asprintf_append(& supported, "%s%d.%02d%s",
+ prefix,
+ ver / 100, ver % 100,
+ (ver == 100) ? " ES" : "");
+ }
+
+ this->supported_version_string = supported;
+}
+
+const char *
+_mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target)
+{
+ switch (target) {
+ case vertex_shader: return "vertex";
+ case fragment_shader: return "fragment";
+ case geometry_shader: return "geometry";
+ }
+
+ assert(!"Should not get here.");
+ return "unknown";
+}
+
+
+void
+_mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
+ const char *fmt, ...)
+{
+ va_list ap;
+
+ state->error = true;
+
+ assert(state->info_log != NULL);
+ ralloc_asprintf_append(&state->info_log, "%u:%u(%u): error: ",
+ locp->source,
+ locp->first_line,
+ locp->first_column);
+ va_start(ap, fmt);
+ ralloc_vasprintf_append(&state->info_log, fmt, ap);
+ va_end(ap);
+ ralloc_strcat(&state->info_log, "\n");
+}
+
+
+void
+_mesa_glsl_warning(const YYLTYPE *locp, _mesa_glsl_parse_state *state,
+ const char *fmt, ...)
+{
+ va_list ap;
+
+ assert(state->info_log != NULL);
+ ralloc_asprintf_append(&state->info_log, "%u:%u(%u): warning: ",
+ locp->source,
+ locp->first_line,
+ locp->first_column);
+ va_start(ap, fmt);
+ ralloc_vasprintf_append(&state->info_log, fmt, ap);
+ va_end(ap);
+ ralloc_strcat(&state->info_log, "\n");
+}
+
+
+bool
+_mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
+ const char *behavior, YYLTYPE *behavior_locp,
+ _mesa_glsl_parse_state *state)
+{
+ enum {
+ extension_disable,
+ extension_enable,
+ extension_require,
+ extension_warn
+ } ext_mode;
+
+ if (strcmp(behavior, "warn") == 0) {
+ ext_mode = extension_warn;
+ } else if (strcmp(behavior, "require") == 0) {
+ ext_mode = extension_require;
+ } else if (strcmp(behavior, "enable") == 0) {
+ ext_mode = extension_enable;
+ } else if (strcmp(behavior, "disable") == 0) {
+ ext_mode = extension_disable;
+ } else {
+ _mesa_glsl_error(behavior_locp, state,
+ "Unknown extension behavior `%s'",
+ behavior);
+ return false;
+ }
+
+ bool unsupported = false;
+
+ if (strcmp(name, "all") == 0) {
+ if ((ext_mode == extension_enable) || (ext_mode == extension_require)) {
+ _mesa_glsl_error(name_locp, state, "Cannot %s all extensions",
+ (ext_mode == extension_enable)
+ ? "enable" : "require");
+ return false;
+ }
+ } else if (strcmp(name, "GL_ARB_draw_buffers") == 0) {
+ /* This extension is only supported in fragment shaders.
+ */
+ if (state->target != fragment_shader) {
+ unsupported = true;
+ } else {
+ state->ARB_draw_buffers_enable = (ext_mode != extension_disable);
+ state->ARB_draw_buffers_warn = (ext_mode == extension_warn);
+ }
+ } else if (strcmp(name, "GL_ARB_draw_instanced") == 0) {
+ /* This extension is only supported in vertex shaders.
+ */
+ if (state->target != vertex_shader) {
+ unsupported = true;
+ } else {
+ state->ARB_draw_instanced_enable = (ext_mode != extension_disable);
+ state->ARB_draw_instanced_warn = (ext_mode == extension_warn);
+ }
+ } else if (strcmp(name, "GL_ARB_explicit_attrib_location") == 0) {
+ state->ARB_explicit_attrib_location_enable =
+ (ext_mode != extension_disable);
+ state->ARB_explicit_attrib_location_warn =
+ (ext_mode == extension_warn);
+
+ unsupported = !state->extensions->ARB_explicit_attrib_location;
+ } else if (strcmp(name, "GL_ARB_fragment_coord_conventions") == 0) {
+ state->ARB_fragment_coord_conventions_enable =
+ (ext_mode != extension_disable);
+ state->ARB_fragment_coord_conventions_warn =
+ (ext_mode == extension_warn);
+
+ unsupported = !state->extensions->ARB_fragment_coord_conventions;
+ } else if (strcmp(name, "GL_ARB_texture_rectangle") == 0) {
+ state->ARB_texture_rectangle_enable = (ext_mode != extension_disable);
+ state->ARB_texture_rectangle_warn = (ext_mode == extension_warn);
+ } else if (strcmp(name, "GL_EXT_texture_array") == 0) {
+ state->EXT_texture_array_enable = (ext_mode != extension_disable);
+ state->EXT_texture_array_warn = (ext_mode == extension_warn);
+
+ unsupported = !state->extensions->EXT_texture_array;
+ } else if (strcmp(name, "GL_ARB_shader_stencil_export") == 0) {
+ if (state->target != fragment_shader) {
+ unsupported = true;
+ } else {
+ state->ARB_shader_stencil_export_enable = (ext_mode != extension_disable);
+ state->ARB_shader_stencil_export_warn = (ext_mode == extension_warn);
+ unsupported = !state->extensions->ARB_shader_stencil_export;
+ }
+ } else if (strcmp(name, "GL_AMD_conservative_depth") == 0) {
+ /* The AMD_conservative spec does not forbid requiring the extension in
+ * the vertex shader.
+ */
+ state->AMD_conservative_depth_enable = (ext_mode != extension_disable);
+ state->AMD_conservative_depth_warn = (ext_mode == extension_warn);
+ unsupported = !state->extensions->AMD_conservative_depth;
+ } else {
+ unsupported = true;
+ }
+
+ if (unsupported) {
+ static const char *const fmt = "extension `%s' unsupported in %s shader";
+
+ if (ext_mode == extension_require) {
+ _mesa_glsl_error(name_locp, state, fmt,
+ name, _mesa_glsl_shader_target_name(state->target));
+ return false;
+ } else {
+ _mesa_glsl_warning(name_locp, state, fmt,
+ name, _mesa_glsl_shader_target_name(state->target));
+ }
+ }
+
+ return true;
+}
+
+void
+_mesa_ast_type_qualifier_print(const struct ast_type_qualifier *q)
+{
+ if (q->flags.q.constant)
+ printf("const ");
+
+ if (q->flags.q.invariant)
+ printf("invariant ");
+
+ if (q->flags.q.attribute)
+ printf("attribute ");
+
+ if (q->flags.q.varying)
+ printf("varying ");
+
+ if (q->flags.q.in && q->flags.q.out)
+ printf("inout ");
+ else {
+ if (q->flags.q.in)
+ printf("in ");
+
+ if (q->flags.q.out)
+ printf("out ");
+ }
+
+ if (q->flags.q.centroid)
+ printf("centroid ");
+ if (q->flags.q.uniform)
+ printf("uniform ");
+ if (q->flags.q.smooth)
+ printf("smooth ");
+ if (q->flags.q.flat)
+ printf("flat ");
+ if (q->flags.q.noperspective)
+ printf("noperspective ");
+}
+
+
+void
+ast_node::print(void) const
+{
+ printf("unhandled node ");
+}
+
+
+ast_node::ast_node(void)
+{
+ this->location.source = 0;
+ this->location.line = 0;
+ this->location.column = 0;
+}
+
+
+static void
+ast_opt_array_size_print(bool is_array, const ast_expression *array_size)
+{
+ if (is_array) {
+ printf("[ ");
+
+ if (array_size)
+ array_size->print();
+
+ printf("] ");
+ }
+}
+
+
+void
+ast_compound_statement::print(void) const
+{
+ printf("{\n");
+
+ foreach_list_const(n, &this->statements) {
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+
+ printf("}\n");
+}
+
+
+ast_compound_statement::ast_compound_statement(int new_scope,
+ ast_node *statements)
+{
+ this->new_scope = new_scope;
+
+ if (statements != NULL) {
+ this->statements.push_degenerate_list_at_head(&statements->link);
+ }
+}
+
+
+void
+ast_expression::print(void) const
+{
+ switch (oper) {
+ case ast_assign:
+ case ast_mul_assign:
+ case ast_div_assign:
+ case ast_mod_assign:
+ case ast_add_assign:
+ case ast_sub_assign:
+ case ast_ls_assign:
+ case ast_rs_assign:
+ case ast_and_assign:
+ case ast_xor_assign:
+ case ast_or_assign:
+ subexpressions[0]->print();
+ printf("%s ", operator_string(oper));
+ subexpressions[1]->print();
+ break;
+
+ case ast_field_selection:
+ subexpressions[0]->print();
+ printf(". %s ", primary_expression.identifier);
+ break;
+
+ case ast_plus:
+ case ast_neg:
+ case ast_bit_not:
+ case ast_logic_not:
+ case ast_pre_inc:
+ case ast_pre_dec:
+ printf("%s ", operator_string(oper));
+ subexpressions[0]->print();
+ break;
+
+ case ast_post_inc:
+ case ast_post_dec:
+ subexpressions[0]->print();
+ printf("%s ", operator_string(oper));
+ break;
+
+ case ast_conditional:
+ subexpressions[0]->print();
+ printf("? ");
+ subexpressions[1]->print();
+ printf(": ");
+ subexpressions[1]->print();
+ break;
+
+ case ast_array_index:
+ subexpressions[0]->print();
+ printf("[ ");
+ subexpressions[1]->print();
+ printf("] ");
+ break;
+
+ case ast_function_call: {
+ subexpressions[0]->print();
+ printf("( ");
+
+ foreach_list_const (n, &this->expressions) {
+ if (n != this->expressions.get_head())
+ printf(", ");
+
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+
+ printf(") ");
+ break;
+ }
+
+ case ast_identifier:
+ printf("%s ", primary_expression.identifier);
+ break;
+
+ case ast_int_constant:
+ printf("%d ", primary_expression.int_constant);
+ break;
+
+ case ast_uint_constant:
+ printf("%u ", primary_expression.uint_constant);
+ break;
+
+ case ast_float_constant:
+ printf("%f ", primary_expression.float_constant);
+ break;
+
+ case ast_bool_constant:
+ printf("%s ",
+ primary_expression.bool_constant
+ ? "true" : "false");
+ break;
+
+ case ast_sequence: {
+ printf("( ");
+ foreach_list_const(n, & this->expressions) {
+ if (n != this->expressions.get_head())
+ printf(", ");
+
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+ printf(") ");
+ break;
+ }
+
+ default:
+ assert(0);
+ break;
+ }
+}
+
+ast_expression::ast_expression(int oper,
+ ast_expression *ex0,
+ ast_expression *ex1,
+ ast_expression *ex2)
+{
+ this->oper = ast_operators(oper);
+ this->subexpressions[0] = ex0;
+ this->subexpressions[1] = ex1;
+ this->subexpressions[2] = ex2;
+}
+
+
+void
+ast_expression_statement::print(void) const
+{
+ if (expression)
+ expression->print();
+
+ printf("; ");
+}
+
+
+ast_expression_statement::ast_expression_statement(ast_expression *ex) :
+ expression(ex)
+{
+ /* empty */
+}
+
+
+void
+ast_function::print(void) const
+{
+ return_type->print();
+ printf(" %s (", identifier);
+
+ foreach_list_const(n, & this->parameters) {
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+
+ printf(")");
+}
+
+
+ast_function::ast_function(void)
+ : is_definition(false), signature(NULL)
+{
+ /* empty */
+}
+
+
+void
+ast_fully_specified_type::print(void) const
+{
+ _mesa_ast_type_qualifier_print(& qualifier);
+ specifier->print();
+}
+
+
+void
+ast_parameter_declarator::print(void) const
+{
+ type->print();
+ if (identifier)
+ printf("%s ", identifier);
+ ast_opt_array_size_print(is_array, array_size);
+}
+
+
+void
+ast_function_definition::print(void) const
+{
+ prototype->print();
+ body->print();
+}
+
+
+void
+ast_declaration::print(void) const
+{
+ printf("%s ", identifier);
+ ast_opt_array_size_print(is_array, array_size);
+
+ if (initializer) {
+ printf("= ");
+ initializer->print();
+ }
+}
+
+
+ast_declaration::ast_declaration(char *identifier, int is_array,
+ ast_expression *array_size,
+ ast_expression *initializer)
+{
+ this->identifier = identifier;
+ this->is_array = is_array;
+ this->array_size = array_size;
+ this->initializer = initializer;
+}
+
+
+void
+ast_declarator_list::print(void) const
+{
+ assert(type || invariant);
+
+ if (type)
+ type->print();
+ else
+ printf("invariant ");
+
+ foreach_list_const (ptr, & this->declarations) {
+ if (ptr != this->declarations.get_head())
+ printf(", ");
+
+ ast_node *ast = exec_node_data(ast_node, ptr, link);
+ ast->print();
+ }
+
+ printf("; ");
+}
+
+
+ast_declarator_list::ast_declarator_list(ast_fully_specified_type *type)
+{
+ this->type = type;
+ this->invariant = false;
+}
+
+void
+ast_jump_statement::print(void) const
+{
+ switch (mode) {
+ case ast_continue:
+ printf("continue; ");
+ break;
+ case ast_break:
+ printf("break; ");
+ break;
+ case ast_return:
+ printf("return ");
+ if (opt_return_value)
+ opt_return_value->print();
+
+ printf("; ");
+ break;
+ case ast_discard:
+ printf("discard; ");
+ break;
+ }
+}
+
+
+ast_jump_statement::ast_jump_statement(int mode, ast_expression *return_value)
+{
+ this->mode = ast_jump_modes(mode);
+
+ if (mode == ast_return)
+ opt_return_value = return_value;
+}
+
+
+void
+ast_selection_statement::print(void) const
+{
+ printf("if ( ");
+ condition->print();
+ printf(") ");
+
+ then_statement->print();
+
+ if (else_statement) {
+ printf("else ");
+ else_statement->print();
+ }
+
+}
+
+
+ast_selection_statement::ast_selection_statement(ast_expression *condition,
+ ast_node *then_statement,
+ ast_node *else_statement)
+{
+ this->condition = condition;
+ this->then_statement = then_statement;
+ this->else_statement = else_statement;
+}
+
+
+void
+ast_iteration_statement::print(void) const
+{
+ switch (mode) {
+ case ast_for:
+ printf("for( ");
+ if (init_statement)
+ init_statement->print();
+ printf("; ");
+
+ if (condition)
+ condition->print();
+ printf("; ");
+
+ if (rest_expression)
+ rest_expression->print();
+ printf(") ");
+
+ body->print();
+ break;
+
+ case ast_while:
+ printf("while ( ");
+ if (condition)
+ condition->print();
+ printf(") ");
+ body->print();
+ break;
+
+ case ast_do_while:
+ printf("do ");
+ body->print();
+ printf("while ( ");
+ if (condition)
+ condition->print();
+ printf("); ");
+ break;
+ }
+}
+
+
+ast_iteration_statement::ast_iteration_statement(int mode,
+ ast_node *init,
+ ast_node *condition,
+ ast_expression *rest_expression,
+ ast_node *body)
+{
+ this->mode = ast_iteration_modes(mode);
+ this->init_statement = init;
+ this->condition = condition;
+ this->rest_expression = rest_expression;
+ this->body = body;
+}
+
+
+void
+ast_struct_specifier::print(void) const
+{
+ printf("struct %s { ", name);
+ foreach_list_const(n, &this->declarations) {
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+ printf("} ");
+}
+
+
+ast_struct_specifier::ast_struct_specifier(char *identifier,
+ ast_node *declarator_list)
+{
+ if (identifier == NULL) {
+ static unsigned anon_count = 1;
+ identifier = ralloc_asprintf(this, "#anon_struct_%04x", anon_count);
+ anon_count++;
+ }
+ name = identifier;
+ this->declarations.push_degenerate_list_at_head(&declarator_list->link);
+}
+
+bool
+do_common_optimization(exec_list *ir, bool linked, unsigned max_unroll_iterations)
+{
+ GLboolean progress = GL_FALSE;
+
+ progress = lower_instructions(ir, SUB_TO_ADD_NEG) || progress;
+
+ if (linked) {
+ progress = do_function_inlining(ir) || progress;
+ progress = do_dead_functions(ir) || progress;
+ }
+ progress = do_structure_splitting(ir) || progress;
+ progress = do_if_simplification(ir) || progress;
+ progress = do_discard_simplification(ir) || progress;
+ progress = do_copy_propagation(ir) || progress;
+ /*progress = do_copy_propagation_elements(ir) || progress;*/
+ if (linked)
+ progress = do_dead_code(ir) || progress;
+ else
+ progress = do_dead_code_unlinked(ir) || progress;
+ progress = do_dead_code_local(ir) || progress;
+ progress = do_tree_grafting(ir) || progress;
+ progress = do_constant_propagation(ir) || progress;
+ if (linked)
+ progress = do_constant_variable(ir) || progress;
+ else
+ progress = do_constant_variable_unlinked(ir) || progress;
+ progress = do_constant_folding(ir) || progress;
+ progress = do_algebraic(ir) || progress;
+ progress = do_lower_jumps(ir) || progress;
+ progress = do_vec_index_to_swizzle(ir) || progress;
+ progress = do_swizzle_swizzle(ir) || progress;
+ progress = do_noop_swizzle(ir) || progress;
+
+ progress = optimize_redundant_jumps(ir) || progress;
+
+ loop_state *ls = analyze_loop_variables(ir);
+ if (ls->loop_found) {
+ progress = set_loop_controls(ir, ls) || progress;
+ progress = unroll_loops(ir, ls, max_unroll_iterations) || progress;
+ }
+ delete ls;
+
+ return progress;
+}
+
+extern "C" {
+
+/**
+ * To be called at GL teardown time, this frees compiler datastructures.
+ *
+ * After calling this, any previously compiled shaders and shader
+ * programs would be invalid. So this should happen at approximately
+ * program exit.
+ */
+void
+_mesa_destroy_shader_compiler(void)
+{
+ _mesa_destroy_shader_compiler_caches();
+
+ _mesa_glsl_release_types();
+}
+
+/**
+ * Releases compiler caches to trade off performance for memory.
+ *
+ * Intended to be used with glReleaseShaderCompiler().
+ */
+void
+_mesa_destroy_shader_compiler_caches(void)
+{
+ _mesa_glsl_release_functions();
+}
+
+}
diff --git a/mesalib/src/glsl/glsl_parser_extras.h b/mesalib/src/glsl/glsl_parser_extras.h
index 10cb673c6..0d9c78719 100644
--- a/mesalib/src/glsl/glsl_parser_extras.h
+++ b/mesalib/src/glsl/glsl_parser_extras.h
@@ -1,277 +1,281 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#pragma once
-#ifndef GLSL_PARSER_EXTRAS_H
-#define GLSL_PARSER_EXTRAS_H
-
-/*
- * Most of the definitions here only apply to C++
- */
-#ifdef __cplusplus
-
-
-#include <stdlib.h>
-#include "glsl_symbol_table.h"
-
-enum _mesa_glsl_parser_targets {
- vertex_shader,
- geometry_shader,
- fragment_shader
-};
-
-struct gl_context;
-
-struct _mesa_glsl_parse_state {
- _mesa_glsl_parse_state(struct gl_context *ctx, GLenum target,
- void *mem_ctx);
-
- /* Callers of this ralloc-based new need not call delete. It's
- * easier to just ralloc_free 'ctx' (or any of its ancestors). */
- static void* operator new(size_t size, void *ctx)
- {
- void *mem = rzalloc_size(ctx, size);
- assert(mem != NULL);
-
- return mem;
- }
-
- /* If the user *does* call delete, that's OK, we will just
- * ralloc_free in that case. */
- static void operator delete(void *mem)
- {
- ralloc_free(mem);
- }
-
- void *scanner;
- exec_list translation_unit;
- glsl_symbol_table *symbols;
-
- bool es_shader;
- unsigned language_version;
- const char *version_string;
- enum _mesa_glsl_parser_targets target;
-
- /**
- * Printable list of GLSL versions supported by the current context
- *
- * \note
- * This string should probably be generated per-context instead of per
- * invokation of the compiler. This should be changed when the method of
- * tracking supported GLSL versions changes.
- */
- const char *supported_version_string;
-
- /**
- * Implementation defined limits that affect built-in variables, etc.
- *
- * \sa struct gl_constants (in mtypes.h)
- */
- struct {
- /* 1.10 */
- unsigned MaxLights;
- unsigned MaxClipPlanes;
- unsigned MaxTextureUnits;
- unsigned MaxTextureCoords;
- unsigned MaxVertexAttribs;
- unsigned MaxVertexUniformComponents;
- unsigned MaxVaryingFloats;
- unsigned MaxVertexTextureImageUnits;
- unsigned MaxCombinedTextureImageUnits;
- unsigned MaxTextureImageUnits;
- unsigned MaxFragmentUniformComponents;
-
- /* ARB_draw_buffers */
- unsigned MaxDrawBuffers;
-
- /**
- * Set of GLSL versions supported by the current context
- *
- * Knowing that version X is supported doesn't mean that versions before
- * X are also supported. Version 1.00 is only supported in an ES2
- * context or when GL_ARB_ES2_compatibility is supported. In an OpenGL
- * 3.0 "forward compatible" context, GLSL 1.10 and 1.20 are \b not
- * supported.
- */
- /*@{*/
- unsigned GLSL_100ES:1;
- unsigned GLSL_110:1;
- unsigned GLSL_120:1;
- unsigned GLSL_130:1;
- /*@}*/
- } Const;
-
- /**
- * During AST to IR conversion, pointer to current IR function
- *
- * Will be \c NULL whenever the AST to IR conversion is not inside a
- * function definition.
- */
- class ir_function_signature *current_function;
-
- /** Have we found a return statement in this function? */
- bool found_return;
-
- /** Was there an error during compilation? */
- bool error;
-
- /**
- * Are all shader inputs / outputs invariant?
- *
- * This is set when the 'STDGL invariant(all)' pragma is used.
- */
- bool all_invariant;
-
- /** Loop or switch statement containing the current instructions. */
- class ir_instruction *loop_or_switch_nesting;
- class ast_iteration_statement *loop_or_switch_nesting_ast;
-
- /** List of structures defined in user code. */
- const glsl_type **user_structures;
- unsigned num_user_structures;
-
- char *info_log;
-
- /**
- * \name Enable bits for GLSL extensions
- */
- /*@{*/
- unsigned ARB_draw_buffers_enable:1;
- unsigned ARB_draw_buffers_warn:1;
- unsigned ARB_draw_instanced_enable:1;
- unsigned ARB_draw_instanced_warn:1;
- unsigned ARB_explicit_attrib_location_enable:1;
- unsigned ARB_explicit_attrib_location_warn:1;
- unsigned ARB_fragment_coord_conventions_enable:1;
- unsigned ARB_fragment_coord_conventions_warn:1;
- unsigned ARB_texture_rectangle_enable:1;
- unsigned ARB_texture_rectangle_warn:1;
- unsigned EXT_texture_array_enable:1;
- unsigned EXT_texture_array_warn:1;
- unsigned ARB_shader_stencil_export_enable:1;
- unsigned ARB_shader_stencil_export_warn:1;
- unsigned AMD_conservative_depth_enable:1;
- unsigned AMD_conservative_depth_warn:1;
- /*@}*/
-
- /** Extensions supported by the OpenGL implementation. */
- const struct gl_extensions *extensions;
-
- /** Shaders containing built-in functions that are used for linking. */
- struct gl_shader *builtins_to_link[16];
- unsigned num_builtins_to_link;
-};
-
-typedef struct YYLTYPE {
- int first_line;
- int first_column;
- int last_line;
- int last_column;
- unsigned source;
-} YYLTYPE;
-# define YYLTYPE_IS_DECLARED 1
-# define YYLTYPE_IS_TRIVIAL 1
-
-# define YYLLOC_DEFAULT(Current, Rhs, N) \
-do { \
- if (N) \
- { \
- (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
- (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
- (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
- (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
- } \
- else \
- { \
- (Current).first_line = (Current).last_line = \
- YYRHSLOC(Rhs, 0).last_line; \
- (Current).first_column = (Current).last_column = \
- YYRHSLOC(Rhs, 0).last_column; \
- } \
- (Current).source = 0; \
-} while (0)
-
-extern void _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
- const char *fmt, ...);
-
-/**
- * Emit a warning to the shader log
- *
- * \sa _mesa_glsl_error
- */
-extern void _mesa_glsl_warning(const YYLTYPE *locp,
- _mesa_glsl_parse_state *state,
- const char *fmt, ...);
-
-extern void _mesa_glsl_lexer_ctor(struct _mesa_glsl_parse_state *state,
- const char *string);
-
-extern void _mesa_glsl_lexer_dtor(struct _mesa_glsl_parse_state *state);
-
-union YYSTYPE;
-extern int _mesa_glsl_lex(union YYSTYPE *yylval, YYLTYPE *yylloc,
- void *scanner);
-
-extern int _mesa_glsl_parse(struct _mesa_glsl_parse_state *);
-
-/**
- * Process elements of the #extension directive
- *
- * \return
- * If \c name and \c behavior are valid, \c true is returned. Otherwise
- * \c false is returned.
- */
-extern bool _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
- const char *behavior,
- YYLTYPE *behavior_locp,
- _mesa_glsl_parse_state *state);
-
-/**
- * Get the textual name of the specified shader target
- */
-extern const char *
-_mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target);
-
-
-#endif /* __cplusplus */
-
-
-/*
- * These definitions apply to C and C++
- */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-extern int preprocess(void *ctx, const char **shader, char **info_log,
- const struct gl_extensions *extensions, int api);
-
-extern void _mesa_destroy_shader_compiler();
-extern void _mesa_destroy_shader_compiler_caches();
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* GLSL_PARSER_EXTRAS_H */
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#pragma once
+#ifndef GLSL_PARSER_EXTRAS_H
+#define GLSL_PARSER_EXTRAS_H
+
+/*
+ * Most of the definitions here only apply to C++
+ */
+#ifdef __cplusplus
+
+
+#include <stdlib.h>
+#include "glsl_symbol_table.h"
+
+enum _mesa_glsl_parser_targets {
+ vertex_shader,
+ geometry_shader,
+ fragment_shader
+};
+
+struct gl_context;
+
+struct _mesa_glsl_parse_state {
+ _mesa_glsl_parse_state(struct gl_context *ctx, GLenum target,
+ void *mem_ctx);
+
+ /* Callers of this ralloc-based new need not call delete. It's
+ * easier to just ralloc_free 'ctx' (or any of its ancestors). */
+ static void* operator new(size_t size, void *ctx)
+ {
+ void *mem = rzalloc_size(ctx, size);
+ assert(mem != NULL);
+
+ return mem;
+ }
+
+ /* If the user *does* call delete, that's OK, we will just
+ * ralloc_free in that case. */
+ static void operator delete(void *mem, void *ctx)
+ {
+ ralloc_free(mem);
+ }
+ static void operator delete(void *mem)
+ {
+ ralloc_free(mem);
+ }
+
+ void *scanner;
+ exec_list translation_unit;
+ glsl_symbol_table *symbols;
+
+ bool es_shader;
+ unsigned language_version;
+ const char *version_string;
+ enum _mesa_glsl_parser_targets target;
+
+ /**
+ * Printable list of GLSL versions supported by the current context
+ *
+ * \note
+ * This string should probably be generated per-context instead of per
+ * invokation of the compiler. This should be changed when the method of
+ * tracking supported GLSL versions changes.
+ */
+ const char *supported_version_string;
+
+ /**
+ * Implementation defined limits that affect built-in variables, etc.
+ *
+ * \sa struct gl_constants (in mtypes.h)
+ */
+ struct {
+ /* 1.10 */
+ unsigned MaxLights;
+ unsigned MaxClipPlanes;
+ unsigned MaxTextureUnits;
+ unsigned MaxTextureCoords;
+ unsigned MaxVertexAttribs;
+ unsigned MaxVertexUniformComponents;
+ unsigned MaxVaryingFloats;
+ unsigned MaxVertexTextureImageUnits;
+ unsigned MaxCombinedTextureImageUnits;
+ unsigned MaxTextureImageUnits;
+ unsigned MaxFragmentUniformComponents;
+
+ /* ARB_draw_buffers */
+ unsigned MaxDrawBuffers;
+
+ /**
+ * Set of GLSL versions supported by the current context
+ *
+ * Knowing that version X is supported doesn't mean that versions before
+ * X are also supported. Version 1.00 is only supported in an ES2
+ * context or when GL_ARB_ES2_compatibility is supported. In an OpenGL
+ * 3.0 "forward compatible" context, GLSL 1.10 and 1.20 are \b not
+ * supported.
+ */
+ /*@{*/
+ unsigned GLSL_100ES:1;
+ unsigned GLSL_110:1;
+ unsigned GLSL_120:1;
+ unsigned GLSL_130:1;
+ /*@}*/
+ } Const;
+
+ /**
+ * During AST to IR conversion, pointer to current IR function
+ *
+ * Will be \c NULL whenever the AST to IR conversion is not inside a
+ * function definition.
+ */
+ class ir_function_signature *current_function;
+
+ /** Have we found a return statement in this function? */
+ bool found_return;
+
+ /** Was there an error during compilation? */
+ bool error;
+
+ /**
+ * Are all shader inputs / outputs invariant?
+ *
+ * This is set when the 'STDGL invariant(all)' pragma is used.
+ */
+ bool all_invariant;
+
+ /** Loop or switch statement containing the current instructions. */
+ class ir_instruction *loop_or_switch_nesting;
+ class ast_iteration_statement *loop_or_switch_nesting_ast;
+
+ /** List of structures defined in user code. */
+ const glsl_type **user_structures;
+ unsigned num_user_structures;
+
+ char *info_log;
+
+ /**
+ * \name Enable bits for GLSL extensions
+ */
+ /*@{*/
+ unsigned ARB_draw_buffers_enable:1;
+ unsigned ARB_draw_buffers_warn:1;
+ unsigned ARB_draw_instanced_enable:1;
+ unsigned ARB_draw_instanced_warn:1;
+ unsigned ARB_explicit_attrib_location_enable:1;
+ unsigned ARB_explicit_attrib_location_warn:1;
+ unsigned ARB_fragment_coord_conventions_enable:1;
+ unsigned ARB_fragment_coord_conventions_warn:1;
+ unsigned ARB_texture_rectangle_enable:1;
+ unsigned ARB_texture_rectangle_warn:1;
+ unsigned EXT_texture_array_enable:1;
+ unsigned EXT_texture_array_warn:1;
+ unsigned ARB_shader_stencil_export_enable:1;
+ unsigned ARB_shader_stencil_export_warn:1;
+ unsigned AMD_conservative_depth_enable:1;
+ unsigned AMD_conservative_depth_warn:1;
+ /*@}*/
+
+ /** Extensions supported by the OpenGL implementation. */
+ const struct gl_extensions *extensions;
+
+ /** Shaders containing built-in functions that are used for linking. */
+ struct gl_shader *builtins_to_link[16];
+ unsigned num_builtins_to_link;
+};
+
+typedef struct YYLTYPE {
+ int first_line;
+ int first_column;
+ int last_line;
+ int last_column;
+ unsigned source;
+} YYLTYPE;
+# define YYLTYPE_IS_DECLARED 1
+# define YYLTYPE_IS_TRIVIAL 1
+
+# define YYLLOC_DEFAULT(Current, Rhs, N) \
+do { \
+ if (N) \
+ { \
+ (Current).first_line = YYRHSLOC(Rhs, 1).first_line; \
+ (Current).first_column = YYRHSLOC(Rhs, 1).first_column; \
+ (Current).last_line = YYRHSLOC(Rhs, N).last_line; \
+ (Current).last_column = YYRHSLOC(Rhs, N).last_column; \
+ } \
+ else \
+ { \
+ (Current).first_line = (Current).last_line = \
+ YYRHSLOC(Rhs, 0).last_line; \
+ (Current).first_column = (Current).last_column = \
+ YYRHSLOC(Rhs, 0).last_column; \
+ } \
+ (Current).source = 0; \
+} while (0)
+
+extern void _mesa_glsl_error(YYLTYPE *locp, _mesa_glsl_parse_state *state,
+ const char *fmt, ...);
+
+/**
+ * Emit a warning to the shader log
+ *
+ * \sa _mesa_glsl_error
+ */
+extern void _mesa_glsl_warning(const YYLTYPE *locp,
+ _mesa_glsl_parse_state *state,
+ const char *fmt, ...);
+
+extern void _mesa_glsl_lexer_ctor(struct _mesa_glsl_parse_state *state,
+ const char *string);
+
+extern void _mesa_glsl_lexer_dtor(struct _mesa_glsl_parse_state *state);
+
+union YYSTYPE;
+extern int _mesa_glsl_lex(union YYSTYPE *yylval, YYLTYPE *yylloc,
+ void *scanner);
+
+extern int _mesa_glsl_parse(struct _mesa_glsl_parse_state *);
+
+/**
+ * Process elements of the #extension directive
+ *
+ * \return
+ * If \c name and \c behavior are valid, \c true is returned. Otherwise
+ * \c false is returned.
+ */
+extern bool _mesa_glsl_process_extension(const char *name, YYLTYPE *name_locp,
+ const char *behavior,
+ YYLTYPE *behavior_locp,
+ _mesa_glsl_parse_state *state);
+
+/**
+ * Get the textual name of the specified shader target
+ */
+extern const char *
+_mesa_glsl_shader_target_name(enum _mesa_glsl_parser_targets target);
+
+
+#endif /* __cplusplus */
+
+
+/*
+ * These definitions apply to C and C++
+ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int preprocess(void *ctx, const char **shader, char **info_log,
+ const struct gl_extensions *extensions, int api);
+
+extern void _mesa_destroy_shader_compiler();
+extern void _mesa_destroy_shader_compiler_caches();
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* GLSL_PARSER_EXTRAS_H */
diff --git a/mesalib/src/glsl/glsl_symbol_table.cpp b/mesalib/src/glsl/glsl_symbol_table.cpp
index 2f291d4f9..9714384eb 100644
--- a/mesalib/src/glsl/glsl_symbol_table.cpp
+++ b/mesalib/src/glsl/glsl_symbol_table.cpp
@@ -36,6 +36,10 @@ public:
}
/* If the user *does* call delete, that's OK, we will just ralloc_free. */
+ static void operator delete(void *entry, void *ctx)
+ {
+ ralloc_free(entry);
+ }
static void operator delete(void *entry)
{
ralloc_free(entry);
diff --git a/mesalib/src/glsl/glsl_symbol_table.h b/mesalib/src/glsl/glsl_symbol_table.h
index 637bc033b..1afeddb33 100644
--- a/mesalib/src/glsl/glsl_symbol_table.h
+++ b/mesalib/src/glsl/glsl_symbol_table.h
@@ -68,6 +68,11 @@ public:
/* If the user *does* call delete, that's OK, we will just
* ralloc_free in that case. Here, C++ will have already called the
* destructor so tell ralloc not to do that again. */
+ static void operator delete(void *table, void *ctx)
+ {
+ ralloc_set_destructor(table, NULL);
+ ralloc_free(table);
+ }
static void operator delete(void *table)
{
ralloc_set_destructor(table, NULL);
diff --git a/mesalib/src/glsl/glsl_types.cpp b/mesalib/src/glsl/glsl_types.cpp
index 76b4f3e4c..1802bf0ac 100644
--- a/mesalib/src/glsl/glsl_types.cpp
+++ b/mesalib/src/glsl/glsl_types.cpp
@@ -1,497 +1,497 @@
-/*
- * Copyright © 2009 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include "main/core.h" /* for Elements */
-#include "glsl_symbol_table.h"
-#include "glsl_parser_extras.h"
-#include "glsl_types.h"
-#include "builtin_types.h"
-extern "C" {
-#include "program/hash_table.h"
-}
-
-hash_table *glsl_type::array_types = NULL;
-hash_table *glsl_type::record_types = NULL;
-void *glsl_type::mem_ctx = NULL;
-
-void
-glsl_type::init_ralloc_type_ctx(void)
-{
- if (glsl_type::mem_ctx == NULL) {
- glsl_type::mem_ctx = ralloc_autofree_context();
- assert(glsl_type::mem_ctx != NULL);
- }
-}
-
-glsl_type::glsl_type(GLenum gl_type,
- glsl_base_type base_type, unsigned vector_elements,
- unsigned matrix_columns, const char *name) :
- gl_type(gl_type),
- base_type(base_type),
- sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
- sampler_type(0),
- vector_elements(vector_elements), matrix_columns(matrix_columns),
- length(0)
-{
- init_ralloc_type_ctx();
- this->name = ralloc_strdup(this->mem_ctx, name);
- /* Neither dimension is zero or both dimensions are zero.
- */
- assert((vector_elements == 0) == (matrix_columns == 0));
- memset(& fields, 0, sizeof(fields));
-}
-
-glsl_type::glsl_type(GLenum gl_type,
- enum glsl_sampler_dim dim, bool shadow, bool array,
- unsigned type, const char *name) :
- gl_type(gl_type),
- base_type(GLSL_TYPE_SAMPLER),
- sampler_dimensionality(dim), sampler_shadow(shadow),
- sampler_array(array), sampler_type(type),
- vector_elements(0), matrix_columns(0),
- length(0)
-{
- init_ralloc_type_ctx();
- this->name = ralloc_strdup(this->mem_ctx, name);
- memset(& fields, 0, sizeof(fields));
-}
-
-glsl_type::glsl_type(const glsl_struct_field *fields, unsigned num_fields,
- const char *name) :
- base_type(GLSL_TYPE_STRUCT),
- sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
- sampler_type(0),
- vector_elements(0), matrix_columns(0),
- length(num_fields)
-{
- unsigned int i;
-
- init_ralloc_type_ctx();
- this->name = ralloc_strdup(this->mem_ctx, name);
- this->fields.structure = ralloc_array(this->mem_ctx,
- glsl_struct_field, length);
- for (i = 0; i < length; i++) {
- this->fields.structure[i].type = fields[i].type;
- this->fields.structure[i].name = ralloc_strdup(this->fields.structure,
- fields[i].name);
- }
-}
-
-static void
-add_types_to_symbol_table(glsl_symbol_table *symtab,
- const struct glsl_type *types,
- unsigned num_types, bool warn)
-{
- (void) warn;
-
- for (unsigned i = 0; i < num_types; i++) {
- symtab->add_type(types[i].name, & types[i]);
- }
-}
-
-void
-glsl_type::generate_100ES_types(glsl_symbol_table *symtab)
-{
- add_types_to_symbol_table(symtab, builtin_core_types,
- Elements(builtin_core_types),
- false);
- add_types_to_symbol_table(symtab, builtin_structure_types,
- Elements(builtin_structure_types),
- false);
- add_types_to_symbol_table(symtab, void_type, 1, false);
-}
-
-void
-glsl_type::generate_110_types(glsl_symbol_table *symtab)
-{
- generate_100ES_types(symtab);
-
- add_types_to_symbol_table(symtab, builtin_110_types,
- Elements(builtin_110_types),
- false);
- add_types_to_symbol_table(symtab, builtin_110_deprecated_structure_types,
- Elements(builtin_110_deprecated_structure_types),
- false);
-}
-
-
-void
-glsl_type::generate_120_types(glsl_symbol_table *symtab)
-{
- generate_110_types(symtab);
-
- add_types_to_symbol_table(symtab, builtin_120_types,
- Elements(builtin_120_types), false);
-}
-
-
-void
-glsl_type::generate_130_types(glsl_symbol_table *symtab)
-{
- generate_120_types(symtab);
-
- add_types_to_symbol_table(symtab, builtin_130_types,
- Elements(builtin_130_types), false);
- generate_EXT_texture_array_types(symtab, false);
-}
-
-
-void
-glsl_type::generate_ARB_texture_rectangle_types(glsl_symbol_table *symtab,
- bool warn)
-{
- add_types_to_symbol_table(symtab, builtin_ARB_texture_rectangle_types,
- Elements(builtin_ARB_texture_rectangle_types),
- warn);
-}
-
-
-void
-glsl_type::generate_EXT_texture_array_types(glsl_symbol_table *symtab,
- bool warn)
-{
- add_types_to_symbol_table(symtab, builtin_EXT_texture_array_types,
- Elements(builtin_EXT_texture_array_types),
- warn);
-}
-
-
-void
-_mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *state)
-{
- switch (state->language_version) {
- case 100:
- assert(state->es_shader);
- glsl_type::generate_100ES_types(state->symbols);
- break;
- case 110:
- glsl_type::generate_110_types(state->symbols);
- break;
- case 120:
- glsl_type::generate_120_types(state->symbols);
- break;
- case 130:
- glsl_type::generate_130_types(state->symbols);
- break;
- default:
- /* error */
- break;
- }
-
- if (state->ARB_texture_rectangle_enable) {
- glsl_type::generate_ARB_texture_rectangle_types(state->symbols,
- state->ARB_texture_rectangle_warn);
- }
-
- if (state->EXT_texture_array_enable && state->language_version < 130) {
- // These are already included in 130; don't create twice.
- glsl_type::generate_EXT_texture_array_types(state->symbols,
- state->EXT_texture_array_warn);
- }
-}
-
-
-const glsl_type *glsl_type::get_base_type() const
-{
- switch (base_type) {
- case GLSL_TYPE_UINT:
- return uint_type;
- case GLSL_TYPE_INT:
- return int_type;
- case GLSL_TYPE_FLOAT:
- return float_type;
- case GLSL_TYPE_BOOL:
- return bool_type;
- default:
- return error_type;
- }
-}
-
-
-void
-_mesa_glsl_release_types(void)
-{
- if (glsl_type::array_types != NULL) {
- hash_table_dtor(glsl_type::array_types);
- glsl_type::array_types = NULL;
- }
-
- if (glsl_type::record_types != NULL) {
- hash_table_dtor(glsl_type::record_types);
- glsl_type::record_types = NULL;
- }
-}
-
-
-glsl_type::glsl_type(const glsl_type *array, unsigned length) :
- base_type(GLSL_TYPE_ARRAY),
- sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
- sampler_type(0),
- vector_elements(0), matrix_columns(0),
- name(NULL), length(length)
-{
- this->fields.array = array;
- /* Inherit the gl type of the base. The GL type is used for
- * uniform/statevar handling in Mesa and the arrayness of the type
- * is represented by the size rather than the type.
- */
- this->gl_type = array->gl_type;
-
- /* Allow a maximum of 10 characters for the array size. This is enough
- * for 32-bits of ~0. The extra 3 are for the '[', ']', and terminating
- * NUL.
- */
- const unsigned name_length = strlen(array->name) + 10 + 3;
- char *const n = (char *) ralloc_size(this->mem_ctx, name_length);
-
- if (length == 0)
- snprintf(n, name_length, "%s[]", array->name);
- else
- snprintf(n, name_length, "%s[%u]", array->name, length);
-
- this->name = n;
-}
-
-
-const glsl_type *
-glsl_type::get_instance(unsigned base_type, unsigned rows, unsigned columns)
-{
- if (base_type == GLSL_TYPE_VOID)
- return void_type;
-
- if ((rows < 1) || (rows > 4) || (columns < 1) || (columns > 4))
- return error_type;
-
- /* Treat GLSL vectors as Nx1 matrices.
- */
- if (columns == 1) {
- switch (base_type) {
- case GLSL_TYPE_UINT:
- return uint_type + (rows - 1);
- case GLSL_TYPE_INT:
- return int_type + (rows - 1);
- case GLSL_TYPE_FLOAT:
- return float_type + (rows - 1);
- case GLSL_TYPE_BOOL:
- return bool_type + (rows - 1);
- default:
- return error_type;
- }
- } else {
- if ((base_type != GLSL_TYPE_FLOAT) || (rows == 1))
- return error_type;
-
- /* GLSL matrix types are named mat{COLUMNS}x{ROWS}. Only the following
- * combinations are valid:
- *
- * 1 2 3 4
- * 1
- * 2 x x x
- * 3 x x x
- * 4 x x x
- */
-#define IDX(c,r) (((c-1)*3) + (r-1))
-
- switch (IDX(columns, rows)) {
- case IDX(2,2): return mat2_type;
- case IDX(2,3): return mat2x3_type;
- case IDX(2,4): return mat2x4_type;
- case IDX(3,2): return mat3x2_type;
- case IDX(3,3): return mat3_type;
- case IDX(3,4): return mat3x4_type;
- case IDX(4,2): return mat4x2_type;
- case IDX(4,3): return mat4x3_type;
- case IDX(4,4): return mat4_type;
- default: return error_type;
- }
- }
-
- assert(!"Should not get here.");
- return error_type;
-}
-
-
-const glsl_type *
-glsl_type::get_array_instance(const glsl_type *base, unsigned array_size)
-{
-
- if (array_types == NULL) {
- array_types = hash_table_ctor(64, hash_table_string_hash,
- hash_table_string_compare);
- }
-
- /* Generate a name using the base type pointer in the key. This is
- * done because the name of the base type may not be unique across
- * shaders. For example, two shaders may have different record types
- * named 'foo'.
- */
- char key[128];
- snprintf(key, sizeof(key), "%p[%u]", (void *) base, array_size);
-
- const glsl_type *t = (glsl_type *) hash_table_find(array_types, key);
- if (t == NULL) {
- t = new glsl_type(base, array_size);
-
- hash_table_insert(array_types, (void *) t, ralloc_strdup(mem_ctx, key));
- }
-
- assert(t->base_type == GLSL_TYPE_ARRAY);
- assert(t->length == array_size);
- assert(t->fields.array == base);
-
- return t;
-}
-
-
-int
-glsl_type::record_key_compare(const void *a, const void *b)
-{
- const glsl_type *const key1 = (glsl_type *) a;
- const glsl_type *const key2 = (glsl_type *) b;
-
- /* Return zero is the types match (there is zero difference) or non-zero
- * otherwise.
- */
- if (strcmp(key1->name, key2->name) != 0)
- return 1;
-
- if (key1->length != key2->length)
- return 1;
-
- for (unsigned i = 0; i < key1->length; i++) {
- if (key1->fields.structure[i].type != key2->fields.structure[i].type)
- return 1;
- if (strcmp(key1->fields.structure[i].name,
- key2->fields.structure[i].name) != 0)
- return 1;
- }
-
- return 0;
-}
-
-
-unsigned
-glsl_type::record_key_hash(const void *a)
-{
- const glsl_type *const key = (glsl_type *) a;
- char hash_key[128];
- unsigned size = 0;
-
- size = snprintf(hash_key, sizeof(hash_key), "%08x", key->length);
-
- for (unsigned i = 0; i < key->length; i++) {
- if (size >= sizeof(hash_key))
- break;
-
- size += snprintf(& hash_key[size], sizeof(hash_key) - size,
- "%p", (void *) key->fields.structure[i].type);
- }
-
- return hash_table_string_hash(& hash_key);
-}
-
-
-const glsl_type *
-glsl_type::get_record_instance(const glsl_struct_field *fields,
- unsigned num_fields,
- const char *name)
-{
- const glsl_type key(fields, num_fields, name);
-
- if (record_types == NULL) {
- record_types = hash_table_ctor(64, record_key_hash, record_key_compare);
- }
-
- const glsl_type *t = (glsl_type *) hash_table_find(record_types, & key);
- if (t == NULL) {
- t = new glsl_type(fields, num_fields, name);
-
- hash_table_insert(record_types, (void *) t, t);
- }
-
- assert(t->base_type == GLSL_TYPE_STRUCT);
- assert(t->length == num_fields);
- assert(strcmp(t->name, name) == 0);
-
- return t;
-}
-
-
-const glsl_type *
-glsl_type::field_type(const char *name) const
-{
- if (this->base_type != GLSL_TYPE_STRUCT)
- return error_type;
-
- for (unsigned i = 0; i < this->length; i++) {
- if (strcmp(name, this->fields.structure[i].name) == 0)
- return this->fields.structure[i].type;
- }
-
- return error_type;
-}
-
-
-int
-glsl_type::field_index(const char *name) const
-{
- if (this->base_type != GLSL_TYPE_STRUCT)
- return -1;
-
- for (unsigned i = 0; i < this->length; i++) {
- if (strcmp(name, this->fields.structure[i].name) == 0)
- return i;
- }
-
- return -1;
-}
-
-
-unsigned
-glsl_type::component_slots() const
-{
- switch (this->base_type) {
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT:
- case GLSL_TYPE_FLOAT:
- case GLSL_TYPE_BOOL:
- return this->components();
-
- case GLSL_TYPE_STRUCT: {
- unsigned size = 0;
-
- for (unsigned i = 0; i < this->length; i++)
- size += this->fields.structure[i].type->component_slots();
-
- return size;
- }
-
- case GLSL_TYPE_ARRAY:
- return this->length * this->fields.array->component_slots();
-
- default:
- return 0;
- }
-}
+/*
+ * Copyright © 2009 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "main/core.h" /* for Elements */
+#include "glsl_symbol_table.h"
+#include "glsl_parser_extras.h"
+#include "glsl_types.h"
+#include "builtin_types.h"
+extern "C" {
+#include "program/hash_table.h"
+}
+
+hash_table *glsl_type::array_types = NULL;
+hash_table *glsl_type::record_types = NULL;
+void *glsl_type::mem_ctx = NULL;
+
+void
+glsl_type::init_ralloc_type_ctx(void)
+{
+ if (glsl_type::mem_ctx == NULL) {
+ glsl_type::mem_ctx = ralloc_autofree_context();
+ assert(glsl_type::mem_ctx != NULL);
+ }
+}
+
+glsl_type::glsl_type(GLenum gl_type,
+ glsl_base_type base_type, unsigned vector_elements,
+ unsigned matrix_columns, const char *name) :
+ gl_type(gl_type),
+ base_type(base_type),
+ sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
+ sampler_type(0),
+ vector_elements(vector_elements), matrix_columns(matrix_columns),
+ length(0)
+{
+ init_ralloc_type_ctx();
+ this->name = ralloc_strdup(this->mem_ctx, name);
+ /* Neither dimension is zero or both dimensions are zero.
+ */
+ assert((vector_elements == 0) == (matrix_columns == 0));
+ memset(& fields, 0, sizeof(fields));
+}
+
+glsl_type::glsl_type(GLenum gl_type,
+ enum glsl_sampler_dim dim, bool shadow, bool array,
+ unsigned type, const char *name) :
+ gl_type(gl_type),
+ base_type(GLSL_TYPE_SAMPLER),
+ sampler_dimensionality(dim), sampler_shadow(shadow),
+ sampler_array(array), sampler_type(type),
+ vector_elements(0), matrix_columns(0),
+ length(0)
+{
+ init_ralloc_type_ctx();
+ this->name = ralloc_strdup(this->mem_ctx, name);
+ memset(& fields, 0, sizeof(fields));
+}
+
+glsl_type::glsl_type(const glsl_struct_field *fields, unsigned num_fields,
+ const char *name) :
+ base_type(GLSL_TYPE_STRUCT),
+ sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
+ sampler_type(0),
+ vector_elements(0), matrix_columns(0),
+ length(num_fields)
+{
+ unsigned int i;
+
+ init_ralloc_type_ctx();
+ this->name = ralloc_strdup(this->mem_ctx, name);
+ this->fields.structure = ralloc_array(this->mem_ctx,
+ glsl_struct_field, length);
+ for (i = 0; i < length; i++) {
+ this->fields.structure[i].type = fields[i].type;
+ this->fields.structure[i].name = ralloc_strdup(this->fields.structure,
+ fields[i].name);
+ }
+}
+
+static void
+add_types_to_symbol_table(glsl_symbol_table *symtab,
+ const struct glsl_type *types,
+ unsigned num_types, bool warn)
+{
+ (void) warn;
+
+ for (unsigned i = 0; i < num_types; i++) {
+ symtab->add_type(types[i].name, & types[i]);
+ }
+}
+
+void
+glsl_type::generate_100ES_types(glsl_symbol_table *symtab)
+{
+ add_types_to_symbol_table(symtab, builtin_core_types,
+ Elements(builtin_core_types),
+ false);
+ add_types_to_symbol_table(symtab, builtin_structure_types,
+ Elements(builtin_structure_types),
+ false);
+ add_types_to_symbol_table(symtab, void_type, 1, false);
+}
+
+void
+glsl_type::generate_110_types(glsl_symbol_table *symtab)
+{
+ generate_100ES_types(symtab);
+
+ add_types_to_symbol_table(symtab, builtin_110_types,
+ Elements(builtin_110_types),
+ false);
+ add_types_to_symbol_table(symtab, builtin_110_deprecated_structure_types,
+ Elements(builtin_110_deprecated_structure_types),
+ false);
+}
+
+
+void
+glsl_type::generate_120_types(glsl_symbol_table *symtab)
+{
+ generate_110_types(symtab);
+
+ add_types_to_symbol_table(symtab, builtin_120_types,
+ Elements(builtin_120_types), false);
+}
+
+
+void
+glsl_type::generate_130_types(glsl_symbol_table *symtab)
+{
+ generate_120_types(symtab);
+
+ add_types_to_symbol_table(symtab, builtin_130_types,
+ Elements(builtin_130_types), false);
+ generate_EXT_texture_array_types(symtab, false);
+}
+
+
+void
+glsl_type::generate_ARB_texture_rectangle_types(glsl_symbol_table *symtab,
+ bool warn)
+{
+ add_types_to_symbol_table(symtab, builtin_ARB_texture_rectangle_types,
+ Elements(builtin_ARB_texture_rectangle_types),
+ warn);
+}
+
+
+void
+glsl_type::generate_EXT_texture_array_types(glsl_symbol_table *symtab,
+ bool warn)
+{
+ add_types_to_symbol_table(symtab, builtin_EXT_texture_array_types,
+ Elements(builtin_EXT_texture_array_types),
+ warn);
+}
+
+
+void
+_mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *state)
+{
+ switch (state->language_version) {
+ case 100:
+ assert(state->es_shader);
+ glsl_type::generate_100ES_types(state->symbols);
+ break;
+ case 110:
+ glsl_type::generate_110_types(state->symbols);
+ break;
+ case 120:
+ glsl_type::generate_120_types(state->symbols);
+ break;
+ case 130:
+ glsl_type::generate_130_types(state->symbols);
+ break;
+ default:
+ /* error */
+ break;
+ }
+
+ if (state->ARB_texture_rectangle_enable) {
+ glsl_type::generate_ARB_texture_rectangle_types(state->symbols,
+ state->ARB_texture_rectangle_warn);
+ }
+
+ if (state->EXT_texture_array_enable && state->language_version < 130) {
+ // These are already included in 130; don't create twice.
+ glsl_type::generate_EXT_texture_array_types(state->symbols,
+ state->EXT_texture_array_warn);
+ }
+}
+
+
+const glsl_type *glsl_type::get_base_type() const
+{
+ switch (base_type) {
+ case GLSL_TYPE_UINT:
+ return uint_type;
+ case GLSL_TYPE_INT:
+ return int_type;
+ case GLSL_TYPE_FLOAT:
+ return float_type;
+ case GLSL_TYPE_BOOL:
+ return bool_type;
+ default:
+ return error_type;
+ }
+}
+
+
+void
+_mesa_glsl_release_types(void)
+{
+ if (glsl_type::array_types != NULL) {
+ hash_table_dtor(glsl_type::array_types);
+ glsl_type::array_types = NULL;
+ }
+
+ if (glsl_type::record_types != NULL) {
+ hash_table_dtor(glsl_type::record_types);
+ glsl_type::record_types = NULL;
+ }
+}
+
+
+glsl_type::glsl_type(const glsl_type *array, unsigned length) :
+ base_type(GLSL_TYPE_ARRAY),
+ sampler_dimensionality(0), sampler_shadow(0), sampler_array(0),
+ sampler_type(0),
+ vector_elements(0), matrix_columns(0),
+ name(NULL), length(length)
+{
+ this->fields.array = array;
+ /* Inherit the gl type of the base. The GL type is used for
+ * uniform/statevar handling in Mesa and the arrayness of the type
+ * is represented by the size rather than the type.
+ */
+ this->gl_type = array->gl_type;
+
+ /* Allow a maximum of 10 characters for the array size. This is enough
+ * for 32-bits of ~0. The extra 3 are for the '[', ']', and terminating
+ * NUL.
+ */
+ const unsigned name_length = strlen(array->name) + 10 + 3;
+ char *const n = (char *) ralloc_size(this->mem_ctx, name_length);
+
+ if (length == 0)
+ snprintf(n, name_length, "%s[]", array->name);
+ else
+ snprintf(n, name_length, "%s[%u]", array->name, length);
+
+ this->name = n;
+}
+
+
+const glsl_type *
+glsl_type::get_instance(unsigned base_type, unsigned rows, unsigned columns)
+{
+ if (base_type == GLSL_TYPE_VOID)
+ return void_type;
+
+ if ((rows < 1) || (rows > 4) || (columns < 1) || (columns > 4))
+ return error_type;
+
+ /* Treat GLSL vectors as Nx1 matrices.
+ */
+ if (columns == 1) {
+ switch (base_type) {
+ case GLSL_TYPE_UINT:
+ return uint_type + (rows - 1);
+ case GLSL_TYPE_INT:
+ return int_type + (rows - 1);
+ case GLSL_TYPE_FLOAT:
+ return float_type + (rows - 1);
+ case GLSL_TYPE_BOOL:
+ return bool_type + (rows - 1);
+ default:
+ return error_type;
+ }
+ } else {
+ if ((base_type != GLSL_TYPE_FLOAT) || (rows == 1))
+ return error_type;
+
+ /* GLSL matrix types are named mat{COLUMNS}x{ROWS}. Only the following
+ * combinations are valid:
+ *
+ * 1 2 3 4
+ * 1
+ * 2 x x x
+ * 3 x x x
+ * 4 x x x
+ */
+#define IDX(c,r) (((c-1)*3) + (r-1))
+
+ switch (IDX(columns, rows)) {
+ case IDX(2,2): return mat2_type;
+ case IDX(2,3): return mat2x3_type;
+ case IDX(2,4): return mat2x4_type;
+ case IDX(3,2): return mat3x2_type;
+ case IDX(3,3): return mat3_type;
+ case IDX(3,4): return mat3x4_type;
+ case IDX(4,2): return mat4x2_type;
+ case IDX(4,3): return mat4x3_type;
+ case IDX(4,4): return mat4_type;
+ default: return error_type;
+ }
+ }
+
+ assert(!"Should not get here.");
+ return error_type;
+}
+
+
+const glsl_type *
+glsl_type::get_array_instance(const glsl_type *base, unsigned array_size)
+{
+
+ if (array_types == NULL) {
+ array_types = hash_table_ctor(64, hash_table_string_hash,
+ hash_table_string_compare);
+ }
+
+ /* Generate a name using the base type pointer in the key. This is
+ * done because the name of the base type may not be unique across
+ * shaders. For example, two shaders may have different record types
+ * named 'foo'.
+ */
+ char key[128];
+ snprintf(key, sizeof(key), "%p[%u]", (void *) base, array_size);
+
+ const glsl_type *t = (glsl_type *) hash_table_find(array_types, key);
+ if (t == NULL) {
+ t = new glsl_type(base, array_size);
+
+ hash_table_insert(array_types, (void *) t, ralloc_strdup(mem_ctx, key));
+ }
+
+ assert(t->base_type == GLSL_TYPE_ARRAY);
+ assert(t->length == array_size);
+ assert(t->fields.array == base);
+
+ return t;
+}
+
+
+int
+glsl_type::record_key_compare(const void *a, const void *b)
+{
+ const glsl_type *const key1 = (glsl_type *) a;
+ const glsl_type *const key2 = (glsl_type *) b;
+
+ /* Return zero is the types match (there is zero difference) or non-zero
+ * otherwise.
+ */
+ if (strcmp(key1->name, key2->name) != 0)
+ return 1;
+
+ if (key1->length != key2->length)
+ return 1;
+
+ for (unsigned i = 0; i < key1->length; i++) {
+ if (key1->fields.structure[i].type != key2->fields.structure[i].type)
+ return 1;
+ if (strcmp(key1->fields.structure[i].name,
+ key2->fields.structure[i].name) != 0)
+ return 1;
+ }
+
+ return 0;
+}
+
+
+unsigned
+glsl_type::record_key_hash(const void *a)
+{
+ const glsl_type *const key = (glsl_type *) a;
+ char hash_key[128];
+ unsigned size = 0;
+
+ size = snprintf(hash_key, sizeof(hash_key), "%08x", key->length);
+
+ for (unsigned i = 0; i < key->length; i++) {
+ if (size >= sizeof(hash_key))
+ break;
+
+ size += snprintf(& hash_key[size], sizeof(hash_key) - size,
+ "%p", (void *) key->fields.structure[i].type);
+ }
+
+ return hash_table_string_hash(& hash_key);
+}
+
+
+const glsl_type *
+glsl_type::get_record_instance(const glsl_struct_field *fields,
+ unsigned num_fields,
+ const char *name)
+{
+ const glsl_type key(fields, num_fields, name);
+
+ if (record_types == NULL) {
+ record_types = hash_table_ctor(64, record_key_hash, record_key_compare);
+ }
+
+ const glsl_type *t = (glsl_type *) hash_table_find(record_types, & key);
+ if (t == NULL) {
+ t = new glsl_type(fields, num_fields, name);
+
+ hash_table_insert(record_types, (void *) t, t);
+ }
+
+ assert(t->base_type == GLSL_TYPE_STRUCT);
+ assert(t->length == num_fields);
+ assert(strcmp(t->name, name) == 0);
+
+ return t;
+}
+
+
+const glsl_type *
+glsl_type::field_type(const char *name) const
+{
+ if (this->base_type != GLSL_TYPE_STRUCT)
+ return error_type;
+
+ for (unsigned i = 0; i < this->length; i++) {
+ if (strcmp(name, this->fields.structure[i].name) == 0)
+ return this->fields.structure[i].type;
+ }
+
+ return error_type;
+}
+
+
+int
+glsl_type::field_index(const char *name) const
+{
+ if (this->base_type != GLSL_TYPE_STRUCT)
+ return -1;
+
+ for (unsigned i = 0; i < this->length; i++) {
+ if (strcmp(name, this->fields.structure[i].name) == 0)
+ return i;
+ }
+
+ return -1;
+}
+
+
+unsigned
+glsl_type::component_slots() const
+{
+ switch (this->base_type) {
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT:
+ case GLSL_TYPE_FLOAT:
+ case GLSL_TYPE_BOOL:
+ return this->components();
+
+ case GLSL_TYPE_STRUCT: {
+ unsigned size = 0;
+
+ for (unsigned i = 0; i < this->length; i++)
+ size += this->fields.structure[i].type->component_slots();
+
+ return size;
+ }
+
+ case GLSL_TYPE_ARRAY:
+ return this->length * this->fields.array->component_slots();
+
+ default:
+ return 0;
+ }
+}
diff --git a/mesalib/src/glsl/glsl_types.h b/mesalib/src/glsl/glsl_types.h
index 61bf5e0cf..c3b7255a3 100644
--- a/mesalib/src/glsl/glsl_types.h
+++ b/mesalib/src/glsl/glsl_types.h
@@ -1,476 +1,476 @@
-/* -*- c++ -*- */
-/*
- * Copyright © 2009 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#pragma once
-#ifndef GLSL_TYPES_H
-#define GLSL_TYPES_H
-
-#include <string.h>
-#include <assert.h>
-
-extern "C" {
-#include "GL/gl.h"
-}
-
-#include "ralloc.h"
-
-struct _mesa_glsl_parse_state;
-struct glsl_symbol_table;
-
-extern "C" void
-_mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *state);
-
-extern "C" void
-_mesa_glsl_release_types(void);
-
-enum glsl_base_type {
- GLSL_TYPE_UINT = 0,
- GLSL_TYPE_INT,
- GLSL_TYPE_FLOAT,
- GLSL_TYPE_BOOL,
- GLSL_TYPE_SAMPLER,
- GLSL_TYPE_STRUCT,
- GLSL_TYPE_ARRAY,
- GLSL_TYPE_VOID,
- GLSL_TYPE_ERROR
-};
-
-enum glsl_sampler_dim {
- GLSL_SAMPLER_DIM_1D = 0,
- GLSL_SAMPLER_DIM_2D,
- GLSL_SAMPLER_DIM_3D,
- GLSL_SAMPLER_DIM_CUBE,
- GLSL_SAMPLER_DIM_RECT,
- GLSL_SAMPLER_DIM_BUF
-};
-
-
-struct glsl_type {
- GLenum gl_type;
- glsl_base_type base_type;
-
- unsigned sampler_dimensionality:3;
- unsigned sampler_shadow:1;
- unsigned sampler_array:1;
- unsigned sampler_type:2; /**< Type of data returned using this sampler.
- * only \c GLSL_TYPE_FLOAT, \c GLSL_TYPE_INT,
- * and \c GLSL_TYPE_UINT are valid.
- */
-
- /* Callers of this ralloc-based new need not call delete. It's
- * easier to just ralloc_free 'mem_ctx' (or any of its ancestors). */
- static void* operator new(size_t size)
- {
- if (glsl_type::mem_ctx == NULL) {
- glsl_type::mem_ctx = ralloc_context(NULL);
- assert(glsl_type::mem_ctx != NULL);
- }
-
- void *type;
-
- type = ralloc_size(glsl_type::mem_ctx, size);
- assert(type != NULL);
-
- return type;
- }
-
- /* If the user *does* call delete, that's OK, we will just
- * ralloc_free in that case. */
- static void operator delete(void *type)
- {
- ralloc_free(type);
- }
-
- /**
- * \name Vector and matrix element counts
- *
- * For scalars, each of these values will be 1. For non-numeric types
- * these will be 0.
- */
- /*@{*/
- unsigned vector_elements:3; /**< 1, 2, 3, or 4 vector elements. */
- unsigned matrix_columns:3; /**< 1, 2, 3, or 4 matrix columns. */
- /*@}*/
-
- /**
- * Name of the data type
- *
- * This may be \c NULL for anonymous structures, for arrays, or for
- * function types.
- */
- const char *name;
-
- /**
- * For \c GLSL_TYPE_ARRAY, this is the length of the array. For
- * \c GLSL_TYPE_STRUCT, it is the number of elements in the structure and
- * the number of values pointed to by \c fields.structure (below).
- */
- unsigned length;
-
- /**
- * Subtype of composite data types.
- */
- union {
- const struct glsl_type *array; /**< Type of array elements. */
- const struct glsl_type *parameters; /**< Parameters to function. */
- struct glsl_struct_field *structure; /**< List of struct fields. */
- } fields;
-
-
- /**
- * \name Pointers to various public type singletons
- */
- /*@{*/
- static const glsl_type *const error_type;
- static const glsl_type *const void_type;
- static const glsl_type *const int_type;
- static const glsl_type *const ivec4_type;
- static const glsl_type *const uint_type;
- static const glsl_type *const uvec2_type;
- static const glsl_type *const uvec3_type;
- static const glsl_type *const uvec4_type;
- static const glsl_type *const float_type;
- static const glsl_type *const vec2_type;
- static const glsl_type *const vec3_type;
- static const glsl_type *const vec4_type;
- static const glsl_type *const bool_type;
- static const glsl_type *const mat2_type;
- static const glsl_type *const mat2x3_type;
- static const glsl_type *const mat2x4_type;
- static const glsl_type *const mat3x2_type;
- static const glsl_type *const mat3_type;
- static const glsl_type *const mat3x4_type;
- static const glsl_type *const mat4x2_type;
- static const glsl_type *const mat4x3_type;
- static const glsl_type *const mat4_type;
- /*@}*/
-
-
- /**
- * For numeric and boolean derrived types returns the basic scalar type
- *
- * If the type is a numeric or boolean scalar, vector, or matrix type,
- * this function gets the scalar type of the individual components. For
- * all other types, including arrays of numeric or boolean types, the
- * error type is returned.
- */
- const glsl_type *get_base_type() const;
-
- /**
- * Query the type of elements in an array
- *
- * \return
- * Pointer to the type of elements in the array for array types, or \c NULL
- * for non-array types.
- */
- const glsl_type *element_type() const
- {
- return is_array() ? fields.array : NULL;
- }
-
- /**
- * Get the instance of a built-in scalar, vector, or matrix type
- */
- static const glsl_type *get_instance(unsigned base_type, unsigned rows,
- unsigned columns);
-
- /**
- * Get the instance of an array type
- */
- static const glsl_type *get_array_instance(const glsl_type *base,
- unsigned elements);
-
- /**
- * Get the instance of a record type
- */
- static const glsl_type *get_record_instance(const glsl_struct_field *fields,
- unsigned num_fields,
- const char *name);
-
- /**
- * Query the total number of scalars that make up a scalar, vector or matrix
- */
- unsigned components() const
- {
- return vector_elements * matrix_columns;
- }
-
- /**
- * Calculate the number of components slots required to hold this type
- *
- * This is used to determine how many uniform or varying locations a type
- * might occupy.
- */
- unsigned component_slots() const;
-
-
- /**
- * Query whether or not a type is a scalar (non-vector and non-matrix).
- */
- bool is_scalar() const
- {
- return (vector_elements == 1)
- && (base_type >= GLSL_TYPE_UINT)
- && (base_type <= GLSL_TYPE_BOOL);
- }
-
- /**
- * Query whether or not a type is a vector
- */
- bool is_vector() const
- {
- return (vector_elements > 1)
- && (matrix_columns == 1)
- && (base_type >= GLSL_TYPE_UINT)
- && (base_type <= GLSL_TYPE_BOOL);
- }
-
- /**
- * Query whether or not a type is a matrix
- */
- bool is_matrix() const
- {
- /* GLSL only has float matrices. */
- return (matrix_columns > 1) && (base_type == GLSL_TYPE_FLOAT);
- }
-
- /**
- * Query whether or not a type is a non-array numeric type
- */
- bool is_numeric() const
- {
- return (base_type >= GLSL_TYPE_UINT) && (base_type <= GLSL_TYPE_FLOAT);
- }
-
- /**
- * Query whether or not a type is an integral type
- */
- bool is_integer() const
- {
- return (base_type == GLSL_TYPE_UINT) || (base_type == GLSL_TYPE_INT);
- }
-
- /**
- * Query whether or not a type is a float type
- */
- bool is_float() const
- {
- return base_type == GLSL_TYPE_FLOAT;
- }
-
- /**
- * Query whether or not a type is a non-array boolean type
- */
- bool is_boolean() const
- {
- return base_type == GLSL_TYPE_BOOL;
- }
-
- /**
- * Query whether or not a type is a sampler
- */
- bool is_sampler() const
- {
- return base_type == GLSL_TYPE_SAMPLER;
- }
-
- /**
- * Query whether or not a type is an array
- */
- bool is_array() const
- {
- return base_type == GLSL_TYPE_ARRAY;
- }
-
- /**
- * Query whether or not a type is a record
- */
- bool is_record() const
- {
- return base_type == GLSL_TYPE_STRUCT;
- }
-
- /**
- * Query whether or not a type is the void type singleton.
- */
- bool is_void() const
- {
- return base_type == GLSL_TYPE_VOID;
- }
-
- /**
- * Query whether or not a type is the error type singleton.
- */
- bool is_error() const
- {
- return base_type == GLSL_TYPE_ERROR;
- }
-
- /**
- * Query the full type of a matrix row
- *
- * \return
- * If the type is not a matrix, \c glsl_type::error_type is returned.
- * Otherwise a type matching the rows of the matrix is returned.
- */
- const glsl_type *row_type() const
- {
- return is_matrix()
- ? get_instance(base_type, matrix_columns, 1)
- : error_type;
- }
-
- /**
- * Query the full type of a matrix column
- *
- * \return
- * If the type is not a matrix, \c glsl_type::error_type is returned.
- * Otherwise a type matching the columns of the matrix is returned.
- */
- const glsl_type *column_type() const
- {
- return is_matrix()
- ? get_instance(base_type, vector_elements, 1)
- : error_type;
- }
-
-
- /**
- * Get the type of a structure field
- *
- * \return
- * Pointer to the type of the named field. If the type is not a structure
- * or the named field does not exist, \c glsl_type::error_type is returned.
- */
- const glsl_type *field_type(const char *name) const;
-
-
- /**
- * Get the location of a filed within a record type
- */
- int field_index(const char *name) const;
-
-
- /**
- * Query the number of elements in an array type
- *
- * \return
- * The number of elements in the array for array types or -1 for non-array
- * types. If the number of elements in the array has not yet been declared,
- * zero is returned.
- */
- int array_size() const
- {
- return is_array() ? length : -1;
- }
-
-private:
- /**
- * ralloc context for all glsl_type allocations
- *
- * Set on the first call to \c glsl_type::new.
- */
- static void *mem_ctx;
-
- void init_ralloc_type_ctx(void);
-
- /** Constructor for vector and matrix types */
- glsl_type(GLenum gl_type,
- glsl_base_type base_type, unsigned vector_elements,
- unsigned matrix_columns, const char *name);
-
- /** Constructor for sampler types */
- glsl_type(GLenum gl_type,
- enum glsl_sampler_dim dim, bool shadow, bool array,
- unsigned type, const char *name);
-
- /** Constructor for record types */
- glsl_type(const glsl_struct_field *fields, unsigned num_fields,
- const char *name);
-
- /** Constructor for array types */
- glsl_type(const glsl_type *array, unsigned length);
-
- /** Hash table containing the known array types. */
- static struct hash_table *array_types;
-
- /** Hash table containing the known record types. */
- static struct hash_table *record_types;
-
- static int record_key_compare(const void *a, const void *b);
- static unsigned record_key_hash(const void *key);
-
- /**
- * \name Pointers to various type singletons
- */
- /*@{*/
- static const glsl_type _error_type;
- static const glsl_type _void_type;
- static const glsl_type builtin_core_types[];
- static const glsl_type builtin_structure_types[];
- static const glsl_type builtin_110_deprecated_structure_types[];
- static const glsl_type builtin_110_types[];
- static const glsl_type builtin_120_types[];
- static const glsl_type builtin_130_types[];
- static const glsl_type builtin_ARB_texture_rectangle_types[];
- static const glsl_type builtin_EXT_texture_array_types[];
- static const glsl_type builtin_EXT_texture_buffer_object_types[];
- /*@}*/
-
- /**
- * \name Methods to populate a symbol table with built-in types.
- *
- * \internal
- * This is one of the truely annoying things about C++. Methods that are
- * completely internal and private to a type still have to be advertised to
- * the world in a public header file.
- */
- /*@{*/
- static void generate_100ES_types(glsl_symbol_table *);
- static void generate_110_types(glsl_symbol_table *);
- static void generate_120_types(glsl_symbol_table *);
- static void generate_130_types(glsl_symbol_table *);
- static void generate_ARB_texture_rectangle_types(glsl_symbol_table *, bool);
- static void generate_EXT_texture_array_types(glsl_symbol_table *, bool);
- /*@}*/
-
- /**
- * \name Friend functions.
- *
- * These functions are friends because they must have C linkage and the
- * need to call various private methods or access various private static
- * data.
- */
- /*@{*/
- friend void _mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *);
- friend void _mesa_glsl_release_types(void);
- /*@}*/
-};
-
-struct glsl_struct_field {
- const struct glsl_type *type;
- const char *name;
-};
-
-#endif /* GLSL_TYPES_H */
+/* -*- c++ -*- */
+/*
+ * Copyright © 2009 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#pragma once
+#ifndef GLSL_TYPES_H
+#define GLSL_TYPES_H
+
+#include <string.h>
+#include <assert.h>
+
+extern "C" {
+#include "GL/gl.h"
+}
+
+#include "ralloc.h"
+
+struct _mesa_glsl_parse_state;
+struct glsl_symbol_table;
+
+extern "C" void
+_mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *state);
+
+extern "C" void
+_mesa_glsl_release_types(void);
+
+enum glsl_base_type {
+ GLSL_TYPE_UINT = 0,
+ GLSL_TYPE_INT,
+ GLSL_TYPE_FLOAT,
+ GLSL_TYPE_BOOL,
+ GLSL_TYPE_SAMPLER,
+ GLSL_TYPE_STRUCT,
+ GLSL_TYPE_ARRAY,
+ GLSL_TYPE_VOID,
+ GLSL_TYPE_ERROR
+};
+
+enum glsl_sampler_dim {
+ GLSL_SAMPLER_DIM_1D = 0,
+ GLSL_SAMPLER_DIM_2D,
+ GLSL_SAMPLER_DIM_3D,
+ GLSL_SAMPLER_DIM_CUBE,
+ GLSL_SAMPLER_DIM_RECT,
+ GLSL_SAMPLER_DIM_BUF
+};
+
+
+struct glsl_type {
+ GLenum gl_type;
+ glsl_base_type base_type;
+
+ unsigned sampler_dimensionality:3;
+ unsigned sampler_shadow:1;
+ unsigned sampler_array:1;
+ unsigned sampler_type:2; /**< Type of data returned using this sampler.
+ * only \c GLSL_TYPE_FLOAT, \c GLSL_TYPE_INT,
+ * and \c GLSL_TYPE_UINT are valid.
+ */
+
+ /* Callers of this ralloc-based new need not call delete. It's
+ * easier to just ralloc_free 'mem_ctx' (or any of its ancestors). */
+ static void* operator new(size_t size)
+ {
+ if (glsl_type::mem_ctx == NULL) {
+ glsl_type::mem_ctx = ralloc_context(NULL);
+ assert(glsl_type::mem_ctx != NULL);
+ }
+
+ void *type;
+
+ type = ralloc_size(glsl_type::mem_ctx, size);
+ assert(type != NULL);
+
+ return type;
+ }
+
+ /* If the user *does* call delete, that's OK, we will just
+ * ralloc_free in that case. */
+ static void operator delete(void *type)
+ {
+ ralloc_free(type);
+ }
+
+ /**
+ * \name Vector and matrix element counts
+ *
+ * For scalars, each of these values will be 1. For non-numeric types
+ * these will be 0.
+ */
+ /*@{*/
+ unsigned vector_elements:3; /**< 1, 2, 3, or 4 vector elements. */
+ unsigned matrix_columns:3; /**< 1, 2, 3, or 4 matrix columns. */
+ /*@}*/
+
+ /**
+ * Name of the data type
+ *
+ * This may be \c NULL for anonymous structures, for arrays, or for
+ * function types.
+ */
+ const char *name;
+
+ /**
+ * For \c GLSL_TYPE_ARRAY, this is the length of the array. For
+ * \c GLSL_TYPE_STRUCT, it is the number of elements in the structure and
+ * the number of values pointed to by \c fields.structure (below).
+ */
+ unsigned length;
+
+ /**
+ * Subtype of composite data types.
+ */
+ union {
+ const struct glsl_type *array; /**< Type of array elements. */
+ const struct glsl_type *parameters; /**< Parameters to function. */
+ struct glsl_struct_field *structure; /**< List of struct fields. */
+ } fields;
+
+
+ /**
+ * \name Pointers to various public type singletons
+ */
+ /*@{*/
+ static const glsl_type *const error_type;
+ static const glsl_type *const void_type;
+ static const glsl_type *const int_type;
+ static const glsl_type *const ivec4_type;
+ static const glsl_type *const uint_type;
+ static const glsl_type *const uvec2_type;
+ static const glsl_type *const uvec3_type;
+ static const glsl_type *const uvec4_type;
+ static const glsl_type *const float_type;
+ static const glsl_type *const vec2_type;
+ static const glsl_type *const vec3_type;
+ static const glsl_type *const vec4_type;
+ static const glsl_type *const bool_type;
+ static const glsl_type *const mat2_type;
+ static const glsl_type *const mat2x3_type;
+ static const glsl_type *const mat2x4_type;
+ static const glsl_type *const mat3x2_type;
+ static const glsl_type *const mat3_type;
+ static const glsl_type *const mat3x4_type;
+ static const glsl_type *const mat4x2_type;
+ static const glsl_type *const mat4x3_type;
+ static const glsl_type *const mat4_type;
+ /*@}*/
+
+
+ /**
+ * For numeric and boolean derrived types returns the basic scalar type
+ *
+ * If the type is a numeric or boolean scalar, vector, or matrix type,
+ * this function gets the scalar type of the individual components. For
+ * all other types, including arrays of numeric or boolean types, the
+ * error type is returned.
+ */
+ const glsl_type *get_base_type() const;
+
+ /**
+ * Query the type of elements in an array
+ *
+ * \return
+ * Pointer to the type of elements in the array for array types, or \c NULL
+ * for non-array types.
+ */
+ const glsl_type *element_type() const
+ {
+ return is_array() ? fields.array : NULL;
+ }
+
+ /**
+ * Get the instance of a built-in scalar, vector, or matrix type
+ */
+ static const glsl_type *get_instance(unsigned base_type, unsigned rows,
+ unsigned columns);
+
+ /**
+ * Get the instance of an array type
+ */
+ static const glsl_type *get_array_instance(const glsl_type *base,
+ unsigned elements);
+
+ /**
+ * Get the instance of a record type
+ */
+ static const glsl_type *get_record_instance(const glsl_struct_field *fields,
+ unsigned num_fields,
+ const char *name);
+
+ /**
+ * Query the total number of scalars that make up a scalar, vector or matrix
+ */
+ unsigned components() const
+ {
+ return vector_elements * matrix_columns;
+ }
+
+ /**
+ * Calculate the number of components slots required to hold this type
+ *
+ * This is used to determine how many uniform or varying locations a type
+ * might occupy.
+ */
+ unsigned component_slots() const;
+
+
+ /**
+ * Query whether or not a type is a scalar (non-vector and non-matrix).
+ */
+ bool is_scalar() const
+ {
+ return (vector_elements == 1)
+ && (base_type >= GLSL_TYPE_UINT)
+ && (base_type <= GLSL_TYPE_BOOL);
+ }
+
+ /**
+ * Query whether or not a type is a vector
+ */
+ bool is_vector() const
+ {
+ return (vector_elements > 1)
+ && (matrix_columns == 1)
+ && (base_type >= GLSL_TYPE_UINT)
+ && (base_type <= GLSL_TYPE_BOOL);
+ }
+
+ /**
+ * Query whether or not a type is a matrix
+ */
+ bool is_matrix() const
+ {
+ /* GLSL only has float matrices. */
+ return (matrix_columns > 1) && (base_type == GLSL_TYPE_FLOAT);
+ }
+
+ /**
+ * Query whether or not a type is a non-array numeric type
+ */
+ bool is_numeric() const
+ {
+ return (base_type >= GLSL_TYPE_UINT) && (base_type <= GLSL_TYPE_FLOAT);
+ }
+
+ /**
+ * Query whether or not a type is an integral type
+ */
+ bool is_integer() const
+ {
+ return (base_type == GLSL_TYPE_UINT) || (base_type == GLSL_TYPE_INT);
+ }
+
+ /**
+ * Query whether or not a type is a float type
+ */
+ bool is_float() const
+ {
+ return base_type == GLSL_TYPE_FLOAT;
+ }
+
+ /**
+ * Query whether or not a type is a non-array boolean type
+ */
+ bool is_boolean() const
+ {
+ return base_type == GLSL_TYPE_BOOL;
+ }
+
+ /**
+ * Query whether or not a type is a sampler
+ */
+ bool is_sampler() const
+ {
+ return base_type == GLSL_TYPE_SAMPLER;
+ }
+
+ /**
+ * Query whether or not a type is an array
+ */
+ bool is_array() const
+ {
+ return base_type == GLSL_TYPE_ARRAY;
+ }
+
+ /**
+ * Query whether or not a type is a record
+ */
+ bool is_record() const
+ {
+ return base_type == GLSL_TYPE_STRUCT;
+ }
+
+ /**
+ * Query whether or not a type is the void type singleton.
+ */
+ bool is_void() const
+ {
+ return base_type == GLSL_TYPE_VOID;
+ }
+
+ /**
+ * Query whether or not a type is the error type singleton.
+ */
+ bool is_error() const
+ {
+ return base_type == GLSL_TYPE_ERROR;
+ }
+
+ /**
+ * Query the full type of a matrix row
+ *
+ * \return
+ * If the type is not a matrix, \c glsl_type::error_type is returned.
+ * Otherwise a type matching the rows of the matrix is returned.
+ */
+ const glsl_type *row_type() const
+ {
+ return is_matrix()
+ ? get_instance(base_type, matrix_columns, 1)
+ : error_type;
+ }
+
+ /**
+ * Query the full type of a matrix column
+ *
+ * \return
+ * If the type is not a matrix, \c glsl_type::error_type is returned.
+ * Otherwise a type matching the columns of the matrix is returned.
+ */
+ const glsl_type *column_type() const
+ {
+ return is_matrix()
+ ? get_instance(base_type, vector_elements, 1)
+ : error_type;
+ }
+
+
+ /**
+ * Get the type of a structure field
+ *
+ * \return
+ * Pointer to the type of the named field. If the type is not a structure
+ * or the named field does not exist, \c glsl_type::error_type is returned.
+ */
+ const glsl_type *field_type(const char *name) const;
+
+
+ /**
+ * Get the location of a filed within a record type
+ */
+ int field_index(const char *name) const;
+
+
+ /**
+ * Query the number of elements in an array type
+ *
+ * \return
+ * The number of elements in the array for array types or -1 for non-array
+ * types. If the number of elements in the array has not yet been declared,
+ * zero is returned.
+ */
+ int array_size() const
+ {
+ return is_array() ? length : -1;
+ }
+
+private:
+ /**
+ * ralloc context for all glsl_type allocations
+ *
+ * Set on the first call to \c glsl_type::new.
+ */
+ static void *mem_ctx;
+
+ void init_ralloc_type_ctx(void);
+
+ /** Constructor for vector and matrix types */
+ glsl_type(GLenum gl_type,
+ glsl_base_type base_type, unsigned vector_elements,
+ unsigned matrix_columns, const char *name);
+
+ /** Constructor for sampler types */
+ glsl_type(GLenum gl_type,
+ enum glsl_sampler_dim dim, bool shadow, bool array,
+ unsigned type, const char *name);
+
+ /** Constructor for record types */
+ glsl_type(const glsl_struct_field *fields, unsigned num_fields,
+ const char *name);
+
+ /** Constructor for array types */
+ glsl_type(const glsl_type *array, unsigned length);
+
+ /** Hash table containing the known array types. */
+ static struct hash_table *array_types;
+
+ /** Hash table containing the known record types. */
+ static struct hash_table *record_types;
+
+ static int record_key_compare(const void *a, const void *b);
+ static unsigned record_key_hash(const void *key);
+
+ /**
+ * \name Pointers to various type singletons
+ */
+ /*@{*/
+ static const glsl_type _error_type;
+ static const glsl_type _void_type;
+ static const glsl_type builtin_core_types[];
+ static const glsl_type builtin_structure_types[];
+ static const glsl_type builtin_110_deprecated_structure_types[];
+ static const glsl_type builtin_110_types[];
+ static const glsl_type builtin_120_types[];
+ static const glsl_type builtin_130_types[];
+ static const glsl_type builtin_ARB_texture_rectangle_types[];
+ static const glsl_type builtin_EXT_texture_array_types[];
+ static const glsl_type builtin_EXT_texture_buffer_object_types[];
+ /*@}*/
+
+ /**
+ * \name Methods to populate a symbol table with built-in types.
+ *
+ * \internal
+ * This is one of the truely annoying things about C++. Methods that are
+ * completely internal and private to a type still have to be advertised to
+ * the world in a public header file.
+ */
+ /*@{*/
+ static void generate_100ES_types(glsl_symbol_table *);
+ static void generate_110_types(glsl_symbol_table *);
+ static void generate_120_types(glsl_symbol_table *);
+ static void generate_130_types(glsl_symbol_table *);
+ static void generate_ARB_texture_rectangle_types(glsl_symbol_table *, bool);
+ static void generate_EXT_texture_array_types(glsl_symbol_table *, bool);
+ /*@}*/
+
+ /**
+ * \name Friend functions.
+ *
+ * These functions are friends because they must have C linkage and the
+ * need to call various private methods or access various private static
+ * data.
+ */
+ /*@{*/
+ friend void _mesa_glsl_initialize_types(struct _mesa_glsl_parse_state *);
+ friend void _mesa_glsl_release_types(void);
+ /*@}*/
+};
+
+struct glsl_struct_field {
+ const struct glsl_type *type;
+ const char *name;
+};
+
+#endif /* GLSL_TYPES_H */
diff --git a/mesalib/src/glsl/hir_field_selection.cpp b/mesalib/src/glsl/hir_field_selection.cpp
index 3c33127b5..21f107405 100644
--- a/mesalib/src/glsl/hir_field_selection.cpp
+++ b/mesalib/src/glsl/hir_field_selection.cpp
@@ -1,102 +1,102 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include "ir.h"
-#include "program/symbol_table.h"
-#include "glsl_parser_extras.h"
-#include "ast.h"
-#include "glsl_types.h"
-
-ir_rvalue *
-_mesa_ast_field_selection_to_hir(const ast_expression *expr,
- exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- void *ctx = state;
- ir_rvalue *result = NULL;
- ir_rvalue *op;
-
- op = expr->subexpressions[0]->hir(instructions, state);
-
- /* There are two kinds of field selection. There is the selection of a
- * specific field from a structure, and there is the selection of a
- * swizzle / mask from a vector. Which is which is determined entirely
- * by the base type of the thing to which the field selection operator is
- * being applied.
- */
- YYLTYPE loc = expr->get_location();
- if (op->type->is_error()) {
- /* silently propagate the error */
- } else if (op->type->is_vector()) {
- ir_swizzle *swiz = ir_swizzle::create(op,
- expr->primary_expression.identifier,
- op->type->vector_elements);
- if (swiz != NULL) {
- result = swiz;
- } else {
- /* FINISHME: Logging of error messages should be moved into
- * FINISHME: ir_swizzle::create. This allows the generation of more
- * FINISHME: specific error messages.
- */
- _mesa_glsl_error(& loc, state, "Invalid swizzle / mask `%s'",
- expr->primary_expression.identifier);
- }
- } else if (op->type->base_type == GLSL_TYPE_STRUCT) {
- result = new(ctx) ir_dereference_record(op,
- expr->primary_expression.identifier);
-
- if (result->type->is_error()) {
- _mesa_glsl_error(& loc, state, "Cannot access field `%s' of "
- "structure",
- expr->primary_expression.identifier);
- }
- } else if (expr->subexpressions[1] != NULL) {
- /* Handle "method calls" in GLSL 1.20 - namely, array.length() */
- if (state->language_version < 120)
- _mesa_glsl_error(&loc, state, "Methods not supported in GLSL 1.10.");
-
- ast_expression *call = expr->subexpressions[1];
- assert(call->oper == ast_function_call);
-
- const char *method;
- method = call->subexpressions[0]->primary_expression.identifier;
-
- if (op->type->is_array() && strcmp(method, "length") == 0) {
- if (!call->expressions.is_empty())
- _mesa_glsl_error(&loc, state, "length method takes no arguments.");
-
- if (op->type->array_size() == 0)
- _mesa_glsl_error(&loc, state, "length called on unsized array.");
-
- result = new(ctx) ir_constant(op->type->array_size());
- } else {
- _mesa_glsl_error(&loc, state, "Unknown method: `%s'.", method);
- }
- } else {
- _mesa_glsl_error(& loc, state, "Cannot access field `%s' of "
- "non-structure / non-vector.",
- expr->primary_expression.identifier);
- }
-
- return result ? result : ir_call::get_error_instruction(ctx);
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include "ir.h"
+#include "program/symbol_table.h"
+#include "glsl_parser_extras.h"
+#include "ast.h"
+#include "glsl_types.h"
+
+ir_rvalue *
+_mesa_ast_field_selection_to_hir(const ast_expression *expr,
+ exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ void *ctx = state;
+ ir_rvalue *result = NULL;
+ ir_rvalue *op;
+
+ op = expr->subexpressions[0]->hir(instructions, state);
+
+ /* There are two kinds of field selection. There is the selection of a
+ * specific field from a structure, and there is the selection of a
+ * swizzle / mask from a vector. Which is which is determined entirely
+ * by the base type of the thing to which the field selection operator is
+ * being applied.
+ */
+ YYLTYPE loc = expr->get_location();
+ if (op->type->is_error()) {
+ /* silently propagate the error */
+ } else if (op->type->is_vector()) {
+ ir_swizzle *swiz = ir_swizzle::create(op,
+ expr->primary_expression.identifier,
+ op->type->vector_elements);
+ if (swiz != NULL) {
+ result = swiz;
+ } else {
+ /* FINISHME: Logging of error messages should be moved into
+ * FINISHME: ir_swizzle::create. This allows the generation of more
+ * FINISHME: specific error messages.
+ */
+ _mesa_glsl_error(& loc, state, "Invalid swizzle / mask `%s'",
+ expr->primary_expression.identifier);
+ }
+ } else if (op->type->base_type == GLSL_TYPE_STRUCT) {
+ result = new(ctx) ir_dereference_record(op,
+ expr->primary_expression.identifier);
+
+ if (result->type->is_error()) {
+ _mesa_glsl_error(& loc, state, "Cannot access field `%s' of "
+ "structure",
+ expr->primary_expression.identifier);
+ }
+ } else if (expr->subexpressions[1] != NULL) {
+ /* Handle "method calls" in GLSL 1.20 - namely, array.length() */
+ if (state->language_version < 120)
+ _mesa_glsl_error(&loc, state, "Methods not supported in GLSL 1.10.");
+
+ ast_expression *call = expr->subexpressions[1];
+ assert(call->oper == ast_function_call);
+
+ const char *method;
+ method = call->subexpressions[0]->primary_expression.identifier;
+
+ if (op->type->is_array() && strcmp(method, "length") == 0) {
+ if (!call->expressions.is_empty())
+ _mesa_glsl_error(&loc, state, "length method takes no arguments.");
+
+ if (op->type->array_size() == 0)
+ _mesa_glsl_error(&loc, state, "length called on unsized array.");
+
+ result = new(ctx) ir_constant(op->type->array_size());
+ } else {
+ _mesa_glsl_error(&loc, state, "Unknown method: `%s'.", method);
+ }
+ } else {
+ _mesa_glsl_error(& loc, state, "Cannot access field `%s' of "
+ "non-structure / non-vector.",
+ expr->primary_expression.identifier);
+ }
+
+ return result ? result : ir_call::get_error_instruction(ctx);
+}
diff --git a/mesalib/src/glsl/ir.h b/mesalib/src/glsl/ir.h
index f2f902c0a..fcf1931ff 100644
--- a/mesalib/src/glsl/ir.h
+++ b/mesalib/src/glsl/ir.h
@@ -1,1640 +1,1640 @@
-/* -*- c++ -*- */
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#pragma once
-#ifndef IR_H
-#define IR_H
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "ralloc.h"
-#include "glsl_types.h"
-#include "list.h"
-#include "ir_visitor.h"
-#include "ir_hierarchical_visitor.h"
-
-/**
- * \defgroup IR Intermediate representation nodes
- *
- * @{
- */
-
-/**
- * Class tags
- *
- * Each concrete class derived from \c ir_instruction has a value in this
- * enumerant. The value for the type is stored in \c ir_instruction::ir_type
- * by the constructor. While using type tags is not very C++, it is extremely
- * convenient. For example, during debugging you can simply inspect
- * \c ir_instruction::ir_type to find out the actual type of the object.
- *
- * In addition, it is possible to use a switch-statement based on \c
- * \c ir_instruction::ir_type to select different behavior for different object
- * types. For functions that have only slight differences for several object
- * types, this allows writing very straightforward, readable code.
- */
-enum ir_node_type {
- /**
- * Zero is unused so that the IR validator can detect cases where
- * \c ir_instruction::ir_type has not been initialized.
- */
- ir_type_unset,
- ir_type_variable,
- ir_type_assignment,
- ir_type_call,
- ir_type_constant,
- ir_type_dereference_array,
- ir_type_dereference_record,
- ir_type_dereference_variable,
- ir_type_discard,
- ir_type_expression,
- ir_type_function,
- ir_type_function_signature,
- ir_type_if,
- ir_type_loop,
- ir_type_loop_jump,
- ir_type_return,
- ir_type_swizzle,
- ir_type_texture,
- ir_type_max /**< maximum ir_type enum number, for validation */
-};
-
-/**
- * Base class of all IR instructions
- */
-class ir_instruction : public exec_node {
-public:
- enum ir_node_type ir_type;
- const struct glsl_type *type;
-
- /** ir_print_visitor helper for debugging. */
- void print(void) const;
-
- virtual void accept(ir_visitor *) = 0;
- virtual ir_visitor_status accept(ir_hierarchical_visitor *) = 0;
- virtual ir_instruction *clone(void *mem_ctx,
- struct hash_table *ht) const = 0;
-
- /**
- * \name IR instruction downcast functions
- *
- * These functions either cast the object to a derived class or return
- * \c NULL if the object's type does not match the specified derived class.
- * Additional downcast functions will be added as needed.
- */
- /*@{*/
- virtual class ir_variable * as_variable() { return NULL; }
- virtual class ir_function * as_function() { return NULL; }
- virtual class ir_dereference * as_dereference() { return NULL; }
- virtual class ir_dereference_array * as_dereference_array() { return NULL; }
- virtual class ir_dereference_variable *as_dereference_variable() { return NULL; }
- virtual class ir_expression * as_expression() { return NULL; }
- virtual class ir_rvalue * as_rvalue() { return NULL; }
- virtual class ir_loop * as_loop() { return NULL; }
- virtual class ir_assignment * as_assignment() { return NULL; }
- virtual class ir_call * as_call() { return NULL; }
- virtual class ir_return * as_return() { return NULL; }
- virtual class ir_if * as_if() { return NULL; }
- virtual class ir_swizzle * as_swizzle() { return NULL; }
- virtual class ir_constant * as_constant() { return NULL; }
- virtual class ir_discard * as_discard() { return NULL; }
- /*@}*/
-
-protected:
- ir_instruction()
- {
- ir_type = ir_type_unset;
- type = NULL;
- }
-};
-
-
-class ir_rvalue : public ir_instruction {
-public:
- virtual ir_rvalue *clone(void *mem_ctx, struct hash_table *) const = 0;
-
- virtual ir_constant *constant_expression_value() = 0;
-
- virtual ir_rvalue * as_rvalue()
- {
- return this;
- }
-
- ir_rvalue *as_rvalue_to_saturate();
-
- virtual bool is_lvalue()
- {
- return false;
- }
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced()
- {
- return NULL;
- }
-
-
- /**
- * If an r-value is a reference to a whole variable, get that variable
- *
- * \return
- * Pointer to a variable that is completely dereferenced by the r-value. If
- * the r-value is not a dereference or the dereference does not access the
- * entire variable (i.e., it's just one array element, struct field), \c NULL
- * is returned.
- */
- virtual ir_variable *whole_variable_referenced()
- {
- return NULL;
- }
-
- /**
- * Determine if an r-value has the value zero
- *
- * The base implementation of this function always returns \c false. The
- * \c ir_constant class over-rides this function to return \c true \b only
- * for vector and scalar types that have all elements set to the value
- * zero (or \c false for booleans).
- *
- * \sa ir_constant::has_value, ir_rvalue::is_one, ir_rvalue::is_negative_one
- */
- virtual bool is_zero() const;
-
- /**
- * Determine if an r-value has the value one
- *
- * The base implementation of this function always returns \c false. The
- * \c ir_constant class over-rides this function to return \c true \b only
- * for vector and scalar types that have all elements set to the value
- * one (or \c true for booleans).
- *
- * \sa ir_constant::has_value, ir_rvalue::is_zero, ir_rvalue::is_negative_one
- */
- virtual bool is_one() const;
-
- /**
- * Determine if an r-value has the value negative one
- *
- * The base implementation of this function always returns \c false. The
- * \c ir_constant class over-rides this function to return \c true \b only
- * for vector and scalar types that have all elements set to the value
- * negative one. For boolean times, the result is always \c false.
- *
- * \sa ir_constant::has_value, ir_rvalue::is_zero, ir_rvalue::is_one
- */
- virtual bool is_negative_one() const;
-
-protected:
- ir_rvalue();
-};
-
-
-/**
- * Variable storage classes
- */
-enum ir_variable_mode {
- ir_var_auto = 0, /**< Function local variables and globals. */
- ir_var_uniform, /**< Variable declared as a uniform. */
- ir_var_in,
- ir_var_out,
- ir_var_inout,
- ir_var_const_in, /**< "in" param that must be a constant expression */
- ir_var_system_value, /**< Ex: front-face, instance-id, etc. */
- ir_var_temporary /**< Temporary variable generated during compilation. */
-};
-
-enum ir_variable_interpolation {
- ir_var_smooth = 0,
- ir_var_flat,
- ir_var_noperspective
-};
-
-/**
- * \brief Layout qualifiers for gl_FragDepth.
- *
- * The AMD_conservative_depth extension allows gl_FragDepth to be redeclared
- * with a layout qualifier.
- */
-enum ir_depth_layout {
- ir_depth_layout_none, /**< No depth layout is specified. */
- ir_depth_layout_any,
- ir_depth_layout_greater,
- ir_depth_layout_less,
- ir_depth_layout_unchanged
-};
-
-/**
- * \brief Convert depth layout qualifier to string.
- */
-const char*
-depth_layout_string(ir_depth_layout layout);
-
-class ir_variable : public ir_instruction {
-public:
- ir_variable(const struct glsl_type *, const char *, ir_variable_mode);
-
- virtual ir_variable *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual ir_variable *as_variable()
- {
- return this;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
-
- /**
- * Get the string value for the interpolation qualifier
- *
- * \return The string that would be used in a shader to specify \c
- * mode will be returned.
- *
- * This function should only be used on a shader input or output variable.
- */
- const char *interpolation_string() const;
-
- /**
- * Calculate the number of slots required to hold this variable
- *
- * This is used to determine how many uniform or varying locations a variable
- * occupies. The count is in units of floating point components.
- */
- unsigned component_slots() const;
-
- /**
- * Delcared name of the variable
- */
- const char *name;
-
- /**
- * Highest element accessed with a constant expression array index
- *
- * Not used for non-array variables.
- */
- unsigned max_array_access;
-
- /**
- * Is the variable read-only?
- *
- * This is set for variables declared as \c const, shader inputs,
- * and uniforms.
- */
- unsigned read_only:1;
- unsigned centroid:1;
- unsigned invariant:1;
-
- /**
- * Has this variable been used for reading or writing?
- *
- * Several GLSL semantic checks require knowledge of whether or not a
- * variable has been used. For example, it is an error to redeclare a
- * variable as invariant after it has been used.
- */
- unsigned used:1;
-
- /**
- * Storage class of the variable.
- *
- * \sa ir_variable_mode
- */
- unsigned mode:3;
-
- /**
- * Interpolation mode for shader inputs / outputs
- *
- * \sa ir_variable_interpolation
- */
- unsigned interpolation:2;
-
- /**
- * Flag that the whole array is assignable
- *
- * In GLSL 1.20 and later whole arrays are assignable (and comparable for
- * equality). This flag enables this behavior.
- */
- unsigned array_lvalue:1;
-
- /**
- * \name ARB_fragment_coord_conventions
- * @{
- */
- unsigned origin_upper_left:1;
- unsigned pixel_center_integer:1;
- /*@}*/
-
- /**
- * \brief Layout qualifier for gl_FragDepth.
- *
- * This is not equal to \c ir_depth_layout_none if and only if this
- * variable is \c gl_FragDepth and a layout qualifier is specified.
- */
- ir_depth_layout depth_layout;
-
- /**
- * Was the location explicitly set in the shader?
- *
- * If the location is explicitly set in the shader, it \b cannot be changed
- * by the linker or by the API (e.g., calls to \c glBindAttribLocation have
- * no effect).
- */
- unsigned explicit_location:1;
-
- /**
- * Storage location of the base of this variable
- *
- * The precise meaning of this field depends on the nature of the variable.
- *
- * - Vertex shader input: one of the values from \c gl_vert_attrib.
- * - Vertex shader output: one of the values from \c gl_vert_result.
- * - Fragment shader input: one of the values from \c gl_frag_attrib.
- * - Fragment shader output: one of the values from \c gl_frag_result.
- * - Uniforms: Per-stage uniform slot number.
- * - Other: This field is not currently used.
- *
- * If the variable is a uniform, shader input, or shader output, and the
- * slot has not been assigned, the value will be -1.
- */
- int location;
-
- /**
- * Emit a warning if this variable is accessed.
- */
- const char *warn_extension;
-
- /**
- * Value assigned in the initializer of a variable declared "const"
- */
- ir_constant *constant_value;
-};
-
-
-/*@{*/
-/**
- * The representation of a function instance; may be the full definition or
- * simply a prototype.
- */
-class ir_function_signature : public ir_instruction {
- /* An ir_function_signature will be part of the list of signatures in
- * an ir_function.
- */
-public:
- ir_function_signature(const glsl_type *return_type);
-
- virtual ir_function_signature *clone(void *mem_ctx,
- struct hash_table *ht) const;
- ir_function_signature *clone_prototype(void *mem_ctx,
- struct hash_table *ht) const;
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- /**
- * Get the name of the function for which this is a signature
- */
- const char *function_name() const;
-
- /**
- * Get a handle to the function for which this is a signature
- *
- * There is no setter function, this function returns a \c const pointer,
- * and \c ir_function_signature::_function is private for a reason. The
- * only way to make a connection between a function and function signature
- * is via \c ir_function::add_signature. This helps ensure that certain
- * invariants (i.e., a function signature is in the list of signatures for
- * its \c _function) are met.
- *
- * \sa ir_function::add_signature
- */
- inline const class ir_function *function() const
- {
- return this->_function;
- }
-
- /**
- * Check whether the qualifiers match between this signature's parameters
- * and the supplied parameter list. If not, returns the name of the first
- * parameter with mismatched qualifiers (for use in error messages).
- */
- const char *qualifiers_match(exec_list *params);
-
- /**
- * Replace the current parameter list with the given one. This is useful
- * if the current information came from a prototype, and either has invalid
- * or missing parameter names.
- */
- void replace_parameters(exec_list *new_params);
-
- /**
- * Function return type.
- *
- * \note This discards the optional precision qualifier.
- */
- const struct glsl_type *return_type;
-
- /**
- * List of ir_variable of function parameters.
- *
- * This represents the storage. The paramaters passed in a particular
- * call will be in ir_call::actual_paramaters.
- */
- struct exec_list parameters;
-
- /** Whether or not this function has a body (which may be empty). */
- unsigned is_defined:1;
-
- /** Whether or not this function signature is a built-in. */
- unsigned is_builtin:1;
-
- /** Body of instructions in the function. */
- struct exec_list body;
-
-private:
- /** Function of which this signature is one overload. */
- class ir_function *_function;
-
- friend class ir_function;
-};
-
-
-/**
- * Header for tracking multiple overloaded functions with the same name.
- * Contains a list of ir_function_signatures representing each of the
- * actual functions.
- */
-class ir_function : public ir_instruction {
-public:
- ir_function(const char *name);
-
- virtual ir_function *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual ir_function *as_function()
- {
- return this;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- void add_signature(ir_function_signature *sig)
- {
- sig->_function = this;
- this->signatures.push_tail(sig);
- }
-
- /**
- * Get an iterator for the set of function signatures
- */
- exec_list_iterator iterator()
- {
- return signatures.iterator();
- }
-
- /**
- * Find a signature that matches a set of actual parameters, taking implicit
- * conversions into account.
- */
- ir_function_signature *matching_signature(const exec_list *actual_param);
-
- /**
- * Find a signature that exactly matches a set of actual parameters without
- * any implicit type conversions.
- */
- ir_function_signature *exact_matching_signature(const exec_list *actual_ps);
-
- /**
- * Name of the function.
- */
- const char *name;
-
- /** Whether or not this function has a signature that isn't a built-in. */
- bool has_user_signature();
-
- /**
- * List of ir_function_signature for each overloaded function with this name.
- */
- struct exec_list signatures;
-};
-
-inline const char *ir_function_signature::function_name() const
-{
- return this->_function->name;
-}
-/*@}*/
-
-
-/**
- * IR instruction representing high-level if-statements
- */
-class ir_if : public ir_instruction {
-public:
- ir_if(ir_rvalue *condition)
- : condition(condition)
- {
- ir_type = ir_type_if;
- }
-
- virtual ir_if *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual ir_if *as_if()
- {
- return this;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- ir_rvalue *condition;
- /** List of ir_instruction for the body of the then branch */
- exec_list then_instructions;
- /** List of ir_instruction for the body of the else branch */
- exec_list else_instructions;
-};
-
-
-/**
- * IR instruction representing a high-level loop structure.
- */
-class ir_loop : public ir_instruction {
-public:
- ir_loop();
-
- virtual ir_loop *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- virtual ir_loop *as_loop()
- {
- return this;
- }
-
- /**
- * Get an iterator for the instructions of the loop body
- */
- exec_list_iterator iterator()
- {
- return body_instructions.iterator();
- }
-
- /** List of ir_instruction that make up the body of the loop. */
- exec_list body_instructions;
-
- /**
- * \name Loop counter and controls
- *
- * Represents a loop like a FORTRAN \c do-loop.
- *
- * \note
- * If \c from and \c to are the same value, the loop will execute once.
- */
- /*@{*/
- ir_rvalue *from; /** Value of the loop counter on the first
- * iteration of the loop.
- */
- ir_rvalue *to; /** Value of the loop counter on the last
- * iteration of the loop.
- */
- ir_rvalue *increment;
- ir_variable *counter;
-
- /**
- * Comparison operation in the loop terminator.
- *
- * If any of the loop control fields are non-\c NULL, this field must be
- * one of \c ir_binop_less, \c ir_binop_greater, \c ir_binop_lequal,
- * \c ir_binop_gequal, \c ir_binop_equal, or \c ir_binop_nequal.
- */
- int cmp;
- /*@}*/
-};
-
-
-class ir_assignment : public ir_instruction {
-public:
- ir_assignment(ir_rvalue *lhs, ir_rvalue *rhs, ir_rvalue *condition);
-
- /**
- * Construct an assignment with an explicit write mask
- *
- * \note
- * Since a write mask is supplied, the LHS must already be a bare
- * \c ir_dereference. The cannot be any swizzles in the LHS.
- */
- ir_assignment(ir_dereference *lhs, ir_rvalue *rhs, ir_rvalue *condition,
- unsigned write_mask);
-
- virtual ir_assignment *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- virtual ir_assignment * as_assignment()
- {
- return this;
- }
-
- /**
- * Get a whole variable written by an assignment
- *
- * If the LHS of the assignment writes a whole variable, the variable is
- * returned. Otherwise \c NULL is returned. Examples of whole-variable
- * assignment are:
- *
- * - Assigning to a scalar
- * - Assigning to all components of a vector
- * - Whole array (or matrix) assignment
- * - Whole structure assignment
- */
- ir_variable *whole_variable_written();
-
- /**
- * Set the LHS of an assignment
- */
- void set_lhs(ir_rvalue *lhs);
-
- /**
- * Left-hand side of the assignment.
- *
- * This should be treated as read only. If you need to set the LHS of an
- * assignment, use \c ir_assignment::set_lhs.
- */
- ir_dereference *lhs;
-
- /**
- * Value being assigned
- */
- ir_rvalue *rhs;
-
- /**
- * Optional condition for the assignment.
- */
- ir_rvalue *condition;
-
-
- /**
- * Component mask written
- *
- * For non-vector types in the LHS, this field will be zero. For vector
- * types, a bit will be set for each component that is written. Note that
- * for \c vec2 and \c vec3 types only the lower bits will ever be set.
- *
- * A partially-set write mask means that each enabled channel gets
- * the value from a consecutive channel of the rhs. For example,
- * to write just .xyw of gl_FrontColor with color:
- *
- * (assign (constant bool (1)) (xyw)
- * (var_ref gl_FragColor)
- * (swiz xyw (var_ref color)))
- */
- unsigned write_mask:4;
-};
-
-/* Update ir_expression::num_operands() and operator_strs when
- * updating this list.
- */
-enum ir_expression_operation {
- ir_unop_bit_not,
- ir_unop_logic_not,
- ir_unop_neg,
- ir_unop_abs,
- ir_unop_sign,
- ir_unop_rcp,
- ir_unop_rsq,
- ir_unop_sqrt,
- ir_unop_exp, /**< Log base e on gentype */
- ir_unop_log, /**< Natural log on gentype */
- ir_unop_exp2,
- ir_unop_log2,
- ir_unop_f2i, /**< Float-to-integer conversion. */
- ir_unop_i2f, /**< Integer-to-float conversion. */
- ir_unop_f2b, /**< Float-to-boolean conversion */
- ir_unop_b2f, /**< Boolean-to-float conversion */
- ir_unop_i2b, /**< int-to-boolean conversion */
- ir_unop_b2i, /**< Boolean-to-int conversion */
- ir_unop_u2f, /**< Unsigned-to-float conversion. */
- ir_unop_any,
-
- /**
- * \name Unary floating-point rounding operations.
- */
- /*@{*/
- ir_unop_trunc,
- ir_unop_ceil,
- ir_unop_floor,
- ir_unop_fract,
- ir_unop_round_even,
- /*@}*/
-
- /**
- * \name Trigonometric operations.
- */
- /*@{*/
- ir_unop_sin,
- ir_unop_cos,
- ir_unop_sin_reduced, /**< Reduced range sin. [-pi, pi] */
- ir_unop_cos_reduced, /**< Reduced range cos. [-pi, pi] */
- /*@}*/
-
- /**
- * \name Partial derivatives.
- */
- /*@{*/
- ir_unop_dFdx,
- ir_unop_dFdy,
- /*@}*/
-
- ir_unop_noise,
-
- /**
- * A sentinel marking the last of the unary operations.
- */
- ir_last_unop = ir_unop_noise,
-
- ir_binop_add,
- ir_binop_sub,
- ir_binop_mul,
- ir_binop_div,
-
- /**
- * Takes one of two combinations of arguments:
- *
- * - mod(vecN, vecN)
- * - mod(vecN, float)
- *
- * Does not take integer types.
- */
- ir_binop_mod,
-
- /**
- * \name Binary comparison operators which return a boolean vector.
- * The type of both operands must be equal.
- */
- /*@{*/
- ir_binop_less,
- ir_binop_greater,
- ir_binop_lequal,
- ir_binop_gequal,
- ir_binop_equal,
- ir_binop_nequal,
- /**
- * Returns single boolean for whether all components of operands[0]
- * equal the components of operands[1].
- */
- ir_binop_all_equal,
- /**
- * Returns single boolean for whether any component of operands[0]
- * is not equal to the corresponding component of operands[1].
- */
- ir_binop_any_nequal,
- /*@}*/
-
- /**
- * \name Bit-wise binary operations.
- */
- /*@{*/
- ir_binop_lshift,
- ir_binop_rshift,
- ir_binop_bit_and,
- ir_binop_bit_xor,
- ir_binop_bit_or,
- /*@}*/
-
- ir_binop_logic_and,
- ir_binop_logic_xor,
- ir_binop_logic_or,
-
- ir_binop_dot,
- ir_binop_min,
- ir_binop_max,
-
- ir_binop_pow,
-
- /**
- * A sentinel marking the last of the binary operations.
- */
- ir_last_binop = ir_binop_pow,
-
- ir_quadop_vector,
-
- /**
- * A sentinel marking the last of all operations.
- */
- ir_last_opcode = ir_last_binop
-};
-
-class ir_expression : public ir_rvalue {
-public:
- /**
- * Constructor for unary operation expressions
- */
- ir_expression(int op, const struct glsl_type *type, ir_rvalue *);
- ir_expression(int op, ir_rvalue *);
-
- /**
- * Constructor for binary operation expressions
- */
- ir_expression(int op, const struct glsl_type *type,
- ir_rvalue *, ir_rvalue *);
- ir_expression(int op, ir_rvalue *op0, ir_rvalue *op1);
-
- /**
- * Constructor for quad operator expressions
- */
- ir_expression(int op, const struct glsl_type *type,
- ir_rvalue *, ir_rvalue *, ir_rvalue *, ir_rvalue *);
-
- virtual ir_expression *as_expression()
- {
- return this;
- }
-
- virtual ir_expression *clone(void *mem_ctx, struct hash_table *ht) const;
-
- /**
- * Attempt to constant-fold the expression
- *
- * If the expression cannot be constant folded, this method will return
- * \c NULL.
- */
- virtual ir_constant *constant_expression_value();
-
- /**
- * Determine the number of operands used by an expression
- */
- static unsigned int get_num_operands(ir_expression_operation);
-
- /**
- * Determine the number of operands used by an expression
- */
- unsigned int get_num_operands() const
- {
- return (this->operation == ir_quadop_vector)
- ? this->type->vector_elements : get_num_operands(operation);
- }
-
- /**
- * Return a string representing this expression's operator.
- */
- const char *operator_string();
-
- /**
- * Return a string representing this expression's operator.
- */
- static const char *operator_string(ir_expression_operation);
-
-
- /**
- * Do a reverse-lookup to translate the given string into an operator.
- */
- static ir_expression_operation get_operator(const char *);
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- ir_expression_operation operation;
- ir_rvalue *operands[4];
-};
-
-
-/**
- * IR instruction representing a function call
- */
-class ir_call : public ir_rvalue {
-public:
- ir_call(ir_function_signature *callee, exec_list *actual_parameters)
- : callee(callee)
- {
- ir_type = ir_type_call;
- assert(callee->return_type != NULL);
- type = callee->return_type;
- actual_parameters->move_nodes_to(& this->actual_parameters);
- }
-
- virtual ir_call *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual ir_call *as_call()
- {
- return this;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- /**
- * Get a generic ir_call object when an error occurs
- *
- * Any allocation will be performed with 'ctx' as ralloc owner.
- */
- static ir_call *get_error_instruction(void *ctx);
-
- /**
- * Get an iterator for the set of acutal parameters
- */
- exec_list_iterator iterator()
- {
- return actual_parameters.iterator();
- }
-
- /**
- * Get the name of the function being called.
- */
- const char *callee_name() const
- {
- return callee->function_name();
- }
-
- /**
- * Get the function signature bound to this function call
- */
- ir_function_signature *get_callee()
- {
- return callee;
- }
-
- /**
- * Set the function call target
- */
- void set_callee(ir_function_signature *sig);
-
- /**
- * Generates an inline version of the function before @ir,
- * returning the return value of the function.
- */
- ir_rvalue *generate_inline(ir_instruction *ir);
-
- /* List of ir_rvalue of paramaters passed in this call. */
- exec_list actual_parameters;
-
-private:
- ir_call()
- : callee(NULL)
- {
- this->ir_type = ir_type_call;
- }
-
- ir_function_signature *callee;
-};
-
-
-/**
- * \name Jump-like IR instructions.
- *
- * These include \c break, \c continue, \c return, and \c discard.
- */
-/*@{*/
-class ir_jump : public ir_instruction {
-protected:
- ir_jump()
- {
- ir_type = ir_type_unset;
- }
-};
-
-class ir_return : public ir_jump {
-public:
- ir_return()
- : value(NULL)
- {
- this->ir_type = ir_type_return;
- }
-
- ir_return(ir_rvalue *value)
- : value(value)
- {
- this->ir_type = ir_type_return;
- }
-
- virtual ir_return *clone(void *mem_ctx, struct hash_table *) const;
-
- virtual ir_return *as_return()
- {
- return this;
- }
-
- ir_rvalue *get_value() const
- {
- return value;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- ir_rvalue *value;
-};
-
-
-/**
- * Jump instructions used inside loops
- *
- * These include \c break and \c continue. The \c break within a loop is
- * different from the \c break within a switch-statement.
- *
- * \sa ir_switch_jump
- */
-class ir_loop_jump : public ir_jump {
-public:
- enum jump_mode {
- jump_break,
- jump_continue
- };
-
- ir_loop_jump(jump_mode mode)
- {
- this->ir_type = ir_type_loop_jump;
- this->mode = mode;
- this->loop = loop;
- }
-
- virtual ir_loop_jump *clone(void *mem_ctx, struct hash_table *) const;
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- bool is_break() const
- {
- return mode == jump_break;
- }
-
- bool is_continue() const
- {
- return mode == jump_continue;
- }
-
- /** Mode selector for the jump instruction. */
- enum jump_mode mode;
-private:
- /** Loop containing this break instruction. */
- ir_loop *loop;
-};
-
-/**
- * IR instruction representing discard statements.
- */
-class ir_discard : public ir_jump {
-public:
- ir_discard()
- {
- this->ir_type = ir_type_discard;
- this->condition = NULL;
- }
-
- ir_discard(ir_rvalue *cond)
- {
- this->ir_type = ir_type_discard;
- this->condition = cond;
- }
-
- virtual ir_discard *clone(void *mem_ctx, struct hash_table *ht) const;
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- virtual ir_discard *as_discard()
- {
- return this;
- }
-
- ir_rvalue *condition;
-};
-/*@}*/
-
-
-/**
- * Texture sampling opcodes used in ir_texture
- */
-enum ir_texture_opcode {
- ir_tex, /**< Regular texture look-up */
- ir_txb, /**< Texture look-up with LOD bias */
- ir_txl, /**< Texture look-up with explicit LOD */
- ir_txd, /**< Texture look-up with partial derivatvies */
- ir_txf /**< Texel fetch with explicit LOD */
-};
-
-
-/**
- * IR instruction to sample a texture
- *
- * The specific form of the IR instruction depends on the \c mode value
- * selected from \c ir_texture_opcodes. In the printed IR, these will
- * appear as:
- *
- * Texel offset (0 or an expression)
- * | Projection divisor
- * | | Shadow comparitor
- * | | |
- * v v v
- * (tex <sampler> <coordinate> 0 1 ( ))
- * (txb <sampler> <coordinate> 0 1 ( ) <bias>)
- * (txl <sampler> <coordinate> 0 1 ( ) <lod>)
- * (txd <sampler> <coordinate> 0 1 ( ) (dPdx dPdy))
- * (txf <sampler> <coordinate> 0 <lod>)
- */
-class ir_texture : public ir_rvalue {
-public:
- ir_texture(enum ir_texture_opcode op)
- : op(op), projector(NULL), shadow_comparitor(NULL), offset(NULL)
- {
- this->ir_type = ir_type_texture;
- }
-
- virtual ir_texture *clone(void *mem_ctx, struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- /**
- * Return a string representing the ir_texture_opcode.
- */
- const char *opcode_string();
-
- /** Set the sampler and infer the type. */
- void set_sampler(ir_dereference *sampler);
-
- /**
- * Do a reverse-lookup to translate a string into an ir_texture_opcode.
- */
- static ir_texture_opcode get_opcode(const char *);
-
- enum ir_texture_opcode op;
-
- /** Sampler to use for the texture access. */
- ir_dereference *sampler;
-
- /** Texture coordinate to sample */
- ir_rvalue *coordinate;
-
- /**
- * Value used for projective divide.
- *
- * If there is no projective divide (the common case), this will be
- * \c NULL. Optimization passes should check for this to point to a constant
- * of 1.0 and replace that with \c NULL.
- */
- ir_rvalue *projector;
-
- /**
- * Coordinate used for comparison on shadow look-ups.
- *
- * If there is no shadow comparison, this will be \c NULL. For the
- * \c ir_txf opcode, this *must* be \c NULL.
- */
- ir_rvalue *shadow_comparitor;
-
- /** Texel offset. */
- ir_rvalue *offset;
-
- union {
- ir_rvalue *lod; /**< Floating point LOD */
- ir_rvalue *bias; /**< Floating point LOD bias */
- struct {
- ir_rvalue *dPdx; /**< Partial derivative of coordinate wrt X */
- ir_rvalue *dPdy; /**< Partial derivative of coordinate wrt Y */
- } grad;
- } lod_info;
-};
-
-
-struct ir_swizzle_mask {
- unsigned x:2;
- unsigned y:2;
- unsigned z:2;
- unsigned w:2;
-
- /**
- * Number of components in the swizzle.
- */
- unsigned num_components:3;
-
- /**
- * Does the swizzle contain duplicate components?
- *
- * L-value swizzles cannot contain duplicate components.
- */
- unsigned has_duplicates:1;
-};
-
-
-class ir_swizzle : public ir_rvalue {
-public:
- ir_swizzle(ir_rvalue *, unsigned x, unsigned y, unsigned z, unsigned w,
- unsigned count);
-
- ir_swizzle(ir_rvalue *val, const unsigned *components, unsigned count);
-
- ir_swizzle(ir_rvalue *val, ir_swizzle_mask mask);
-
- virtual ir_swizzle *clone(void *mem_ctx, struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual ir_swizzle *as_swizzle()
- {
- return this;
- }
-
- /**
- * Construct an ir_swizzle from the textual representation. Can fail.
- */
- static ir_swizzle *create(ir_rvalue *, const char *, unsigned vector_length);
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- bool is_lvalue()
- {
- return val->is_lvalue() && !mask.has_duplicates;
- }
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced();
-
- ir_rvalue *val;
- ir_swizzle_mask mask;
-
-private:
- /**
- * Initialize the mask component of a swizzle
- *
- * This is used by the \c ir_swizzle constructors.
- */
- void init_mask(const unsigned *components, unsigned count);
-};
-
-
-class ir_dereference : public ir_rvalue {
-public:
- virtual ir_dereference *clone(void *mem_ctx, struct hash_table *) const = 0;
-
- virtual ir_dereference *as_dereference()
- {
- return this;
- }
-
- bool is_lvalue();
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced() = 0;
-};
-
-
-class ir_dereference_variable : public ir_dereference {
-public:
- ir_dereference_variable(ir_variable *var);
-
- virtual ir_dereference_variable *clone(void *mem_ctx,
- struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual ir_dereference_variable *as_dereference_variable()
- {
- return this;
- }
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced()
- {
- return this->var;
- }
-
- virtual ir_variable *whole_variable_referenced()
- {
- /* ir_dereference_variable objects always dereference the entire
- * variable. However, if this dereference is dereferenced by anything
- * else, the complete deferefernce chain is not a whole-variable
- * dereference. This method should only be called on the top most
- * ir_rvalue in a dereference chain.
- */
- return this->var;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- /**
- * Object being dereferenced.
- */
- ir_variable *var;
-};
-
-
-class ir_dereference_array : public ir_dereference {
-public:
- ir_dereference_array(ir_rvalue *value, ir_rvalue *array_index);
-
- ir_dereference_array(ir_variable *var, ir_rvalue *array_index);
-
- virtual ir_dereference_array *clone(void *mem_ctx,
- struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual ir_dereference_array *as_dereference_array()
- {
- return this;
- }
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced()
- {
- return this->array->variable_referenced();
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- ir_rvalue *array;
- ir_rvalue *array_index;
-
-private:
- void set_array(ir_rvalue *value);
-};
-
-
-class ir_dereference_record : public ir_dereference {
-public:
- ir_dereference_record(ir_rvalue *value, const char *field);
-
- ir_dereference_record(ir_variable *var, const char *field);
-
- virtual ir_dereference_record *clone(void *mem_ctx,
- struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- /**
- * Get the variable that is ultimately referenced by an r-value
- */
- virtual ir_variable *variable_referenced()
- {
- return this->record->variable_referenced();
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- ir_rvalue *record;
- const char *field;
-};
-
-
-/**
- * Data stored in an ir_constant
- */
-union ir_constant_data {
- unsigned u[16];
- int i[16];
- float f[16];
- bool b[16];
-};
-
-
-class ir_constant : public ir_rvalue {
-public:
- ir_constant(const struct glsl_type *type, const ir_constant_data *data);
- ir_constant(bool b);
- ir_constant(unsigned int u);
- ir_constant(int i);
- ir_constant(float f);
-
- /**
- * Construct an ir_constant from a list of ir_constant values
- */
- ir_constant(const struct glsl_type *type, exec_list *values);
-
- /**
- * Construct an ir_constant from a scalar component of another ir_constant
- *
- * The new \c ir_constant inherits the type of the component from the
- * source constant.
- *
- * \note
- * In the case of a matrix constant, the new constant is a scalar, \b not
- * a vector.
- */
- ir_constant(const ir_constant *c, unsigned i);
-
- /**
- * Return a new ir_constant of the specified type containing all zeros.
- */
- static ir_constant *zero(void *mem_ctx, const glsl_type *type);
-
- virtual ir_constant *clone(void *mem_ctx, struct hash_table *) const;
-
- virtual ir_constant *constant_expression_value();
-
- virtual ir_constant *as_constant()
- {
- return this;
- }
-
- virtual void accept(ir_visitor *v)
- {
- v->visit(this);
- }
-
- virtual ir_visitor_status accept(ir_hierarchical_visitor *);
-
- /**
- * Get a particular component of a constant as a specific type
- *
- * This is useful, for example, to get a value from an integer constant
- * as a float or bool. This appears frequently when constructors are
- * called with all constant parameters.
- */
- /*@{*/
- bool get_bool_component(unsigned i) const;
- float get_float_component(unsigned i) const;
- int get_int_component(unsigned i) const;
- unsigned get_uint_component(unsigned i) const;
- /*@}*/
-
- ir_constant *get_array_element(unsigned i) const;
-
- ir_constant *get_record_field(const char *name);
-
- /**
- * Determine whether a constant has the same value as another constant
- *
- * \sa ir_constant::is_zero, ir_constant::is_one,
- * ir_constant::is_negative_one
- */
- bool has_value(const ir_constant *) const;
-
- virtual bool is_zero() const;
- virtual bool is_one() const;
- virtual bool is_negative_one() const;
-
- /**
- * Value of the constant.
- *
- * The field used to back the values supplied by the constant is determined
- * by the type associated with the \c ir_instruction. Constants may be
- * scalars, vectors, or matrices.
- */
- union ir_constant_data value;
-
- /* Array elements */
- ir_constant **array_elements;
-
- /* Structure fields */
- exec_list components;
-
-private:
- /**
- * Parameterless constructor only used by the clone method
- */
- ir_constant(void);
-};
-
-/*@}*/
-
-/**
- * Apply a visitor to each IR node in a list
- */
-void
-visit_exec_list(exec_list *list, ir_visitor *visitor);
-
-/**
- * Validate invariants on each IR node in a list
- */
-void validate_ir_tree(exec_list *instructions);
-
-/**
- * Make a clone of each IR instruction in a list
- *
- * \param in List of IR instructions that are to be cloned
- * \param out List to hold the cloned instructions
- */
-void
-clone_ir_list(void *mem_ctx, exec_list *out, const exec_list *in);
-
-extern void
-_mesa_glsl_initialize_variables(exec_list *instructions,
- struct _mesa_glsl_parse_state *state);
-
-extern void
-_mesa_glsl_initialize_functions(_mesa_glsl_parse_state *state);
-
-extern void
-_mesa_glsl_release_functions(void);
-
-extern void
-reparent_ir(exec_list *list, void *mem_ctx);
-
-struct glsl_symbol_table;
-
-extern void
-import_prototypes(const exec_list *source, exec_list *dest,
- struct glsl_symbol_table *symbols, void *mem_ctx);
-
-extern bool
-ir_has_call(ir_instruction *ir);
-
-extern void
-do_set_program_inouts(exec_list *instructions, struct gl_program *prog);
-
-#endif /* IR_H */
+/* -*- c++ -*- */
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#pragma once
+#ifndef IR_H
+#define IR_H
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include "ralloc.h"
+#include "glsl_types.h"
+#include "list.h"
+#include "ir_visitor.h"
+#include "ir_hierarchical_visitor.h"
+
+/**
+ * \defgroup IR Intermediate representation nodes
+ *
+ * @{
+ */
+
+/**
+ * Class tags
+ *
+ * Each concrete class derived from \c ir_instruction has a value in this
+ * enumerant. The value for the type is stored in \c ir_instruction::ir_type
+ * by the constructor. While using type tags is not very C++, it is extremely
+ * convenient. For example, during debugging you can simply inspect
+ * \c ir_instruction::ir_type to find out the actual type of the object.
+ *
+ * In addition, it is possible to use a switch-statement based on \c
+ * \c ir_instruction::ir_type to select different behavior for different object
+ * types. For functions that have only slight differences for several object
+ * types, this allows writing very straightforward, readable code.
+ */
+enum ir_node_type {
+ /**
+ * Zero is unused so that the IR validator can detect cases where
+ * \c ir_instruction::ir_type has not been initialized.
+ */
+ ir_type_unset,
+ ir_type_variable,
+ ir_type_assignment,
+ ir_type_call,
+ ir_type_constant,
+ ir_type_dereference_array,
+ ir_type_dereference_record,
+ ir_type_dereference_variable,
+ ir_type_discard,
+ ir_type_expression,
+ ir_type_function,
+ ir_type_function_signature,
+ ir_type_if,
+ ir_type_loop,
+ ir_type_loop_jump,
+ ir_type_return,
+ ir_type_swizzle,
+ ir_type_texture,
+ ir_type_max /**< maximum ir_type enum number, for validation */
+};
+
+/**
+ * Base class of all IR instructions
+ */
+class ir_instruction : public exec_node {
+public:
+ enum ir_node_type ir_type;
+ const struct glsl_type *type;
+
+ /** ir_print_visitor helper for debugging. */
+ void print(void) const;
+
+ virtual void accept(ir_visitor *) = 0;
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *) = 0;
+ virtual ir_instruction *clone(void *mem_ctx,
+ struct hash_table *ht) const = 0;
+
+ /**
+ * \name IR instruction downcast functions
+ *
+ * These functions either cast the object to a derived class or return
+ * \c NULL if the object's type does not match the specified derived class.
+ * Additional downcast functions will be added as needed.
+ */
+ /*@{*/
+ virtual class ir_variable * as_variable() { return NULL; }
+ virtual class ir_function * as_function() { return NULL; }
+ virtual class ir_dereference * as_dereference() { return NULL; }
+ virtual class ir_dereference_array * as_dereference_array() { return NULL; }
+ virtual class ir_dereference_variable *as_dereference_variable() { return NULL; }
+ virtual class ir_expression * as_expression() { return NULL; }
+ virtual class ir_rvalue * as_rvalue() { return NULL; }
+ virtual class ir_loop * as_loop() { return NULL; }
+ virtual class ir_assignment * as_assignment() { return NULL; }
+ virtual class ir_call * as_call() { return NULL; }
+ virtual class ir_return * as_return() { return NULL; }
+ virtual class ir_if * as_if() { return NULL; }
+ virtual class ir_swizzle * as_swizzle() { return NULL; }
+ virtual class ir_constant * as_constant() { return NULL; }
+ virtual class ir_discard * as_discard() { return NULL; }
+ /*@}*/
+
+protected:
+ ir_instruction()
+ {
+ ir_type = ir_type_unset;
+ type = NULL;
+ }
+};
+
+
+class ir_rvalue : public ir_instruction {
+public:
+ virtual ir_rvalue *clone(void *mem_ctx, struct hash_table *) const = 0;
+
+ virtual ir_constant *constant_expression_value() = 0;
+
+ virtual ir_rvalue * as_rvalue()
+ {
+ return this;
+ }
+
+ ir_rvalue *as_rvalue_to_saturate();
+
+ virtual bool is_lvalue()
+ {
+ return false;
+ }
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced()
+ {
+ return NULL;
+ }
+
+
+ /**
+ * If an r-value is a reference to a whole variable, get that variable
+ *
+ * \return
+ * Pointer to a variable that is completely dereferenced by the r-value. If
+ * the r-value is not a dereference or the dereference does not access the
+ * entire variable (i.e., it's just one array element, struct field), \c NULL
+ * is returned.
+ */
+ virtual ir_variable *whole_variable_referenced()
+ {
+ return NULL;
+ }
+
+ /**
+ * Determine if an r-value has the value zero
+ *
+ * The base implementation of this function always returns \c false. The
+ * \c ir_constant class over-rides this function to return \c true \b only
+ * for vector and scalar types that have all elements set to the value
+ * zero (or \c false for booleans).
+ *
+ * \sa ir_constant::has_value, ir_rvalue::is_one, ir_rvalue::is_negative_one
+ */
+ virtual bool is_zero() const;
+
+ /**
+ * Determine if an r-value has the value one
+ *
+ * The base implementation of this function always returns \c false. The
+ * \c ir_constant class over-rides this function to return \c true \b only
+ * for vector and scalar types that have all elements set to the value
+ * one (or \c true for booleans).
+ *
+ * \sa ir_constant::has_value, ir_rvalue::is_zero, ir_rvalue::is_negative_one
+ */
+ virtual bool is_one() const;
+
+ /**
+ * Determine if an r-value has the value negative one
+ *
+ * The base implementation of this function always returns \c false. The
+ * \c ir_constant class over-rides this function to return \c true \b only
+ * for vector and scalar types that have all elements set to the value
+ * negative one. For boolean times, the result is always \c false.
+ *
+ * \sa ir_constant::has_value, ir_rvalue::is_zero, ir_rvalue::is_one
+ */
+ virtual bool is_negative_one() const;
+
+protected:
+ ir_rvalue();
+};
+
+
+/**
+ * Variable storage classes
+ */
+enum ir_variable_mode {
+ ir_var_auto = 0, /**< Function local variables and globals. */
+ ir_var_uniform, /**< Variable declared as a uniform. */
+ ir_var_in,
+ ir_var_out,
+ ir_var_inout,
+ ir_var_const_in, /**< "in" param that must be a constant expression */
+ ir_var_system_value, /**< Ex: front-face, instance-id, etc. */
+ ir_var_temporary /**< Temporary variable generated during compilation. */
+};
+
+enum ir_variable_interpolation {
+ ir_var_smooth = 0,
+ ir_var_flat,
+ ir_var_noperspective
+};
+
+/**
+ * \brief Layout qualifiers for gl_FragDepth.
+ *
+ * The AMD_conservative_depth extension allows gl_FragDepth to be redeclared
+ * with a layout qualifier.
+ */
+enum ir_depth_layout {
+ ir_depth_layout_none, /**< No depth layout is specified. */
+ ir_depth_layout_any,
+ ir_depth_layout_greater,
+ ir_depth_layout_less,
+ ir_depth_layout_unchanged
+};
+
+/**
+ * \brief Convert depth layout qualifier to string.
+ */
+const char*
+depth_layout_string(ir_depth_layout layout);
+
+class ir_variable : public ir_instruction {
+public:
+ ir_variable(const struct glsl_type *, const char *, ir_variable_mode);
+
+ virtual ir_variable *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual ir_variable *as_variable()
+ {
+ return this;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+
+ /**
+ * Get the string value for the interpolation qualifier
+ *
+ * \return The string that would be used in a shader to specify \c
+ * mode will be returned.
+ *
+ * This function should only be used on a shader input or output variable.
+ */
+ const char *interpolation_string() const;
+
+ /**
+ * Calculate the number of slots required to hold this variable
+ *
+ * This is used to determine how many uniform or varying locations a variable
+ * occupies. The count is in units of floating point components.
+ */
+ unsigned component_slots() const;
+
+ /**
+ * Delcared name of the variable
+ */
+ const char *name;
+
+ /**
+ * Highest element accessed with a constant expression array index
+ *
+ * Not used for non-array variables.
+ */
+ unsigned max_array_access;
+
+ /**
+ * Is the variable read-only?
+ *
+ * This is set for variables declared as \c const, shader inputs,
+ * and uniforms.
+ */
+ unsigned read_only:1;
+ unsigned centroid:1;
+ unsigned invariant:1;
+
+ /**
+ * Has this variable been used for reading or writing?
+ *
+ * Several GLSL semantic checks require knowledge of whether or not a
+ * variable has been used. For example, it is an error to redeclare a
+ * variable as invariant after it has been used.
+ */
+ unsigned used:1;
+
+ /**
+ * Storage class of the variable.
+ *
+ * \sa ir_variable_mode
+ */
+ unsigned mode:3;
+
+ /**
+ * Interpolation mode for shader inputs / outputs
+ *
+ * \sa ir_variable_interpolation
+ */
+ unsigned interpolation:2;
+
+ /**
+ * Flag that the whole array is assignable
+ *
+ * In GLSL 1.20 and later whole arrays are assignable (and comparable for
+ * equality). This flag enables this behavior.
+ */
+ unsigned array_lvalue:1;
+
+ /**
+ * \name ARB_fragment_coord_conventions
+ * @{
+ */
+ unsigned origin_upper_left:1;
+ unsigned pixel_center_integer:1;
+ /*@}*/
+
+ /**
+ * \brief Layout qualifier for gl_FragDepth.
+ *
+ * This is not equal to \c ir_depth_layout_none if and only if this
+ * variable is \c gl_FragDepth and a layout qualifier is specified.
+ */
+ ir_depth_layout depth_layout;
+
+ /**
+ * Was the location explicitly set in the shader?
+ *
+ * If the location is explicitly set in the shader, it \b cannot be changed
+ * by the linker or by the API (e.g., calls to \c glBindAttribLocation have
+ * no effect).
+ */
+ unsigned explicit_location:1;
+
+ /**
+ * Storage location of the base of this variable
+ *
+ * The precise meaning of this field depends on the nature of the variable.
+ *
+ * - Vertex shader input: one of the values from \c gl_vert_attrib.
+ * - Vertex shader output: one of the values from \c gl_vert_result.
+ * - Fragment shader input: one of the values from \c gl_frag_attrib.
+ * - Fragment shader output: one of the values from \c gl_frag_result.
+ * - Uniforms: Per-stage uniform slot number.
+ * - Other: This field is not currently used.
+ *
+ * If the variable is a uniform, shader input, or shader output, and the
+ * slot has not been assigned, the value will be -1.
+ */
+ int location;
+
+ /**
+ * Emit a warning if this variable is accessed.
+ */
+ const char *warn_extension;
+
+ /**
+ * Value assigned in the initializer of a variable declared "const"
+ */
+ ir_constant *constant_value;
+};
+
+
+/*@{*/
+/**
+ * The representation of a function instance; may be the full definition or
+ * simply a prototype.
+ */
+class ir_function_signature : public ir_instruction {
+ /* An ir_function_signature will be part of the list of signatures in
+ * an ir_function.
+ */
+public:
+ ir_function_signature(const glsl_type *return_type);
+
+ virtual ir_function_signature *clone(void *mem_ctx,
+ struct hash_table *ht) const;
+ ir_function_signature *clone_prototype(void *mem_ctx,
+ struct hash_table *ht) const;
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ /**
+ * Get the name of the function for which this is a signature
+ */
+ const char *function_name() const;
+
+ /**
+ * Get a handle to the function for which this is a signature
+ *
+ * There is no setter function, this function returns a \c const pointer,
+ * and \c ir_function_signature::_function is private for a reason. The
+ * only way to make a connection between a function and function signature
+ * is via \c ir_function::add_signature. This helps ensure that certain
+ * invariants (i.e., a function signature is in the list of signatures for
+ * its \c _function) are met.
+ *
+ * \sa ir_function::add_signature
+ */
+ inline const class ir_function *function() const
+ {
+ return this->_function;
+ }
+
+ /**
+ * Check whether the qualifiers match between this signature's parameters
+ * and the supplied parameter list. If not, returns the name of the first
+ * parameter with mismatched qualifiers (for use in error messages).
+ */
+ const char *qualifiers_match(exec_list *params);
+
+ /**
+ * Replace the current parameter list with the given one. This is useful
+ * if the current information came from a prototype, and either has invalid
+ * or missing parameter names.
+ */
+ void replace_parameters(exec_list *new_params);
+
+ /**
+ * Function return type.
+ *
+ * \note This discards the optional precision qualifier.
+ */
+ const struct glsl_type *return_type;
+
+ /**
+ * List of ir_variable of function parameters.
+ *
+ * This represents the storage. The paramaters passed in a particular
+ * call will be in ir_call::actual_paramaters.
+ */
+ struct exec_list parameters;
+
+ /** Whether or not this function has a body (which may be empty). */
+ unsigned is_defined:1;
+
+ /** Whether or not this function signature is a built-in. */
+ unsigned is_builtin:1;
+
+ /** Body of instructions in the function. */
+ struct exec_list body;
+
+private:
+ /** Function of which this signature is one overload. */
+ class ir_function *_function;
+
+ friend class ir_function;
+};
+
+
+/**
+ * Header for tracking multiple overloaded functions with the same name.
+ * Contains a list of ir_function_signatures representing each of the
+ * actual functions.
+ */
+class ir_function : public ir_instruction {
+public:
+ ir_function(const char *name);
+
+ virtual ir_function *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual ir_function *as_function()
+ {
+ return this;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ void add_signature(ir_function_signature *sig)
+ {
+ sig->_function = this;
+ this->signatures.push_tail(sig);
+ }
+
+ /**
+ * Get an iterator for the set of function signatures
+ */
+ exec_list_iterator iterator()
+ {
+ return signatures.iterator();
+ }
+
+ /**
+ * Find a signature that matches a set of actual parameters, taking implicit
+ * conversions into account.
+ */
+ ir_function_signature *matching_signature(const exec_list *actual_param);
+
+ /**
+ * Find a signature that exactly matches a set of actual parameters without
+ * any implicit type conversions.
+ */
+ ir_function_signature *exact_matching_signature(const exec_list *actual_ps);
+
+ /**
+ * Name of the function.
+ */
+ const char *name;
+
+ /** Whether or not this function has a signature that isn't a built-in. */
+ bool has_user_signature();
+
+ /**
+ * List of ir_function_signature for each overloaded function with this name.
+ */
+ struct exec_list signatures;
+};
+
+inline const char *ir_function_signature::function_name() const
+{
+ return this->_function->name;
+}
+/*@}*/
+
+
+/**
+ * IR instruction representing high-level if-statements
+ */
+class ir_if : public ir_instruction {
+public:
+ ir_if(ir_rvalue *condition)
+ : condition(condition)
+ {
+ ir_type = ir_type_if;
+ }
+
+ virtual ir_if *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual ir_if *as_if()
+ {
+ return this;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ ir_rvalue *condition;
+ /** List of ir_instruction for the body of the then branch */
+ exec_list then_instructions;
+ /** List of ir_instruction for the body of the else branch */
+ exec_list else_instructions;
+};
+
+
+/**
+ * IR instruction representing a high-level loop structure.
+ */
+class ir_loop : public ir_instruction {
+public:
+ ir_loop();
+
+ virtual ir_loop *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ virtual ir_loop *as_loop()
+ {
+ return this;
+ }
+
+ /**
+ * Get an iterator for the instructions of the loop body
+ */
+ exec_list_iterator iterator()
+ {
+ return body_instructions.iterator();
+ }
+
+ /** List of ir_instruction that make up the body of the loop. */
+ exec_list body_instructions;
+
+ /**
+ * \name Loop counter and controls
+ *
+ * Represents a loop like a FORTRAN \c do-loop.
+ *
+ * \note
+ * If \c from and \c to are the same value, the loop will execute once.
+ */
+ /*@{*/
+ ir_rvalue *from; /** Value of the loop counter on the first
+ * iteration of the loop.
+ */
+ ir_rvalue *to; /** Value of the loop counter on the last
+ * iteration of the loop.
+ */
+ ir_rvalue *increment;
+ ir_variable *counter;
+
+ /**
+ * Comparison operation in the loop terminator.
+ *
+ * If any of the loop control fields are non-\c NULL, this field must be
+ * one of \c ir_binop_less, \c ir_binop_greater, \c ir_binop_lequal,
+ * \c ir_binop_gequal, \c ir_binop_equal, or \c ir_binop_nequal.
+ */
+ int cmp;
+ /*@}*/
+};
+
+
+class ir_assignment : public ir_instruction {
+public:
+ ir_assignment(ir_rvalue *lhs, ir_rvalue *rhs, ir_rvalue *condition);
+
+ /**
+ * Construct an assignment with an explicit write mask
+ *
+ * \note
+ * Since a write mask is supplied, the LHS must already be a bare
+ * \c ir_dereference. The cannot be any swizzles in the LHS.
+ */
+ ir_assignment(ir_dereference *lhs, ir_rvalue *rhs, ir_rvalue *condition,
+ unsigned write_mask);
+
+ virtual ir_assignment *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ virtual ir_assignment * as_assignment()
+ {
+ return this;
+ }
+
+ /**
+ * Get a whole variable written by an assignment
+ *
+ * If the LHS of the assignment writes a whole variable, the variable is
+ * returned. Otherwise \c NULL is returned. Examples of whole-variable
+ * assignment are:
+ *
+ * - Assigning to a scalar
+ * - Assigning to all components of a vector
+ * - Whole array (or matrix) assignment
+ * - Whole structure assignment
+ */
+ ir_variable *whole_variable_written();
+
+ /**
+ * Set the LHS of an assignment
+ */
+ void set_lhs(ir_rvalue *lhs);
+
+ /**
+ * Left-hand side of the assignment.
+ *
+ * This should be treated as read only. If you need to set the LHS of an
+ * assignment, use \c ir_assignment::set_lhs.
+ */
+ ir_dereference *lhs;
+
+ /**
+ * Value being assigned
+ */
+ ir_rvalue *rhs;
+
+ /**
+ * Optional condition for the assignment.
+ */
+ ir_rvalue *condition;
+
+
+ /**
+ * Component mask written
+ *
+ * For non-vector types in the LHS, this field will be zero. For vector
+ * types, a bit will be set for each component that is written. Note that
+ * for \c vec2 and \c vec3 types only the lower bits will ever be set.
+ *
+ * A partially-set write mask means that each enabled channel gets
+ * the value from a consecutive channel of the rhs. For example,
+ * to write just .xyw of gl_FrontColor with color:
+ *
+ * (assign (constant bool (1)) (xyw)
+ * (var_ref gl_FragColor)
+ * (swiz xyw (var_ref color)))
+ */
+ unsigned write_mask:4;
+};
+
+/* Update ir_expression::num_operands() and operator_strs when
+ * updating this list.
+ */
+enum ir_expression_operation {
+ ir_unop_bit_not,
+ ir_unop_logic_not,
+ ir_unop_neg,
+ ir_unop_abs,
+ ir_unop_sign,
+ ir_unop_rcp,
+ ir_unop_rsq,
+ ir_unop_sqrt,
+ ir_unop_exp, /**< Log base e on gentype */
+ ir_unop_log, /**< Natural log on gentype */
+ ir_unop_exp2,
+ ir_unop_log2,
+ ir_unop_f2i, /**< Float-to-integer conversion. */
+ ir_unop_i2f, /**< Integer-to-float conversion. */
+ ir_unop_f2b, /**< Float-to-boolean conversion */
+ ir_unop_b2f, /**< Boolean-to-float conversion */
+ ir_unop_i2b, /**< int-to-boolean conversion */
+ ir_unop_b2i, /**< Boolean-to-int conversion */
+ ir_unop_u2f, /**< Unsigned-to-float conversion. */
+ ir_unop_any,
+
+ /**
+ * \name Unary floating-point rounding operations.
+ */
+ /*@{*/
+ ir_unop_trunc,
+ ir_unop_ceil,
+ ir_unop_floor,
+ ir_unop_fract,
+ ir_unop_round_even,
+ /*@}*/
+
+ /**
+ * \name Trigonometric operations.
+ */
+ /*@{*/
+ ir_unop_sin,
+ ir_unop_cos,
+ ir_unop_sin_reduced, /**< Reduced range sin. [-pi, pi] */
+ ir_unop_cos_reduced, /**< Reduced range cos. [-pi, pi] */
+ /*@}*/
+
+ /**
+ * \name Partial derivatives.
+ */
+ /*@{*/
+ ir_unop_dFdx,
+ ir_unop_dFdy,
+ /*@}*/
+
+ ir_unop_noise,
+
+ /**
+ * A sentinel marking the last of the unary operations.
+ */
+ ir_last_unop = ir_unop_noise,
+
+ ir_binop_add,
+ ir_binop_sub,
+ ir_binop_mul,
+ ir_binop_div,
+
+ /**
+ * Takes one of two combinations of arguments:
+ *
+ * - mod(vecN, vecN)
+ * - mod(vecN, float)
+ *
+ * Does not take integer types.
+ */
+ ir_binop_mod,
+
+ /**
+ * \name Binary comparison operators which return a boolean vector.
+ * The type of both operands must be equal.
+ */
+ /*@{*/
+ ir_binop_less,
+ ir_binop_greater,
+ ir_binop_lequal,
+ ir_binop_gequal,
+ ir_binop_equal,
+ ir_binop_nequal,
+ /**
+ * Returns single boolean for whether all components of operands[0]
+ * equal the components of operands[1].
+ */
+ ir_binop_all_equal,
+ /**
+ * Returns single boolean for whether any component of operands[0]
+ * is not equal to the corresponding component of operands[1].
+ */
+ ir_binop_any_nequal,
+ /*@}*/
+
+ /**
+ * \name Bit-wise binary operations.
+ */
+ /*@{*/
+ ir_binop_lshift,
+ ir_binop_rshift,
+ ir_binop_bit_and,
+ ir_binop_bit_xor,
+ ir_binop_bit_or,
+ /*@}*/
+
+ ir_binop_logic_and,
+ ir_binop_logic_xor,
+ ir_binop_logic_or,
+
+ ir_binop_dot,
+ ir_binop_min,
+ ir_binop_max,
+
+ ir_binop_pow,
+
+ /**
+ * A sentinel marking the last of the binary operations.
+ */
+ ir_last_binop = ir_binop_pow,
+
+ ir_quadop_vector,
+
+ /**
+ * A sentinel marking the last of all operations.
+ */
+ ir_last_opcode = ir_last_binop
+};
+
+class ir_expression : public ir_rvalue {
+public:
+ /**
+ * Constructor for unary operation expressions
+ */
+ ir_expression(int op, const struct glsl_type *type, ir_rvalue *);
+ ir_expression(int op, ir_rvalue *);
+
+ /**
+ * Constructor for binary operation expressions
+ */
+ ir_expression(int op, const struct glsl_type *type,
+ ir_rvalue *, ir_rvalue *);
+ ir_expression(int op, ir_rvalue *op0, ir_rvalue *op1);
+
+ /**
+ * Constructor for quad operator expressions
+ */
+ ir_expression(int op, const struct glsl_type *type,
+ ir_rvalue *, ir_rvalue *, ir_rvalue *, ir_rvalue *);
+
+ virtual ir_expression *as_expression()
+ {
+ return this;
+ }
+
+ virtual ir_expression *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ /**
+ * Attempt to constant-fold the expression
+ *
+ * If the expression cannot be constant folded, this method will return
+ * \c NULL.
+ */
+ virtual ir_constant *constant_expression_value();
+
+ /**
+ * Determine the number of operands used by an expression
+ */
+ static unsigned int get_num_operands(ir_expression_operation);
+
+ /**
+ * Determine the number of operands used by an expression
+ */
+ unsigned int get_num_operands() const
+ {
+ return (this->operation == ir_quadop_vector)
+ ? this->type->vector_elements : get_num_operands(operation);
+ }
+
+ /**
+ * Return a string representing this expression's operator.
+ */
+ const char *operator_string();
+
+ /**
+ * Return a string representing this expression's operator.
+ */
+ static const char *operator_string(ir_expression_operation);
+
+
+ /**
+ * Do a reverse-lookup to translate the given string into an operator.
+ */
+ static ir_expression_operation get_operator(const char *);
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ ir_expression_operation operation;
+ ir_rvalue *operands[4];
+};
+
+
+/**
+ * IR instruction representing a function call
+ */
+class ir_call : public ir_rvalue {
+public:
+ ir_call(ir_function_signature *callee, exec_list *actual_parameters)
+ : callee(callee)
+ {
+ ir_type = ir_type_call;
+ assert(callee->return_type != NULL);
+ type = callee->return_type;
+ actual_parameters->move_nodes_to(& this->actual_parameters);
+ }
+
+ virtual ir_call *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual ir_call *as_call()
+ {
+ return this;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ /**
+ * Get a generic ir_call object when an error occurs
+ *
+ * Any allocation will be performed with 'ctx' as ralloc owner.
+ */
+ static ir_call *get_error_instruction(void *ctx);
+
+ /**
+ * Get an iterator for the set of acutal parameters
+ */
+ exec_list_iterator iterator()
+ {
+ return actual_parameters.iterator();
+ }
+
+ /**
+ * Get the name of the function being called.
+ */
+ const char *callee_name() const
+ {
+ return callee->function_name();
+ }
+
+ /**
+ * Get the function signature bound to this function call
+ */
+ ir_function_signature *get_callee()
+ {
+ return callee;
+ }
+
+ /**
+ * Set the function call target
+ */
+ void set_callee(ir_function_signature *sig);
+
+ /**
+ * Generates an inline version of the function before @ir,
+ * returning the return value of the function.
+ */
+ ir_rvalue *generate_inline(ir_instruction *ir);
+
+ /* List of ir_rvalue of paramaters passed in this call. */
+ exec_list actual_parameters;
+
+private:
+ ir_call()
+ : callee(NULL)
+ {
+ this->ir_type = ir_type_call;
+ }
+
+ ir_function_signature *callee;
+};
+
+
+/**
+ * \name Jump-like IR instructions.
+ *
+ * These include \c break, \c continue, \c return, and \c discard.
+ */
+/*@{*/
+class ir_jump : public ir_instruction {
+protected:
+ ir_jump()
+ {
+ ir_type = ir_type_unset;
+ }
+};
+
+class ir_return : public ir_jump {
+public:
+ ir_return()
+ : value(NULL)
+ {
+ this->ir_type = ir_type_return;
+ }
+
+ ir_return(ir_rvalue *value)
+ : value(value)
+ {
+ this->ir_type = ir_type_return;
+ }
+
+ virtual ir_return *clone(void *mem_ctx, struct hash_table *) const;
+
+ virtual ir_return *as_return()
+ {
+ return this;
+ }
+
+ ir_rvalue *get_value() const
+ {
+ return value;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ ir_rvalue *value;
+};
+
+
+/**
+ * Jump instructions used inside loops
+ *
+ * These include \c break and \c continue. The \c break within a loop is
+ * different from the \c break within a switch-statement.
+ *
+ * \sa ir_switch_jump
+ */
+class ir_loop_jump : public ir_jump {
+public:
+ enum jump_mode {
+ jump_break,
+ jump_continue
+ };
+
+ ir_loop_jump(jump_mode mode)
+ {
+ this->ir_type = ir_type_loop_jump;
+ this->mode = mode;
+ this->loop = loop;
+ }
+
+ virtual ir_loop_jump *clone(void *mem_ctx, struct hash_table *) const;
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ bool is_break() const
+ {
+ return mode == jump_break;
+ }
+
+ bool is_continue() const
+ {
+ return mode == jump_continue;
+ }
+
+ /** Mode selector for the jump instruction. */
+ enum jump_mode mode;
+private:
+ /** Loop containing this break instruction. */
+ ir_loop *loop;
+};
+
+/**
+ * IR instruction representing discard statements.
+ */
+class ir_discard : public ir_jump {
+public:
+ ir_discard()
+ {
+ this->ir_type = ir_type_discard;
+ this->condition = NULL;
+ }
+
+ ir_discard(ir_rvalue *cond)
+ {
+ this->ir_type = ir_type_discard;
+ this->condition = cond;
+ }
+
+ virtual ir_discard *clone(void *mem_ctx, struct hash_table *ht) const;
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ virtual ir_discard *as_discard()
+ {
+ return this;
+ }
+
+ ir_rvalue *condition;
+};
+/*@}*/
+
+
+/**
+ * Texture sampling opcodes used in ir_texture
+ */
+enum ir_texture_opcode {
+ ir_tex, /**< Regular texture look-up */
+ ir_txb, /**< Texture look-up with LOD bias */
+ ir_txl, /**< Texture look-up with explicit LOD */
+ ir_txd, /**< Texture look-up with partial derivatvies */
+ ir_txf /**< Texel fetch with explicit LOD */
+};
+
+
+/**
+ * IR instruction to sample a texture
+ *
+ * The specific form of the IR instruction depends on the \c mode value
+ * selected from \c ir_texture_opcodes. In the printed IR, these will
+ * appear as:
+ *
+ * Texel offset (0 or an expression)
+ * | Projection divisor
+ * | | Shadow comparitor
+ * | | |
+ * v v v
+ * (tex <sampler> <coordinate> 0 1 ( ))
+ * (txb <sampler> <coordinate> 0 1 ( ) <bias>)
+ * (txl <sampler> <coordinate> 0 1 ( ) <lod>)
+ * (txd <sampler> <coordinate> 0 1 ( ) (dPdx dPdy))
+ * (txf <sampler> <coordinate> 0 <lod>)
+ */
+class ir_texture : public ir_rvalue {
+public:
+ ir_texture(enum ir_texture_opcode op)
+ : op(op), projector(NULL), shadow_comparitor(NULL), offset(NULL)
+ {
+ this->ir_type = ir_type_texture;
+ }
+
+ virtual ir_texture *clone(void *mem_ctx, struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ /**
+ * Return a string representing the ir_texture_opcode.
+ */
+ const char *opcode_string();
+
+ /** Set the sampler and infer the type. */
+ void set_sampler(ir_dereference *sampler);
+
+ /**
+ * Do a reverse-lookup to translate a string into an ir_texture_opcode.
+ */
+ static ir_texture_opcode get_opcode(const char *);
+
+ enum ir_texture_opcode op;
+
+ /** Sampler to use for the texture access. */
+ ir_dereference *sampler;
+
+ /** Texture coordinate to sample */
+ ir_rvalue *coordinate;
+
+ /**
+ * Value used for projective divide.
+ *
+ * If there is no projective divide (the common case), this will be
+ * \c NULL. Optimization passes should check for this to point to a constant
+ * of 1.0 and replace that with \c NULL.
+ */
+ ir_rvalue *projector;
+
+ /**
+ * Coordinate used for comparison on shadow look-ups.
+ *
+ * If there is no shadow comparison, this will be \c NULL. For the
+ * \c ir_txf opcode, this *must* be \c NULL.
+ */
+ ir_rvalue *shadow_comparitor;
+
+ /** Texel offset. */
+ ir_rvalue *offset;
+
+ union {
+ ir_rvalue *lod; /**< Floating point LOD */
+ ir_rvalue *bias; /**< Floating point LOD bias */
+ struct {
+ ir_rvalue *dPdx; /**< Partial derivative of coordinate wrt X */
+ ir_rvalue *dPdy; /**< Partial derivative of coordinate wrt Y */
+ } grad;
+ } lod_info;
+};
+
+
+struct ir_swizzle_mask {
+ unsigned x:2;
+ unsigned y:2;
+ unsigned z:2;
+ unsigned w:2;
+
+ /**
+ * Number of components in the swizzle.
+ */
+ unsigned num_components:3;
+
+ /**
+ * Does the swizzle contain duplicate components?
+ *
+ * L-value swizzles cannot contain duplicate components.
+ */
+ unsigned has_duplicates:1;
+};
+
+
+class ir_swizzle : public ir_rvalue {
+public:
+ ir_swizzle(ir_rvalue *, unsigned x, unsigned y, unsigned z, unsigned w,
+ unsigned count);
+
+ ir_swizzle(ir_rvalue *val, const unsigned *components, unsigned count);
+
+ ir_swizzle(ir_rvalue *val, ir_swizzle_mask mask);
+
+ virtual ir_swizzle *clone(void *mem_ctx, struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual ir_swizzle *as_swizzle()
+ {
+ return this;
+ }
+
+ /**
+ * Construct an ir_swizzle from the textual representation. Can fail.
+ */
+ static ir_swizzle *create(ir_rvalue *, const char *, unsigned vector_length);
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ bool is_lvalue()
+ {
+ return val->is_lvalue() && !mask.has_duplicates;
+ }
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced();
+
+ ir_rvalue *val;
+ ir_swizzle_mask mask;
+
+private:
+ /**
+ * Initialize the mask component of a swizzle
+ *
+ * This is used by the \c ir_swizzle constructors.
+ */
+ void init_mask(const unsigned *components, unsigned count);
+};
+
+
+class ir_dereference : public ir_rvalue {
+public:
+ virtual ir_dereference *clone(void *mem_ctx, struct hash_table *) const = 0;
+
+ virtual ir_dereference *as_dereference()
+ {
+ return this;
+ }
+
+ bool is_lvalue();
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced() = 0;
+};
+
+
+class ir_dereference_variable : public ir_dereference {
+public:
+ ir_dereference_variable(ir_variable *var);
+
+ virtual ir_dereference_variable *clone(void *mem_ctx,
+ struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual ir_dereference_variable *as_dereference_variable()
+ {
+ return this;
+ }
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced()
+ {
+ return this->var;
+ }
+
+ virtual ir_variable *whole_variable_referenced()
+ {
+ /* ir_dereference_variable objects always dereference the entire
+ * variable. However, if this dereference is dereferenced by anything
+ * else, the complete deferefernce chain is not a whole-variable
+ * dereference. This method should only be called on the top most
+ * ir_rvalue in a dereference chain.
+ */
+ return this->var;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ /**
+ * Object being dereferenced.
+ */
+ ir_variable *var;
+};
+
+
+class ir_dereference_array : public ir_dereference {
+public:
+ ir_dereference_array(ir_rvalue *value, ir_rvalue *array_index);
+
+ ir_dereference_array(ir_variable *var, ir_rvalue *array_index);
+
+ virtual ir_dereference_array *clone(void *mem_ctx,
+ struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual ir_dereference_array *as_dereference_array()
+ {
+ return this;
+ }
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced()
+ {
+ return this->array->variable_referenced();
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ ir_rvalue *array;
+ ir_rvalue *array_index;
+
+private:
+ void set_array(ir_rvalue *value);
+};
+
+
+class ir_dereference_record : public ir_dereference {
+public:
+ ir_dereference_record(ir_rvalue *value, const char *field);
+
+ ir_dereference_record(ir_variable *var, const char *field);
+
+ virtual ir_dereference_record *clone(void *mem_ctx,
+ struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ /**
+ * Get the variable that is ultimately referenced by an r-value
+ */
+ virtual ir_variable *variable_referenced()
+ {
+ return this->record->variable_referenced();
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ ir_rvalue *record;
+ const char *field;
+};
+
+
+/**
+ * Data stored in an ir_constant
+ */
+union ir_constant_data {
+ unsigned u[16];
+ int i[16];
+ float f[16];
+ bool b[16];
+};
+
+
+class ir_constant : public ir_rvalue {
+public:
+ ir_constant(const struct glsl_type *type, const ir_constant_data *data);
+ ir_constant(bool b);
+ ir_constant(unsigned int u);
+ ir_constant(int i);
+ ir_constant(float f);
+
+ /**
+ * Construct an ir_constant from a list of ir_constant values
+ */
+ ir_constant(const struct glsl_type *type, exec_list *values);
+
+ /**
+ * Construct an ir_constant from a scalar component of another ir_constant
+ *
+ * The new \c ir_constant inherits the type of the component from the
+ * source constant.
+ *
+ * \note
+ * In the case of a matrix constant, the new constant is a scalar, \b not
+ * a vector.
+ */
+ ir_constant(const ir_constant *c, unsigned i);
+
+ /**
+ * Return a new ir_constant of the specified type containing all zeros.
+ */
+ static ir_constant *zero(void *mem_ctx, const glsl_type *type);
+
+ virtual ir_constant *clone(void *mem_ctx, struct hash_table *) const;
+
+ virtual ir_constant *constant_expression_value();
+
+ virtual ir_constant *as_constant()
+ {
+ return this;
+ }
+
+ virtual void accept(ir_visitor *v)
+ {
+ v->visit(this);
+ }
+
+ virtual ir_visitor_status accept(ir_hierarchical_visitor *);
+
+ /**
+ * Get a particular component of a constant as a specific type
+ *
+ * This is useful, for example, to get a value from an integer constant
+ * as a float or bool. This appears frequently when constructors are
+ * called with all constant parameters.
+ */
+ /*@{*/
+ bool get_bool_component(unsigned i) const;
+ float get_float_component(unsigned i) const;
+ int get_int_component(unsigned i) const;
+ unsigned get_uint_component(unsigned i) const;
+ /*@}*/
+
+ ir_constant *get_array_element(unsigned i) const;
+
+ ir_constant *get_record_field(const char *name);
+
+ /**
+ * Determine whether a constant has the same value as another constant
+ *
+ * \sa ir_constant::is_zero, ir_constant::is_one,
+ * ir_constant::is_negative_one
+ */
+ bool has_value(const ir_constant *) const;
+
+ virtual bool is_zero() const;
+ virtual bool is_one() const;
+ virtual bool is_negative_one() const;
+
+ /**
+ * Value of the constant.
+ *
+ * The field used to back the values supplied by the constant is determined
+ * by the type associated with the \c ir_instruction. Constants may be
+ * scalars, vectors, or matrices.
+ */
+ union ir_constant_data value;
+
+ /* Array elements */
+ ir_constant **array_elements;
+
+ /* Structure fields */
+ exec_list components;
+
+private:
+ /**
+ * Parameterless constructor only used by the clone method
+ */
+ ir_constant(void);
+};
+
+/*@}*/
+
+/**
+ * Apply a visitor to each IR node in a list
+ */
+void
+visit_exec_list(exec_list *list, ir_visitor *visitor);
+
+/**
+ * Validate invariants on each IR node in a list
+ */
+void validate_ir_tree(exec_list *instructions);
+
+/**
+ * Make a clone of each IR instruction in a list
+ *
+ * \param in List of IR instructions that are to be cloned
+ * \param out List to hold the cloned instructions
+ */
+void
+clone_ir_list(void *mem_ctx, exec_list *out, const exec_list *in);
+
+extern void
+_mesa_glsl_initialize_variables(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state);
+
+extern void
+_mesa_glsl_initialize_functions(_mesa_glsl_parse_state *state);
+
+extern void
+_mesa_glsl_release_functions(void);
+
+extern void
+reparent_ir(exec_list *list, void *mem_ctx);
+
+struct glsl_symbol_table;
+
+extern void
+import_prototypes(const exec_list *source, exec_list *dest,
+ struct glsl_symbol_table *symbols, void *mem_ctx);
+
+extern bool
+ir_has_call(ir_instruction *ir);
+
+extern void
+do_set_program_inouts(exec_list *instructions, struct gl_program *prog);
+
+#endif /* IR_H */
diff --git a/mesalib/src/glsl/ir_constant_expression.cpp b/mesalib/src/glsl/ir_constant_expression.cpp
index 2a3084896..1d39e31fa 100644
--- a/mesalib/src/glsl/ir_constant_expression.cpp
+++ b/mesalib/src/glsl/ir_constant_expression.cpp
@@ -1,1372 +1,1372 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_constant_expression.cpp
- * Evaluate and process constant valued expressions
- *
- * In GLSL, constant valued expressions are used in several places. These
- * must be processed and evaluated very early in the compilation process.
- *
- * * Sizes of arrays
- * * Initializers for uniforms
- * * Initializers for \c const variables
- */
-
-#include <math.h>
-#include "main/core.h" /* for MAX2, MIN2, CLAMP */
-#include "ir.h"
-#include "ir_visitor.h"
-#include "glsl_types.h"
-
-static float
-dot(ir_constant *op0, ir_constant *op1)
-{
- assert(op0->type->is_float() && op1->type->is_float());
-
- float result = 0;
- for (unsigned c = 0; c < op0->type->components(); c++)
- result += op0->value.f[c] * op1->value.f[c];
-
- return result;
-}
-
-ir_constant *
-ir_expression::constant_expression_value()
-{
- if (this->type->is_error())
- return NULL;
-
- ir_constant *op[Elements(this->operands)] = { NULL, };
- ir_constant_data data;
-
- memset(&data, 0, sizeof(data));
-
- for (unsigned operand = 0; operand < this->get_num_operands(); operand++) {
- op[operand] = this->operands[operand]->constant_expression_value();
- if (!op[operand])
- return NULL;
- }
-
- if (op[1] != NULL)
- assert(op[0]->type->base_type == op[1]->type->base_type);
-
- bool op0_scalar = op[0]->type->is_scalar();
- bool op1_scalar = op[1] != NULL && op[1]->type->is_scalar();
-
- /* When iterating over a vector or matrix's components, we want to increase
- * the loop counter. However, for scalars, we want to stay at 0.
- */
- unsigned c0_inc = op0_scalar ? 0 : 1;
- unsigned c1_inc = op1_scalar ? 0 : 1;
- unsigned components;
- if (op1_scalar || !op[1]) {
- components = op[0]->type->components();
- } else {
- components = op[1]->type->components();
- }
-
- void *ctx = ralloc_parent(this);
-
- /* Handle array operations here, rather than below. */
- if (op[0]->type->is_array()) {
- assert(op[1] != NULL && op[1]->type->is_array());
- switch (this->operation) {
- case ir_binop_all_equal:
- return new(ctx) ir_constant(op[0]->has_value(op[1]));
- case ir_binop_any_nequal:
- return new(ctx) ir_constant(!op[0]->has_value(op[1]));
- default:
- break;
- }
- return NULL;
- }
-
- switch (this->operation) {
- case ir_unop_bit_not:
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_INT:
- for (unsigned c = 0; c < components; c++)
- data.i[c] = ~ op[0]->value.i[c];
- break;
- case GLSL_TYPE_UINT:
- for (unsigned c = 0; c < components; c++)
- data.u[c] = ~ op[0]->value.u[c];
- break;
- default:
- assert(0);
- }
- break;
-
- case ir_unop_logic_not:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.b[c] = !op[0]->value.b[c];
- break;
-
- case ir_unop_f2i:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.i[c] = (int) op[0]->value.f[c];
- }
- break;
- case ir_unop_i2f:
- assert(op[0]->type->base_type == GLSL_TYPE_INT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = (float) op[0]->value.i[c];
- }
- break;
- case ir_unop_u2f:
- assert(op[0]->type->base_type == GLSL_TYPE_UINT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = (float) op[0]->value.u[c];
- }
- break;
- case ir_unop_b2f:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = op[0]->value.b[c] ? 1.0F : 0.0F;
- }
- break;
- case ir_unop_f2b:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.b[c] = op[0]->value.f[c] != 0.0F ? true : false;
- }
- break;
- case ir_unop_b2i:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.u[c] = op[0]->value.b[c] ? 1 : 0;
- }
- break;
- case ir_unop_i2b:
- assert(op[0]->type->is_integer());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.b[c] = op[0]->value.u[c] ? true : false;
- }
- break;
-
- case ir_unop_any:
- assert(op[0]->type->is_boolean());
- data.b[0] = false;
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- if (op[0]->value.b[c])
- data.b[0] = true;
- }
- break;
-
- case ir_unop_trunc:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = truncf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_ceil:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = ceilf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_floor:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = floorf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_fract:
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = 0;
- break;
- case GLSL_TYPE_INT:
- data.i[c] = 0;
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[0]->value.f[c] - floor(op[0]->value.f[c]);
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_unop_sin:
- case ir_unop_sin_reduced:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = sinf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_cos:
- case ir_unop_cos_reduced:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = cosf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_neg:
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = -((int) op[0]->value.u[c]);
- break;
- case GLSL_TYPE_INT:
- data.i[c] = -op[0]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = -op[0]->value.f[c];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_unop_abs:
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c];
- if (data.i[c] < 0)
- data.i[c] = -data.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = fabs(op[0]->value.f[c]);
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_unop_sign:
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.i[c] > 0;
- break;
- case GLSL_TYPE_INT:
- data.i[c] = (op[0]->value.i[c] > 0) - (op[0]->value.i[c] < 0);
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = float((op[0]->value.f[c] > 0)-(op[0]->value.f[c] < 0));
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_unop_rcp:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_UINT:
- if (op[0]->value.u[c] != 0.0)
- data.u[c] = 1 / op[0]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- if (op[0]->value.i[c] != 0.0)
- data.i[c] = 1 / op[0]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- if (op[0]->value.f[c] != 0.0)
- data.f[c] = 1.0F / op[0]->value.f[c];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_unop_rsq:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = 1.0F / sqrtf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_sqrt:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = sqrtf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_exp:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = expf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_exp2:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = exp2f(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_log:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = logf(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_log2:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = log2f(op[0]->value.f[c]);
- }
- break;
-
- case ir_unop_dFdx:
- case ir_unop_dFdy:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = 0.0;
- }
- break;
-
- case ir_binop_pow:
- assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- data.f[c] = powf(op[0]->value.f[c], op[1]->value.f[c]);
- }
- break;
-
- case ir_binop_dot:
- data.f[0] = dot(op[0], op[1]);
- break;
-
- case ir_binop_min:
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = MIN2(op[0]->value.u[c0], op[1]->value.u[c1]);
- break;
- case GLSL_TYPE_INT:
- data.i[c] = MIN2(op[0]->value.i[c0], op[1]->value.i[c1]);
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = MIN2(op[0]->value.f[c0], op[1]->value.f[c1]);
- break;
- default:
- assert(0);
- }
- }
-
- break;
- case ir_binop_max:
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = MAX2(op[0]->value.u[c0], op[1]->value.u[c1]);
- break;
- case GLSL_TYPE_INT:
- data.i[c] = MAX2(op[0]->value.i[c0], op[1]->value.i[c1]);
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = MAX2(op[0]->value.f[c0], op[1]->value.f[c1]);
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_binop_add:
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] + op[1]->value.u[c1];
- break;
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] + op[1]->value.i[c1];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[0]->value.f[c0] + op[1]->value.f[c1];
- break;
- default:
- assert(0);
- }
- }
-
- break;
- case ir_binop_sub:
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] - op[1]->value.u[c1];
- break;
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] - op[1]->value.i[c1];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1];
- break;
- default:
- assert(0);
- }
- }
-
- break;
- case ir_binop_mul:
- /* Check for equal types, or unequal types involving scalars */
- if ((op[0]->type == op[1]->type && !op[0]->type->is_matrix())
- || op0_scalar || op1_scalar) {
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] * op[1]->value.u[c1];
- break;
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] * op[1]->value.i[c1];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[0]->value.f[c0] * op[1]->value.f[c1];
- break;
- default:
- assert(0);
- }
- }
- } else {
- assert(op[0]->type->is_matrix() || op[1]->type->is_matrix());
-
- /* Multiply an N-by-M matrix with an M-by-P matrix. Since either
- * matrix can be a GLSL vector, either N or P can be 1.
- *
- * For vec*mat, the vector is treated as a row vector. This
- * means the vector is a 1-row x M-column matrix.
- *
- * For mat*vec, the vector is treated as a column vector. Since
- * matrix_columns is 1 for vectors, this just works.
- */
- const unsigned n = op[0]->type->is_vector()
- ? 1 : op[0]->type->vector_elements;
- const unsigned m = op[1]->type->vector_elements;
- const unsigned p = op[1]->type->matrix_columns;
- for (unsigned j = 0; j < p; j++) {
- for (unsigned i = 0; i < n; i++) {
- for (unsigned k = 0; k < m; k++) {
- data.f[i+n*j] += op[0]->value.f[i+n*k]*op[1]->value.f[k+m*j];
- }
- }
- }
- }
-
- break;
- case ir_binop_div:
- /* FINISHME: Emit warning when division-by-zero is detected. */
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- if (op[1]->value.u[c1] == 0) {
- data.u[c] = 0;
- } else {
- data.u[c] = op[0]->value.u[c0] / op[1]->value.u[c1];
- }
- break;
- case GLSL_TYPE_INT:
- if (op[1]->value.i[c1] == 0) {
- data.i[c] = 0;
- } else {
- data.i[c] = op[0]->value.i[c0] / op[1]->value.i[c1];
- }
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[0]->value.f[c0] / op[1]->value.f[c1];
- break;
- default:
- assert(0);
- }
- }
-
- break;
- case ir_binop_mod:
- /* FINISHME: Emit warning when division-by-zero is detected. */
- assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- if (op[1]->value.u[c1] == 0) {
- data.u[c] = 0;
- } else {
- data.u[c] = op[0]->value.u[c0] % op[1]->value.u[c1];
- }
- break;
- case GLSL_TYPE_INT:
- if (op[1]->value.i[c1] == 0) {
- data.i[c] = 0;
- } else {
- data.i[c] = op[0]->value.i[c0] % op[1]->value.i[c1];
- }
- break;
- case GLSL_TYPE_FLOAT:
- /* We don't use fmod because it rounds toward zero; GLSL specifies
- * the use of floor.
- */
- data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1]
- * floorf(op[0]->value.f[c0] / op[1]->value.f[c1]);
- break;
- default:
- assert(0);
- }
- }
-
- break;
-
- case ir_binop_logic_and:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.b[c] = op[0]->value.b[c] && op[1]->value.b[c];
- break;
- case ir_binop_logic_xor:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.b[c] = op[0]->value.b[c] ^ op[1]->value.b[c];
- break;
- case ir_binop_logic_or:
- assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.b[c] = op[0]->value.b[c] || op[1]->value.b[c];
- break;
-
- case ir_binop_less:
- assert(op[0]->type == op[1]->type);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[0] = op[0]->value.u[0] < op[1]->value.u[0];
- break;
- case GLSL_TYPE_INT:
- data.b[0] = op[0]->value.i[0] < op[1]->value.i[0];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[0] = op[0]->value.f[0] < op[1]->value.f[0];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_greater:
- assert(op[0]->type == op[1]->type);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] > op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] > op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] > op[1]->value.f[c];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_lequal:
- assert(op[0]->type == op[1]->type);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[0] = op[0]->value.u[0] <= op[1]->value.u[0];
- break;
- case GLSL_TYPE_INT:
- data.b[0] = op[0]->value.i[0] <= op[1]->value.i[0];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[0] = op[0]->value.f[0] <= op[1]->value.f[0];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_gequal:
- assert(op[0]->type == op[1]->type);
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[0] = op[0]->value.u[0] >= op[1]->value.u[0];
- break;
- case GLSL_TYPE_INT:
- data.b[0] = op[0]->value.i[0] >= op[1]->value.i[0];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[0] = op[0]->value.f[0] >= op[1]->value.f[0];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_equal:
- assert(op[0]->type == op[1]->type);
- for (unsigned c = 0; c < components; c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] == op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] == op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] == op[1]->value.f[c];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_nequal:
- assert(op[0]->type != op[1]->type);
- for (unsigned c = 0; c < components; c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] != op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] != op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] != op[1]->value.f[c];
- break;
- default:
- assert(0);
- }
- }
- break;
- case ir_binop_all_equal:
- data.b[0] = op[0]->has_value(op[1]);
- break;
- case ir_binop_any_nequal:
- data.b[0] = !op[0]->has_value(op[1]);
- break;
-
- case ir_binop_lshift:
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- if (op[0]->type->base_type == GLSL_TYPE_INT &&
- op[1]->type->base_type == GLSL_TYPE_INT) {
- data.i[c] = op[0]->value.i[c0] << op[1]->value.i[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_INT &&
- op[1]->type->base_type == GLSL_TYPE_UINT) {
- data.i[c] = op[0]->value.i[c0] << op[1]->value.u[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
- op[1]->type->base_type == GLSL_TYPE_INT) {
- data.u[c] = op[0]->value.u[c0] << op[1]->value.i[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
- op[1]->type->base_type == GLSL_TYPE_UINT) {
- data.u[c] = op[0]->value.u[c0] << op[1]->value.u[c1];
- }
- }
- break;
-
- case ir_binop_rshift:
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- if (op[0]->type->base_type == GLSL_TYPE_INT &&
- op[1]->type->base_type == GLSL_TYPE_INT) {
- data.i[c] = op[0]->value.i[c0] >> op[1]->value.i[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_INT &&
- op[1]->type->base_type == GLSL_TYPE_UINT) {
- data.i[c] = op[0]->value.i[c0] >> op[1]->value.u[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
- op[1]->type->base_type == GLSL_TYPE_INT) {
- data.u[c] = op[0]->value.u[c0] >> op[1]->value.i[c1];
-
- } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
- op[1]->type->base_type == GLSL_TYPE_UINT) {
- data.u[c] = op[0]->value.u[c0] >> op[1]->value.u[c1];
- }
- }
- break;
-
- case ir_binop_bit_and:
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] & op[1]->value.i[c1];
- break;
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] & op[1]->value.u[c1];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_binop_bit_or:
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] | op[1]->value.i[c1];
- break;
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] | op[1]->value.u[c1];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_binop_bit_xor:
- for (unsigned c = 0, c0 = 0, c1 = 0;
- c < components;
- c0 += c0_inc, c1 += c1_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_INT:
- data.i[c] = op[0]->value.i[c0] ^ op[1]->value.i[c1];
- break;
- case GLSL_TYPE_UINT:
- data.u[c] = op[0]->value.u[c0] ^ op[1]->value.u[c1];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- case ir_quadop_vector:
- for (unsigned c = 0; c < this->type->vector_elements; c++) {
- switch (this->type->base_type) {
- case GLSL_TYPE_INT:
- data.i[c] = op[c]->value.i[0];
- break;
- case GLSL_TYPE_UINT:
- data.u[c] = op[c]->value.u[0];
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = op[c]->value.f[0];
- break;
- default:
- assert(0);
- }
- }
- break;
-
- default:
- /* FINISHME: Should handle all expression types. */
- return NULL;
- }
-
- return new(ctx) ir_constant(this->type, &data);
-}
-
-
-ir_constant *
-ir_texture::constant_expression_value()
-{
- /* texture lookups aren't constant expressions */
- return NULL;
-}
-
-
-ir_constant *
-ir_swizzle::constant_expression_value()
-{
- ir_constant *v = this->val->constant_expression_value();
-
- if (v != NULL) {
- ir_constant_data data = { { 0 } };
-
- const unsigned swiz_idx[4] = {
- this->mask.x, this->mask.y, this->mask.z, this->mask.w
- };
-
- for (unsigned i = 0; i < this->mask.num_components; i++) {
- switch (v->type->base_type) {
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT: data.u[i] = v->value.u[swiz_idx[i]]; break;
- case GLSL_TYPE_FLOAT: data.f[i] = v->value.f[swiz_idx[i]]; break;
- case GLSL_TYPE_BOOL: data.b[i] = v->value.b[swiz_idx[i]]; break;
- default: assert(!"Should not get here."); break;
- }
- }
-
- void *ctx = ralloc_parent(this);
- return new(ctx) ir_constant(this->type, &data);
- }
- return NULL;
-}
-
-
-ir_constant *
-ir_dereference_variable::constant_expression_value()
-{
- /* This may occur during compile and var->type is glsl_type::error_type */
- if (!var)
- return NULL;
-
- /* The constant_value of a uniform variable is its initializer,
- * not the lifetime constant value of the uniform.
- */
- if (var->mode == ir_var_uniform)
- return NULL;
-
- if (!var->constant_value)
- return NULL;
-
- return var->constant_value->clone(ralloc_parent(var), NULL);
-}
-
-
-ir_constant *
-ir_dereference_array::constant_expression_value()
-{
- ir_constant *array = this->array->constant_expression_value();
- ir_constant *idx = this->array_index->constant_expression_value();
-
- if ((array != NULL) && (idx != NULL)) {
- void *ctx = ralloc_parent(this);
- if (array->type->is_matrix()) {
- /* Array access of a matrix results in a vector.
- */
- const unsigned column = idx->value.u[0];
-
- const glsl_type *const column_type = array->type->column_type();
-
- /* Offset in the constant matrix to the first element of the column
- * to be extracted.
- */
- const unsigned mat_idx = column * column_type->vector_elements;
-
- ir_constant_data data = { { 0 } };
-
- switch (column_type->base_type) {
- case GLSL_TYPE_UINT:
- case GLSL_TYPE_INT:
- for (unsigned i = 0; i < column_type->vector_elements; i++)
- data.u[i] = array->value.u[mat_idx + i];
-
- break;
-
- case GLSL_TYPE_FLOAT:
- for (unsigned i = 0; i < column_type->vector_elements; i++)
- data.f[i] = array->value.f[mat_idx + i];
-
- break;
-
- default:
- assert(!"Should not get here.");
- break;
- }
-
- return new(ctx) ir_constant(column_type, &data);
- } else if (array->type->is_vector()) {
- const unsigned component = idx->value.u[0];
-
- return new(ctx) ir_constant(array, component);
- } else {
- const unsigned index = idx->value.u[0];
- return array->get_array_element(index)->clone(ctx, NULL);
- }
- }
- return NULL;
-}
-
-
-ir_constant *
-ir_dereference_record::constant_expression_value()
-{
- ir_constant *v = this->record->constant_expression_value();
-
- return (v != NULL) ? v->get_record_field(this->field) : NULL;
-}
-
-
-ir_constant *
-ir_assignment::constant_expression_value()
-{
- /* FINISHME: Handle CEs involving assignment (return RHS) */
- return NULL;
-}
-
-
-ir_constant *
-ir_constant::constant_expression_value()
-{
- return this;
-}
-
-
-ir_constant *
-ir_call::constant_expression_value()
-{
- if (this->type == glsl_type::error_type)
- return NULL;
-
- /* From the GLSL 1.20 spec, page 23:
- * "Function calls to user-defined functions (non-built-in functions)
- * cannot be used to form constant expressions."
- */
- if (!this->callee->is_builtin)
- return NULL;
-
- unsigned num_parameters = 0;
-
- /* Check if all parameters are constant */
- ir_constant *op[3];
- foreach_list(n, &this->actual_parameters) {
- ir_constant *constant = ((ir_rvalue *) n)->constant_expression_value();
- if (constant == NULL)
- return NULL;
-
- op[num_parameters] = constant;
-
- assert(num_parameters < 3);
- num_parameters++;
- }
-
- /* Individual cases below can either:
- * - Assign "expr" a new ir_expression to evaluate (for basic opcodes)
- * - Fill "data" with appopriate constant data
- * - Return an ir_constant directly.
- */
- void *mem_ctx = ralloc_parent(this);
- ir_expression *expr = NULL;
-
- ir_constant_data data;
- memset(&data, 0, sizeof(data));
-
- const char *callee = this->callee_name();
- if (strcmp(callee, "abs") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_abs, type, op[0], NULL);
- } else if (strcmp(callee, "all") == 0) {
- assert(op[0]->type->is_boolean());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- if (!op[0]->value.b[c])
- return new(mem_ctx) ir_constant(false);
- }
- return new(mem_ctx) ir_constant(true);
- } else if (strcmp(callee, "any") == 0) {
- assert(op[0]->type->is_boolean());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- if (op[0]->value.b[c])
- return new(mem_ctx) ir_constant(true);
- }
- return new(mem_ctx) ir_constant(false);
- } else if (strcmp(callee, "acos") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = acosf(op[0]->value.f[c]);
- } else if (strcmp(callee, "acosh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = acoshf(op[0]->value.f[c]);
- } else if (strcmp(callee, "asin") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = asinf(op[0]->value.f[c]);
- } else if (strcmp(callee, "asinh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = asinhf(op[0]->value.f[c]);
- } else if (strcmp(callee, "atan") == 0) {
- assert(op[0]->type->is_float());
- if (num_parameters == 2) {
- assert(op[1]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = atan2f(op[0]->value.f[c], op[1]->value.f[c]);
- } else {
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = atanf(op[0]->value.f[c]);
- }
- } else if (strcmp(callee, "atanh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = atanhf(op[0]->value.f[c]);
- } else if (strcmp(callee, "dFdx") == 0 || strcmp(callee, "dFdy") == 0) {
- return ir_constant::zero(mem_ctx, this->type);
- } else if (strcmp(callee, "ceil") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_ceil, type, op[0], NULL);
- } else if (strcmp(callee, "clamp") == 0) {
- assert(num_parameters == 3);
- unsigned c1_inc = op[1]->type->is_scalar() ? 0 : 1;
- unsigned c2_inc = op[2]->type->is_scalar() ? 0 : 1;
- for (unsigned c = 0, c1 = 0, c2 = 0;
- c < op[0]->type->components();
- c1 += c1_inc, c2 += c2_inc, c++) {
-
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.u[c] = CLAMP(op[0]->value.u[c], op[1]->value.u[c1],
- op[2]->value.u[c2]);
- break;
- case GLSL_TYPE_INT:
- data.i[c] = CLAMP(op[0]->value.i[c], op[1]->value.i[c1],
- op[2]->value.i[c2]);
- break;
- case GLSL_TYPE_FLOAT:
- data.f[c] = CLAMP(op[0]->value.f[c], op[1]->value.f[c1],
- op[2]->value.f[c2]);
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "cos") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_cos, type, op[0], NULL);
- } else if (strcmp(callee, "cosh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = coshf(op[0]->value.f[c]);
- } else if (strcmp(callee, "cross") == 0) {
- assert(op[0]->type == glsl_type::vec3_type);
- assert(op[1]->type == glsl_type::vec3_type);
- data.f[0] = (op[0]->value.f[1] * op[1]->value.f[2] -
- op[1]->value.f[1] * op[0]->value.f[2]);
- data.f[1] = (op[0]->value.f[2] * op[1]->value.f[0] -
- op[1]->value.f[2] * op[0]->value.f[0]);
- data.f[2] = (op[0]->value.f[0] * op[1]->value.f[1] -
- op[1]->value.f[0] * op[0]->value.f[1]);
- } else if (strcmp(callee, "degrees") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = 180.0F / M_PI * op[0]->value.f[c];
- } else if (strcmp(callee, "distance") == 0) {
- assert(op[0]->type->is_float() && op[1]->type->is_float());
- float length_squared = 0.0;
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- float t = op[0]->value.f[c] - op[1]->value.f[c];
- length_squared += t * t;
- }
- return new(mem_ctx) ir_constant(sqrtf(length_squared));
- } else if (strcmp(callee, "dot") == 0) {
- return new(mem_ctx) ir_constant(dot(op[0], op[1]));
- } else if (strcmp(callee, "equal") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] == op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] == op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] == op[1]->value.f[c];
- break;
- case GLSL_TYPE_BOOL:
- data.b[c] = op[0]->value.b[c] == op[1]->value.b[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "exp") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_exp, type, op[0], NULL);
- } else if (strcmp(callee, "exp2") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_exp2, type, op[0], NULL);
- } else if (strcmp(callee, "faceforward") == 0) {
- if (dot(op[2], op[1]) < 0)
- return op[0];
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = -op[0]->value.f[c];
- } else if (strcmp(callee, "floor") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_floor, type, op[0], NULL);
- } else if (strcmp(callee, "fract") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_fract, type, op[0], NULL);
- } else if (strcmp(callee, "fwidth") == 0) {
- return ir_constant::zero(mem_ctx, this->type);
- } else if (strcmp(callee, "greaterThan") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] > op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] > op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] > op[1]->value.f[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "greaterThanEqual") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] >= op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] >= op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] >= op[1]->value.f[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "inversesqrt") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_rsq, type, op[0], NULL);
- } else if (strcmp(callee, "length") == 0) {
- return new(mem_ctx) ir_constant(sqrtf(dot(op[0], op[0])));
- } else if (strcmp(callee, "lessThan") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] < op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] < op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] < op[1]->value.f[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "lessThanEqual") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] <= op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] <= op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] <= op[1]->value.f[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "log") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_log, type, op[0], NULL);
- } else if (strcmp(callee, "log2") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_log2, type, op[0], NULL);
- } else if (strcmp(callee, "matrixCompMult") == 0) {
- assert(op[0]->type->is_float() && op[1]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = op[0]->value.f[c] * op[1]->value.f[c];
- } else if (strcmp(callee, "max") == 0) {
- expr = new(mem_ctx) ir_expression(ir_binop_max, type, op[0], op[1]);
- } else if (strcmp(callee, "min") == 0) {
- expr = new(mem_ctx) ir_expression(ir_binop_min, type, op[0], op[1]);
- } else if (strcmp(callee, "mix") == 0) {
- assert(op[0]->type->is_float() && op[1]->type->is_float());
- if (op[2]->type->is_float()) {
- unsigned c2_inc = op[2]->type->is_scalar() ? 0 : 1;
- unsigned components = op[0]->type->components();
- for (unsigned c = 0, c2 = 0; c < components; c2 += c2_inc, c++) {
- data.f[c] = op[0]->value.f[c] * (1 - op[2]->value.f[c2]) +
- op[1]->value.f[c] * op[2]->value.f[c2];
- }
- } else {
- assert(op[2]->type->is_boolean());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = op[op[2]->value.b[c] ? 1 : 0]->value.f[c];
- }
- } else if (strcmp(callee, "mod") == 0) {
- expr = new(mem_ctx) ir_expression(ir_binop_mod, type, op[0], op[1]);
- } else if (strcmp(callee, "normalize") == 0) {
- assert(op[0]->type->is_float());
- float length = sqrtf(dot(op[0], op[0]));
-
- if (length == 0)
- return ir_constant::zero(mem_ctx, this->type);
-
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = op[0]->value.f[c] / length;
- } else if (strcmp(callee, "not") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_logic_not, type, op[0], NULL);
- } else if (strcmp(callee, "notEqual") == 0) {
- assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
- for (unsigned c = 0; c < op[0]->type->components(); c++) {
- switch (op[0]->type->base_type) {
- case GLSL_TYPE_UINT:
- data.b[c] = op[0]->value.u[c] != op[1]->value.u[c];
- break;
- case GLSL_TYPE_INT:
- data.b[c] = op[0]->value.i[c] != op[1]->value.i[c];
- break;
- case GLSL_TYPE_FLOAT:
- data.b[c] = op[0]->value.f[c] != op[1]->value.f[c];
- break;
- case GLSL_TYPE_BOOL:
- data.b[c] = op[0]->value.b[c] != op[1]->value.b[c];
- break;
- default:
- assert(!"Should not get here.");
- }
- }
- } else if (strcmp(callee, "outerProduct") == 0) {
- assert(op[0]->type->is_vector() && op[1]->type->is_vector());
- const unsigned m = op[0]->type->vector_elements;
- const unsigned n = op[1]->type->vector_elements;
- for (unsigned j = 0; j < n; j++) {
- for (unsigned i = 0; i < m; i++) {
- data.f[i+m*j] = op[0]->value.f[i] * op[1]->value.f[j];
- }
- }
- } else if (strcmp(callee, "pow") == 0) {
- expr = new(mem_ctx) ir_expression(ir_binop_pow, type, op[0], op[1]);
- } else if (strcmp(callee, "radians") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = M_PI / 180.0F * op[0]->value.f[c];
- } else if (strcmp(callee, "reflect") == 0) {
- assert(op[0]->type->is_float());
- float dot_NI = dot(op[1], op[0]);
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = op[0]->value.f[c] - 2 * dot_NI * op[1]->value.f[c];
- } else if (strcmp(callee, "refract") == 0) {
- const float eta = op[2]->value.f[0];
- const float dot_NI = dot(op[1], op[0]);
- const float k = 1.0F - eta * eta * (1.0F - dot_NI * dot_NI);
- if (k < 0.0) {
- return ir_constant::zero(mem_ctx, this->type);
- } else {
- for (unsigned c = 0; c < type->components(); c++) {
- data.f[c] = eta * op[0]->value.f[c] - (eta * dot_NI + sqrtf(k))
- * op[1]->value.f[c];
- }
- }
- } else if (strcmp(callee, "sign") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_sign, type, op[0], NULL);
- } else if (strcmp(callee, "sin") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_sin, type, op[0], NULL);
- } else if (strcmp(callee, "sinh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = sinhf(op[0]->value.f[c]);
- } else if (strcmp(callee, "smoothstep") == 0) {
- assert(num_parameters == 3);
- assert(op[1]->type == op[0]->type);
- unsigned edge_inc = op[0]->type->is_scalar() ? 0 : 1;
- for (unsigned c = 0, e = 0; c < type->components(); e += edge_inc, c++) {
- const float edge0 = op[0]->value.f[e];
- const float edge1 = op[1]->value.f[e];
- if (edge0 == edge1) {
- data.f[c] = 0.0; /* Avoid a crash - results are undefined anyway */
- } else {
- const float numerator = op[2]->value.f[c] - edge0;
- const float denominator = edge1 - edge0;
- const float t = CLAMP(numerator/denominator, 0, 1);
- data.f[c] = t * t * (3 - 2 * t);
- }
- }
- } else if (strcmp(callee, "sqrt") == 0) {
- expr = new(mem_ctx) ir_expression(ir_unop_sqrt, type, op[0], NULL);
- } else if (strcmp(callee, "step") == 0) {
- assert(op[0]->type->is_float() && op[1]->type->is_float());
- /* op[0] (edge) may be either a scalar or a vector */
- const unsigned c0_inc = op[0]->type->is_scalar() ? 0 : 1;
- for (unsigned c = 0, c0 = 0; c < type->components(); c0 += c0_inc, c++)
- data.f[c] = (op[1]->value.f[c] < op[0]->value.f[c0]) ? 0.0F : 1.0F;
- } else if (strcmp(callee, "tan") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = tanf(op[0]->value.f[c]);
- } else if (strcmp(callee, "tanh") == 0) {
- assert(op[0]->type->is_float());
- for (unsigned c = 0; c < op[0]->type->components(); c++)
- data.f[c] = tanhf(op[0]->value.f[c]);
- } else if (strcmp(callee, "transpose") == 0) {
- assert(op[0]->type->is_matrix());
- const unsigned n = op[0]->type->vector_elements;
- const unsigned m = op[0]->type->matrix_columns;
- for (unsigned j = 0; j < m; j++) {
- for (unsigned i = 0; i < n; i++) {
- data.f[m*i+j] += op[0]->value.f[i+n*j];
- }
- }
- } else {
- /* Unsupported builtin - some are not allowed in constant expressions. */
- return NULL;
- }
-
- if (expr != NULL)
- return expr->constant_expression_value();
-
- return new(mem_ctx) ir_constant(this->type, &data);
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_constant_expression.cpp
+ * Evaluate and process constant valued expressions
+ *
+ * In GLSL, constant valued expressions are used in several places. These
+ * must be processed and evaluated very early in the compilation process.
+ *
+ * * Sizes of arrays
+ * * Initializers for uniforms
+ * * Initializers for \c const variables
+ */
+
+#include <math.h>
+#include "main/core.h" /* for MAX2, MIN2, CLAMP */
+#include "ir.h"
+#include "ir_visitor.h"
+#include "glsl_types.h"
+
+static float
+dot(ir_constant *op0, ir_constant *op1)
+{
+ assert(op0->type->is_float() && op1->type->is_float());
+
+ float result = 0;
+ for (unsigned c = 0; c < op0->type->components(); c++)
+ result += op0->value.f[c] * op1->value.f[c];
+
+ return result;
+}
+
+ir_constant *
+ir_expression::constant_expression_value()
+{
+ if (this->type->is_error())
+ return NULL;
+
+ ir_constant *op[Elements(this->operands)] = { NULL, };
+ ir_constant_data data;
+
+ memset(&data, 0, sizeof(data));
+
+ for (unsigned operand = 0; operand < this->get_num_operands(); operand++) {
+ op[operand] = this->operands[operand]->constant_expression_value();
+ if (!op[operand])
+ return NULL;
+ }
+
+ if (op[1] != NULL)
+ assert(op[0]->type->base_type == op[1]->type->base_type);
+
+ bool op0_scalar = op[0]->type->is_scalar();
+ bool op1_scalar = op[1] != NULL && op[1]->type->is_scalar();
+
+ /* When iterating over a vector or matrix's components, we want to increase
+ * the loop counter. However, for scalars, we want to stay at 0.
+ */
+ unsigned c0_inc = op0_scalar ? 0 : 1;
+ unsigned c1_inc = op1_scalar ? 0 : 1;
+ unsigned components;
+ if (op1_scalar || !op[1]) {
+ components = op[0]->type->components();
+ } else {
+ components = op[1]->type->components();
+ }
+
+ void *ctx = ralloc_parent(this);
+
+ /* Handle array operations here, rather than below. */
+ if (op[0]->type->is_array()) {
+ assert(op[1] != NULL && op[1]->type->is_array());
+ switch (this->operation) {
+ case ir_binop_all_equal:
+ return new(ctx) ir_constant(op[0]->has_value(op[1]));
+ case ir_binop_any_nequal:
+ return new(ctx) ir_constant(!op[0]->has_value(op[1]));
+ default:
+ break;
+ }
+ return NULL;
+ }
+
+ switch (this->operation) {
+ case ir_unop_bit_not:
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_INT:
+ for (unsigned c = 0; c < components; c++)
+ data.i[c] = ~ op[0]->value.i[c];
+ break;
+ case GLSL_TYPE_UINT:
+ for (unsigned c = 0; c < components; c++)
+ data.u[c] = ~ op[0]->value.u[c];
+ break;
+ default:
+ assert(0);
+ }
+ break;
+
+ case ir_unop_logic_not:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.b[c] = !op[0]->value.b[c];
+ break;
+
+ case ir_unop_f2i:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.i[c] = (int) op[0]->value.f[c];
+ }
+ break;
+ case ir_unop_i2f:
+ assert(op[0]->type->base_type == GLSL_TYPE_INT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = (float) op[0]->value.i[c];
+ }
+ break;
+ case ir_unop_u2f:
+ assert(op[0]->type->base_type == GLSL_TYPE_UINT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = (float) op[0]->value.u[c];
+ }
+ break;
+ case ir_unop_b2f:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = op[0]->value.b[c] ? 1.0F : 0.0F;
+ }
+ break;
+ case ir_unop_f2b:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.b[c] = op[0]->value.f[c] != 0.0F ? true : false;
+ }
+ break;
+ case ir_unop_b2i:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.u[c] = op[0]->value.b[c] ? 1 : 0;
+ }
+ break;
+ case ir_unop_i2b:
+ assert(op[0]->type->is_integer());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.b[c] = op[0]->value.u[c] ? true : false;
+ }
+ break;
+
+ case ir_unop_any:
+ assert(op[0]->type->is_boolean());
+ data.b[0] = false;
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ if (op[0]->value.b[c])
+ data.b[0] = true;
+ }
+ break;
+
+ case ir_unop_trunc:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = truncf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_ceil:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = ceilf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_floor:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = floorf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_fract:
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = 0;
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = 0;
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[0]->value.f[c] - floor(op[0]->value.f[c]);
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_unop_sin:
+ case ir_unop_sin_reduced:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = sinf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_cos:
+ case ir_unop_cos_reduced:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = cosf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_neg:
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = -((int) op[0]->value.u[c]);
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = -op[0]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = -op[0]->value.f[c];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_unop_abs:
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c];
+ if (data.i[c] < 0)
+ data.i[c] = -data.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = fabs(op[0]->value.f[c]);
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_unop_sign:
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.i[c] > 0;
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = (op[0]->value.i[c] > 0) - (op[0]->value.i[c] < 0);
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = float((op[0]->value.f[c] > 0)-(op[0]->value.f[c] < 0));
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_unop_rcp:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_UINT:
+ if (op[0]->value.u[c] != 0.0)
+ data.u[c] = 1 / op[0]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ if (op[0]->value.i[c] != 0.0)
+ data.i[c] = 1 / op[0]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ if (op[0]->value.f[c] != 0.0)
+ data.f[c] = 1.0F / op[0]->value.f[c];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_unop_rsq:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = 1.0F / sqrtf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_sqrt:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = sqrtf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_exp:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = expf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_exp2:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = exp2f(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_log:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = logf(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_log2:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = log2f(op[0]->value.f[c]);
+ }
+ break;
+
+ case ir_unop_dFdx:
+ case ir_unop_dFdy:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = 0.0;
+ }
+ break;
+
+ case ir_binop_pow:
+ assert(op[0]->type->base_type == GLSL_TYPE_FLOAT);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ data.f[c] = powf(op[0]->value.f[c], op[1]->value.f[c]);
+ }
+ break;
+
+ case ir_binop_dot:
+ data.f[0] = dot(op[0], op[1]);
+ break;
+
+ case ir_binop_min:
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = MIN2(op[0]->value.u[c0], op[1]->value.u[c1]);
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = MIN2(op[0]->value.i[c0], op[1]->value.i[c1]);
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = MIN2(op[0]->value.f[c0], op[1]->value.f[c1]);
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+ break;
+ case ir_binop_max:
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = MAX2(op[0]->value.u[c0], op[1]->value.u[c1]);
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = MAX2(op[0]->value.i[c0], op[1]->value.i[c1]);
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = MAX2(op[0]->value.f[c0], op[1]->value.f[c1]);
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_binop_add:
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] + op[1]->value.u[c1];
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] + op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[0]->value.f[c0] + op[1]->value.f[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+ break;
+ case ir_binop_sub:
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] - op[1]->value.u[c1];
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] - op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+ break;
+ case ir_binop_mul:
+ /* Check for equal types, or unequal types involving scalars */
+ if ((op[0]->type == op[1]->type && !op[0]->type->is_matrix())
+ || op0_scalar || op1_scalar) {
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] * op[1]->value.u[c1];
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] * op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[0]->value.f[c0] * op[1]->value.f[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ } else {
+ assert(op[0]->type->is_matrix() || op[1]->type->is_matrix());
+
+ /* Multiply an N-by-M matrix with an M-by-P matrix. Since either
+ * matrix can be a GLSL vector, either N or P can be 1.
+ *
+ * For vec*mat, the vector is treated as a row vector. This
+ * means the vector is a 1-row x M-column matrix.
+ *
+ * For mat*vec, the vector is treated as a column vector. Since
+ * matrix_columns is 1 for vectors, this just works.
+ */
+ const unsigned n = op[0]->type->is_vector()
+ ? 1 : op[0]->type->vector_elements;
+ const unsigned m = op[1]->type->vector_elements;
+ const unsigned p = op[1]->type->matrix_columns;
+ for (unsigned j = 0; j < p; j++) {
+ for (unsigned i = 0; i < n; i++) {
+ for (unsigned k = 0; k < m; k++) {
+ data.f[i+n*j] += op[0]->value.f[i+n*k]*op[1]->value.f[k+m*j];
+ }
+ }
+ }
+ }
+
+ break;
+ case ir_binop_div:
+ /* FINISHME: Emit warning when division-by-zero is detected. */
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ if (op[1]->value.u[c1] == 0) {
+ data.u[c] = 0;
+ } else {
+ data.u[c] = op[0]->value.u[c0] / op[1]->value.u[c1];
+ }
+ break;
+ case GLSL_TYPE_INT:
+ if (op[1]->value.i[c1] == 0) {
+ data.i[c] = 0;
+ } else {
+ data.i[c] = op[0]->value.i[c0] / op[1]->value.i[c1];
+ }
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[0]->value.f[c0] / op[1]->value.f[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+ break;
+ case ir_binop_mod:
+ /* FINISHME: Emit warning when division-by-zero is detected. */
+ assert(op[0]->type == op[1]->type || op0_scalar || op1_scalar);
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ if (op[1]->value.u[c1] == 0) {
+ data.u[c] = 0;
+ } else {
+ data.u[c] = op[0]->value.u[c0] % op[1]->value.u[c1];
+ }
+ break;
+ case GLSL_TYPE_INT:
+ if (op[1]->value.i[c1] == 0) {
+ data.i[c] = 0;
+ } else {
+ data.i[c] = op[0]->value.i[c0] % op[1]->value.i[c1];
+ }
+ break;
+ case GLSL_TYPE_FLOAT:
+ /* We don't use fmod because it rounds toward zero; GLSL specifies
+ * the use of floor.
+ */
+ data.f[c] = op[0]->value.f[c0] - op[1]->value.f[c1]
+ * floorf(op[0]->value.f[c0] / op[1]->value.f[c1]);
+ break;
+ default:
+ assert(0);
+ }
+ }
+
+ break;
+
+ case ir_binop_logic_and:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.b[c] = op[0]->value.b[c] && op[1]->value.b[c];
+ break;
+ case ir_binop_logic_xor:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.b[c] = op[0]->value.b[c] ^ op[1]->value.b[c];
+ break;
+ case ir_binop_logic_or:
+ assert(op[0]->type->base_type == GLSL_TYPE_BOOL);
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.b[c] = op[0]->value.b[c] || op[1]->value.b[c];
+ break;
+
+ case ir_binop_less:
+ assert(op[0]->type == op[1]->type);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[0] = op[0]->value.u[0] < op[1]->value.u[0];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[0] = op[0]->value.i[0] < op[1]->value.i[0];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[0] = op[0]->value.f[0] < op[1]->value.f[0];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_greater:
+ assert(op[0]->type == op[1]->type);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] > op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] > op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] > op[1]->value.f[c];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_lequal:
+ assert(op[0]->type == op[1]->type);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[0] = op[0]->value.u[0] <= op[1]->value.u[0];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[0] = op[0]->value.i[0] <= op[1]->value.i[0];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[0] = op[0]->value.f[0] <= op[1]->value.f[0];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_gequal:
+ assert(op[0]->type == op[1]->type);
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[0] = op[0]->value.u[0] >= op[1]->value.u[0];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[0] = op[0]->value.i[0] >= op[1]->value.i[0];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[0] = op[0]->value.f[0] >= op[1]->value.f[0];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_equal:
+ assert(op[0]->type == op[1]->type);
+ for (unsigned c = 0; c < components; c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] == op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] == op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] == op[1]->value.f[c];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_nequal:
+ assert(op[0]->type != op[1]->type);
+ for (unsigned c = 0; c < components; c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] != op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] != op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] != op[1]->value.f[c];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+ case ir_binop_all_equal:
+ data.b[0] = op[0]->has_value(op[1]);
+ break;
+ case ir_binop_any_nequal:
+ data.b[0] = !op[0]->has_value(op[1]);
+ break;
+
+ case ir_binop_lshift:
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ if (op[0]->type->base_type == GLSL_TYPE_INT &&
+ op[1]->type->base_type == GLSL_TYPE_INT) {
+ data.i[c] = op[0]->value.i[c0] << op[1]->value.i[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_INT &&
+ op[1]->type->base_type == GLSL_TYPE_UINT) {
+ data.i[c] = op[0]->value.i[c0] << op[1]->value.u[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
+ op[1]->type->base_type == GLSL_TYPE_INT) {
+ data.u[c] = op[0]->value.u[c0] << op[1]->value.i[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
+ op[1]->type->base_type == GLSL_TYPE_UINT) {
+ data.u[c] = op[0]->value.u[c0] << op[1]->value.u[c1];
+ }
+ }
+ break;
+
+ case ir_binop_rshift:
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ if (op[0]->type->base_type == GLSL_TYPE_INT &&
+ op[1]->type->base_type == GLSL_TYPE_INT) {
+ data.i[c] = op[0]->value.i[c0] >> op[1]->value.i[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_INT &&
+ op[1]->type->base_type == GLSL_TYPE_UINT) {
+ data.i[c] = op[0]->value.i[c0] >> op[1]->value.u[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
+ op[1]->type->base_type == GLSL_TYPE_INT) {
+ data.u[c] = op[0]->value.u[c0] >> op[1]->value.i[c1];
+
+ } else if (op[0]->type->base_type == GLSL_TYPE_UINT &&
+ op[1]->type->base_type == GLSL_TYPE_UINT) {
+ data.u[c] = op[0]->value.u[c0] >> op[1]->value.u[c1];
+ }
+ }
+ break;
+
+ case ir_binop_bit_and:
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] & op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] & op[1]->value.u[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_binop_bit_or:
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] | op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] | op[1]->value.u[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_binop_bit_xor:
+ for (unsigned c = 0, c0 = 0, c1 = 0;
+ c < components;
+ c0 += c0_inc, c1 += c1_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_INT:
+ data.i[c] = op[0]->value.i[c0] ^ op[1]->value.i[c1];
+ break;
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[0]->value.u[c0] ^ op[1]->value.u[c1];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ case ir_quadop_vector:
+ for (unsigned c = 0; c < this->type->vector_elements; c++) {
+ switch (this->type->base_type) {
+ case GLSL_TYPE_INT:
+ data.i[c] = op[c]->value.i[0];
+ break;
+ case GLSL_TYPE_UINT:
+ data.u[c] = op[c]->value.u[0];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = op[c]->value.f[0];
+ break;
+ default:
+ assert(0);
+ }
+ }
+ break;
+
+ default:
+ /* FINISHME: Should handle all expression types. */
+ return NULL;
+ }
+
+ return new(ctx) ir_constant(this->type, &data);
+}
+
+
+ir_constant *
+ir_texture::constant_expression_value()
+{
+ /* texture lookups aren't constant expressions */
+ return NULL;
+}
+
+
+ir_constant *
+ir_swizzle::constant_expression_value()
+{
+ ir_constant *v = this->val->constant_expression_value();
+
+ if (v != NULL) {
+ ir_constant_data data = { { 0 } };
+
+ const unsigned swiz_idx[4] = {
+ this->mask.x, this->mask.y, this->mask.z, this->mask.w
+ };
+
+ for (unsigned i = 0; i < this->mask.num_components; i++) {
+ switch (v->type->base_type) {
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT: data.u[i] = v->value.u[swiz_idx[i]]; break;
+ case GLSL_TYPE_FLOAT: data.f[i] = v->value.f[swiz_idx[i]]; break;
+ case GLSL_TYPE_BOOL: data.b[i] = v->value.b[swiz_idx[i]]; break;
+ default: assert(!"Should not get here."); break;
+ }
+ }
+
+ void *ctx = ralloc_parent(this);
+ return new(ctx) ir_constant(this->type, &data);
+ }
+ return NULL;
+}
+
+
+ir_constant *
+ir_dereference_variable::constant_expression_value()
+{
+ /* This may occur during compile and var->type is glsl_type::error_type */
+ if (!var)
+ return NULL;
+
+ /* The constant_value of a uniform variable is its initializer,
+ * not the lifetime constant value of the uniform.
+ */
+ if (var->mode == ir_var_uniform)
+ return NULL;
+
+ if (!var->constant_value)
+ return NULL;
+
+ return var->constant_value->clone(ralloc_parent(var), NULL);
+}
+
+
+ir_constant *
+ir_dereference_array::constant_expression_value()
+{
+ ir_constant *array = this->array->constant_expression_value();
+ ir_constant *idx = this->array_index->constant_expression_value();
+
+ if ((array != NULL) && (idx != NULL)) {
+ void *ctx = ralloc_parent(this);
+ if (array->type->is_matrix()) {
+ /* Array access of a matrix results in a vector.
+ */
+ const unsigned column = idx->value.u[0];
+
+ const glsl_type *const column_type = array->type->column_type();
+
+ /* Offset in the constant matrix to the first element of the column
+ * to be extracted.
+ */
+ const unsigned mat_idx = column * column_type->vector_elements;
+
+ ir_constant_data data = { { 0 } };
+
+ switch (column_type->base_type) {
+ case GLSL_TYPE_UINT:
+ case GLSL_TYPE_INT:
+ for (unsigned i = 0; i < column_type->vector_elements; i++)
+ data.u[i] = array->value.u[mat_idx + i];
+
+ break;
+
+ case GLSL_TYPE_FLOAT:
+ for (unsigned i = 0; i < column_type->vector_elements; i++)
+ data.f[i] = array->value.f[mat_idx + i];
+
+ break;
+
+ default:
+ assert(!"Should not get here.");
+ break;
+ }
+
+ return new(ctx) ir_constant(column_type, &data);
+ } else if (array->type->is_vector()) {
+ const unsigned component = idx->value.u[0];
+
+ return new(ctx) ir_constant(array, component);
+ } else {
+ const unsigned index = idx->value.u[0];
+ return array->get_array_element(index)->clone(ctx, NULL);
+ }
+ }
+ return NULL;
+}
+
+
+ir_constant *
+ir_dereference_record::constant_expression_value()
+{
+ ir_constant *v = this->record->constant_expression_value();
+
+ return (v != NULL) ? v->get_record_field(this->field) : NULL;
+}
+
+
+ir_constant *
+ir_assignment::constant_expression_value()
+{
+ /* FINISHME: Handle CEs involving assignment (return RHS) */
+ return NULL;
+}
+
+
+ir_constant *
+ir_constant::constant_expression_value()
+{
+ return this;
+}
+
+
+ir_constant *
+ir_call::constant_expression_value()
+{
+ if (this->type == glsl_type::error_type)
+ return NULL;
+
+ /* From the GLSL 1.20 spec, page 23:
+ * "Function calls to user-defined functions (non-built-in functions)
+ * cannot be used to form constant expressions."
+ */
+ if (!this->callee->is_builtin)
+ return NULL;
+
+ unsigned num_parameters = 0;
+
+ /* Check if all parameters are constant */
+ ir_constant *op[3];
+ foreach_list(n, &this->actual_parameters) {
+ ir_constant *constant = ((ir_rvalue *) n)->constant_expression_value();
+ if (constant == NULL)
+ return NULL;
+
+ op[num_parameters] = constant;
+
+ assert(num_parameters < 3);
+ num_parameters++;
+ }
+
+ /* Individual cases below can either:
+ * - Assign "expr" a new ir_expression to evaluate (for basic opcodes)
+ * - Fill "data" with appopriate constant data
+ * - Return an ir_constant directly.
+ */
+ void *mem_ctx = ralloc_parent(this);
+ ir_expression *expr = NULL;
+
+ ir_constant_data data;
+ memset(&data, 0, sizeof(data));
+
+ const char *callee = this->callee_name();
+ if (strcmp(callee, "abs") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_abs, type, op[0], NULL);
+ } else if (strcmp(callee, "all") == 0) {
+ assert(op[0]->type->is_boolean());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ if (!op[0]->value.b[c])
+ return new(mem_ctx) ir_constant(false);
+ }
+ return new(mem_ctx) ir_constant(true);
+ } else if (strcmp(callee, "any") == 0) {
+ assert(op[0]->type->is_boolean());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ if (op[0]->value.b[c])
+ return new(mem_ctx) ir_constant(true);
+ }
+ return new(mem_ctx) ir_constant(false);
+ } else if (strcmp(callee, "acos") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = acosf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "acosh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = acoshf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "asin") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = asinf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "asinh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = asinhf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "atan") == 0) {
+ assert(op[0]->type->is_float());
+ if (num_parameters == 2) {
+ assert(op[1]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = atan2f(op[0]->value.f[c], op[1]->value.f[c]);
+ } else {
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = atanf(op[0]->value.f[c]);
+ }
+ } else if (strcmp(callee, "atanh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = atanhf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "dFdx") == 0 || strcmp(callee, "dFdy") == 0) {
+ return ir_constant::zero(mem_ctx, this->type);
+ } else if (strcmp(callee, "ceil") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_ceil, type, op[0], NULL);
+ } else if (strcmp(callee, "clamp") == 0) {
+ assert(num_parameters == 3);
+ unsigned c1_inc = op[1]->type->is_scalar() ? 0 : 1;
+ unsigned c2_inc = op[2]->type->is_scalar() ? 0 : 1;
+ for (unsigned c = 0, c1 = 0, c2 = 0;
+ c < op[0]->type->components();
+ c1 += c1_inc, c2 += c2_inc, c++) {
+
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.u[c] = CLAMP(op[0]->value.u[c], op[1]->value.u[c1],
+ op[2]->value.u[c2]);
+ break;
+ case GLSL_TYPE_INT:
+ data.i[c] = CLAMP(op[0]->value.i[c], op[1]->value.i[c1],
+ op[2]->value.i[c2]);
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.f[c] = CLAMP(op[0]->value.f[c], op[1]->value.f[c1],
+ op[2]->value.f[c2]);
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "cos") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_cos, type, op[0], NULL);
+ } else if (strcmp(callee, "cosh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = coshf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "cross") == 0) {
+ assert(op[0]->type == glsl_type::vec3_type);
+ assert(op[1]->type == glsl_type::vec3_type);
+ data.f[0] = (op[0]->value.f[1] * op[1]->value.f[2] -
+ op[1]->value.f[1] * op[0]->value.f[2]);
+ data.f[1] = (op[0]->value.f[2] * op[1]->value.f[0] -
+ op[1]->value.f[2] * op[0]->value.f[0]);
+ data.f[2] = (op[0]->value.f[0] * op[1]->value.f[1] -
+ op[1]->value.f[0] * op[0]->value.f[1]);
+ } else if (strcmp(callee, "degrees") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = 180.0F / M_PI * op[0]->value.f[c];
+ } else if (strcmp(callee, "distance") == 0) {
+ assert(op[0]->type->is_float() && op[1]->type->is_float());
+ float length_squared = 0.0;
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ float t = op[0]->value.f[c] - op[1]->value.f[c];
+ length_squared += t * t;
+ }
+ return new(mem_ctx) ir_constant(sqrtf(length_squared));
+ } else if (strcmp(callee, "dot") == 0) {
+ return new(mem_ctx) ir_constant(dot(op[0], op[1]));
+ } else if (strcmp(callee, "equal") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] == op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] == op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] == op[1]->value.f[c];
+ break;
+ case GLSL_TYPE_BOOL:
+ data.b[c] = op[0]->value.b[c] == op[1]->value.b[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "exp") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_exp, type, op[0], NULL);
+ } else if (strcmp(callee, "exp2") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_exp2, type, op[0], NULL);
+ } else if (strcmp(callee, "faceforward") == 0) {
+ if (dot(op[2], op[1]) < 0)
+ return op[0];
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = -op[0]->value.f[c];
+ } else if (strcmp(callee, "floor") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_floor, type, op[0], NULL);
+ } else if (strcmp(callee, "fract") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_fract, type, op[0], NULL);
+ } else if (strcmp(callee, "fwidth") == 0) {
+ return ir_constant::zero(mem_ctx, this->type);
+ } else if (strcmp(callee, "greaterThan") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] > op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] > op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] > op[1]->value.f[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "greaterThanEqual") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] >= op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] >= op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] >= op[1]->value.f[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "inversesqrt") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_rsq, type, op[0], NULL);
+ } else if (strcmp(callee, "length") == 0) {
+ return new(mem_ctx) ir_constant(sqrtf(dot(op[0], op[0])));
+ } else if (strcmp(callee, "lessThan") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] < op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] < op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] < op[1]->value.f[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "lessThanEqual") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] <= op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] <= op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] <= op[1]->value.f[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "log") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_log, type, op[0], NULL);
+ } else if (strcmp(callee, "log2") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_log2, type, op[0], NULL);
+ } else if (strcmp(callee, "matrixCompMult") == 0) {
+ assert(op[0]->type->is_float() && op[1]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = op[0]->value.f[c] * op[1]->value.f[c];
+ } else if (strcmp(callee, "max") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_binop_max, type, op[0], op[1]);
+ } else if (strcmp(callee, "min") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_binop_min, type, op[0], op[1]);
+ } else if (strcmp(callee, "mix") == 0) {
+ assert(op[0]->type->is_float() && op[1]->type->is_float());
+ if (op[2]->type->is_float()) {
+ unsigned c2_inc = op[2]->type->is_scalar() ? 0 : 1;
+ unsigned components = op[0]->type->components();
+ for (unsigned c = 0, c2 = 0; c < components; c2 += c2_inc, c++) {
+ data.f[c] = op[0]->value.f[c] * (1 - op[2]->value.f[c2]) +
+ op[1]->value.f[c] * op[2]->value.f[c2];
+ }
+ } else {
+ assert(op[2]->type->is_boolean());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = op[op[2]->value.b[c] ? 1 : 0]->value.f[c];
+ }
+ } else if (strcmp(callee, "mod") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_binop_mod, type, op[0], op[1]);
+ } else if (strcmp(callee, "normalize") == 0) {
+ assert(op[0]->type->is_float());
+ float length = sqrtf(dot(op[0], op[0]));
+
+ if (length == 0)
+ return ir_constant::zero(mem_ctx, this->type);
+
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = op[0]->value.f[c] / length;
+ } else if (strcmp(callee, "not") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_logic_not, type, op[0], NULL);
+ } else if (strcmp(callee, "notEqual") == 0) {
+ assert(op[0]->type->is_vector() && op[1] && op[1]->type->is_vector());
+ for (unsigned c = 0; c < op[0]->type->components(); c++) {
+ switch (op[0]->type->base_type) {
+ case GLSL_TYPE_UINT:
+ data.b[c] = op[0]->value.u[c] != op[1]->value.u[c];
+ break;
+ case GLSL_TYPE_INT:
+ data.b[c] = op[0]->value.i[c] != op[1]->value.i[c];
+ break;
+ case GLSL_TYPE_FLOAT:
+ data.b[c] = op[0]->value.f[c] != op[1]->value.f[c];
+ break;
+ case GLSL_TYPE_BOOL:
+ data.b[c] = op[0]->value.b[c] != op[1]->value.b[c];
+ break;
+ default:
+ assert(!"Should not get here.");
+ }
+ }
+ } else if (strcmp(callee, "outerProduct") == 0) {
+ assert(op[0]->type->is_vector() && op[1]->type->is_vector());
+ const unsigned m = op[0]->type->vector_elements;
+ const unsigned n = op[1]->type->vector_elements;
+ for (unsigned j = 0; j < n; j++) {
+ for (unsigned i = 0; i < m; i++) {
+ data.f[i+m*j] = op[0]->value.f[i] * op[1]->value.f[j];
+ }
+ }
+ } else if (strcmp(callee, "pow") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_binop_pow, type, op[0], op[1]);
+ } else if (strcmp(callee, "radians") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = M_PI / 180.0F * op[0]->value.f[c];
+ } else if (strcmp(callee, "reflect") == 0) {
+ assert(op[0]->type->is_float());
+ float dot_NI = dot(op[1], op[0]);
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = op[0]->value.f[c] - 2 * dot_NI * op[1]->value.f[c];
+ } else if (strcmp(callee, "refract") == 0) {
+ const float eta = op[2]->value.f[0];
+ const float dot_NI = dot(op[1], op[0]);
+ const float k = 1.0F - eta * eta * (1.0F - dot_NI * dot_NI);
+ if (k < 0.0) {
+ return ir_constant::zero(mem_ctx, this->type);
+ } else {
+ for (unsigned c = 0; c < type->components(); c++) {
+ data.f[c] = eta * op[0]->value.f[c] - (eta * dot_NI + sqrtf(k))
+ * op[1]->value.f[c];
+ }
+ }
+ } else if (strcmp(callee, "sign") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_sign, type, op[0], NULL);
+ } else if (strcmp(callee, "sin") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_sin, type, op[0], NULL);
+ } else if (strcmp(callee, "sinh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = sinhf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "smoothstep") == 0) {
+ assert(num_parameters == 3);
+ assert(op[1]->type == op[0]->type);
+ unsigned edge_inc = op[0]->type->is_scalar() ? 0 : 1;
+ for (unsigned c = 0, e = 0; c < type->components(); e += edge_inc, c++) {
+ const float edge0 = op[0]->value.f[e];
+ const float edge1 = op[1]->value.f[e];
+ if (edge0 == edge1) {
+ data.f[c] = 0.0; /* Avoid a crash - results are undefined anyway */
+ } else {
+ const float numerator = op[2]->value.f[c] - edge0;
+ const float denominator = edge1 - edge0;
+ const float t = CLAMP(numerator/denominator, 0, 1);
+ data.f[c] = t * t * (3 - 2 * t);
+ }
+ }
+ } else if (strcmp(callee, "sqrt") == 0) {
+ expr = new(mem_ctx) ir_expression(ir_unop_sqrt, type, op[0], NULL);
+ } else if (strcmp(callee, "step") == 0) {
+ assert(op[0]->type->is_float() && op[1]->type->is_float());
+ /* op[0] (edge) may be either a scalar or a vector */
+ const unsigned c0_inc = op[0]->type->is_scalar() ? 0 : 1;
+ for (unsigned c = 0, c0 = 0; c < type->components(); c0 += c0_inc, c++)
+ data.f[c] = (op[1]->value.f[c] < op[0]->value.f[c0]) ? 0.0F : 1.0F;
+ } else if (strcmp(callee, "tan") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = tanf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "tanh") == 0) {
+ assert(op[0]->type->is_float());
+ for (unsigned c = 0; c < op[0]->type->components(); c++)
+ data.f[c] = tanhf(op[0]->value.f[c]);
+ } else if (strcmp(callee, "transpose") == 0) {
+ assert(op[0]->type->is_matrix());
+ const unsigned n = op[0]->type->vector_elements;
+ const unsigned m = op[0]->type->matrix_columns;
+ for (unsigned j = 0; j < m; j++) {
+ for (unsigned i = 0; i < n; i++) {
+ data.f[m*i+j] += op[0]->value.f[i+n*j];
+ }
+ }
+ } else {
+ /* Unsupported builtin - some are not allowed in constant expressions. */
+ return NULL;
+ }
+
+ if (expr != NULL)
+ return expr->constant_expression_value();
+
+ return new(mem_ctx) ir_constant(this->type, &data);
+}
diff --git a/mesalib/src/glsl/ir_import_prototypes.cpp b/mesalib/src/glsl/ir_import_prototypes.cpp
index 3585bf6b2..03d40bb68 100644
--- a/mesalib/src/glsl/ir_import_prototypes.cpp
+++ b/mesalib/src/glsl/ir_import_prototypes.cpp
@@ -1,122 +1,122 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_import_prototypes.cpp
- * Import function prototypes from one IR tree into another.
- *
- * \author Ian Romanick
- */
-#include "ir.h"
-#include "glsl_symbol_table.h"
-
-/**
- * Visitor used to import function prototypes
- *
- * Normally the \c clone method of either \c ir_function or
- * \c ir_function_signature could be used. However, we don't want a complete
- * clone of the \c ir_function_signature. We want everything \b except the
- * body of the function.
- */
-class import_prototype_visitor : public ir_hierarchical_visitor {
-public:
- /**
- */
- import_prototype_visitor(exec_list *list, glsl_symbol_table *symbols,
- void *mem_ctx)
- {
- this->mem_ctx = mem_ctx;
- this->list = list;
- this->symbols = symbols;
- this->function = NULL;
- }
-
- virtual ir_visitor_status visit_enter(ir_function *ir)
- {
- assert(this->function == NULL);
-
- this->function = this->symbols->get_function(ir->name);
- if (!this->function) {
- this->function = new(this->mem_ctx) ir_function(ir->name);
-
- list->push_tail(this->function);
-
- /* Add the new function to the symbol table.
- */
- this->symbols->add_function(this->function);
- }
- return visit_continue;
- }
-
- virtual ir_visitor_status visit_leave(ir_function *ir)
- {
- (void) ir;
- assert(this->function != NULL);
-
- this->function = NULL;
- return visit_continue;
- }
-
- ir_visitor_status visit_enter(ir_function_signature *ir)
- {
- assert(this->function != NULL);
-
- ir_function_signature *copy = ir->clone_prototype(mem_ctx, NULL);
-
- this->function->add_signature(copy);
-
- /* Do not process child nodes of the ir_function_signature. There can
- * never be any nodes inside the ir_function_signature that we care
- * about. Instead continue with the next sibling.
- */
- return visit_continue_with_parent;
- }
-
-private:
- exec_list *list;
- ir_function *function;
- glsl_symbol_table *symbols;
- void *mem_ctx;
-};
-
-
-/**
- * Import function prototypes from one IR tree into another
- *
- * \param source Source instruction stream containing functions whose
- * prototypes are to be imported
- * \param dest Destination instruction stream where new \c ir_function and
- * \c ir_function_signature nodes will be stored
- * \param symbols Symbol table where new functions will be stored
- * \param mem_ctx ralloc memory context used for new allocations
- */
-void
-import_prototypes(const exec_list *source, exec_list *dest,
- glsl_symbol_table *symbols, void *mem_ctx)
-{
- import_prototype_visitor v(dest, symbols, mem_ctx);
-
- /* Making source be const is just extra documentation.
- */
- v.run(const_cast<exec_list *>(source));
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_import_prototypes.cpp
+ * Import function prototypes from one IR tree into another.
+ *
+ * \author Ian Romanick
+ */
+#include "ir.h"
+#include "glsl_symbol_table.h"
+
+/**
+ * Visitor used to import function prototypes
+ *
+ * Normally the \c clone method of either \c ir_function or
+ * \c ir_function_signature could be used. However, we don't want a complete
+ * clone of the \c ir_function_signature. We want everything \b except the
+ * body of the function.
+ */
+class import_prototype_visitor : public ir_hierarchical_visitor {
+public:
+ /**
+ */
+ import_prototype_visitor(exec_list *list, glsl_symbol_table *symbols,
+ void *mem_ctx)
+ {
+ this->mem_ctx = mem_ctx;
+ this->list = list;
+ this->symbols = symbols;
+ this->function = NULL;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_function *ir)
+ {
+ assert(this->function == NULL);
+
+ this->function = this->symbols->get_function(ir->name);
+ if (!this->function) {
+ this->function = new(this->mem_ctx) ir_function(ir->name);
+
+ list->push_tail(this->function);
+
+ /* Add the new function to the symbol table.
+ */
+ this->symbols->add_function(this->function);
+ }
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit_leave(ir_function *ir)
+ {
+ (void) ir;
+ assert(this->function != NULL);
+
+ this->function = NULL;
+ return visit_continue;
+ }
+
+ ir_visitor_status visit_enter(ir_function_signature *ir)
+ {
+ assert(this->function != NULL);
+
+ ir_function_signature *copy = ir->clone_prototype(mem_ctx, NULL);
+
+ this->function->add_signature(copy);
+
+ /* Do not process child nodes of the ir_function_signature. There can
+ * never be any nodes inside the ir_function_signature that we care
+ * about. Instead continue with the next sibling.
+ */
+ return visit_continue_with_parent;
+ }
+
+private:
+ exec_list *list;
+ ir_function *function;
+ glsl_symbol_table *symbols;
+ void *mem_ctx;
+};
+
+
+/**
+ * Import function prototypes from one IR tree into another
+ *
+ * \param source Source instruction stream containing functions whose
+ * prototypes are to be imported
+ * \param dest Destination instruction stream where new \c ir_function and
+ * \c ir_function_signature nodes will be stored
+ * \param symbols Symbol table where new functions will be stored
+ * \param mem_ctx ralloc memory context used for new allocations
+ */
+void
+import_prototypes(const exec_list *source, exec_list *dest,
+ glsl_symbol_table *symbols, void *mem_ctx)
+{
+ import_prototype_visitor v(dest, symbols, mem_ctx);
+
+ /* Making source be const is just extra documentation.
+ */
+ v.run(const_cast<exec_list *>(source));
+}
diff --git a/mesalib/src/glsl/ir_print_visitor.cpp b/mesalib/src/glsl/ir_print_visitor.cpp
index 82ccc722f..f7dc29689 100644
--- a/mesalib/src/glsl/ir_print_visitor.cpp
+++ b/mesalib/src/glsl/ir_print_visitor.cpp
@@ -1,471 +1,471 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include "ir_print_visitor.h"
-#include "glsl_types.h"
-#include "glsl_parser_extras.h"
-
-static void print_type(const glsl_type *t);
-
-void
-ir_instruction::print(void) const
-{
- ir_instruction *deconsted = const_cast<ir_instruction *>(this);
-
- ir_print_visitor v;
- deconsted->accept(&v);
-}
-
-void
-_mesa_print_ir(exec_list *instructions,
- struct _mesa_glsl_parse_state *state)
-{
- if (state) {
- for (unsigned i = 0; i < state->num_user_structures; i++) {
- const glsl_type *const s = state->user_structures[i];
-
- printf("(structure (%s) (%s@%p) (%u) (\n",
- s->name, s->name, (void *) s, s->length);
-
- for (unsigned j = 0; j < s->length; j++) {
- printf("\t((");
- print_type(s->fields.structure[j].type);
- printf(")(%s))\n", s->fields.structure[j].name);
- }
-
- printf(")\n");
- }
- }
-
- printf("(\n");
- foreach_iter(exec_list_iterator, iter, *instructions) {
- ir_instruction *ir = (ir_instruction *)iter.get();
- ir->print();
- if (ir->ir_type != ir_type_function)
- printf("\n");
- }
- printf("\n)");
-}
-
-
-void ir_print_visitor::indent(void)
-{
- for (int i = 0; i < indentation; i++)
- printf(" ");
-}
-
-static void
-print_type(const glsl_type *t)
-{
- if (t->base_type == GLSL_TYPE_ARRAY) {
- printf("(array ");
- print_type(t->fields.array);
- printf(" %u)", t->length);
- } else if ((t->base_type == GLSL_TYPE_STRUCT)
- && (strncmp("gl_", t->name, 3) != 0)) {
- printf("%s@%p", t->name, (void *) t);
- } else {
- printf("%s", t->name);
- }
-}
-
-
-void ir_print_visitor::visit(ir_variable *ir)
-{
- printf("(declare ");
-
- const char *const cent = (ir->centroid) ? "centroid " : "";
- const char *const inv = (ir->invariant) ? "invariant " : "";
- const char *const mode[] = { "", "uniform ", "in ", "out ", "inout ",
- "const_in ", "sys ", "temporary " };
- const char *const interp[] = { "", "flat", "noperspective" };
-
- printf("(%s%s%s%s) ",
- cent, inv, mode[ir->mode], interp[ir->interpolation]);
-
- print_type(ir->type);
- printf(" %s@%p)", ir->name, (void *) ir);
-}
-
-
-void ir_print_visitor::visit(ir_function_signature *ir)
-{
- printf("(signature ");
- indentation++;
-
- print_type(ir->return_type);
- printf("\n");
- indent();
-
- printf("(parameters\n");
- indentation++;
-
- foreach_iter(exec_list_iterator, iter, ir->parameters) {
- ir_variable *const inst = (ir_variable *) iter.get();
-
- indent();
- inst->accept(this);
- printf("\n");
- }
- indentation--;
-
- indent();
- printf(")\n");
-
- indent();
-
- printf("(\n");
- indentation++;
-
- foreach_iter(exec_list_iterator, iter, ir->body) {
- ir_instruction *const inst = (ir_instruction *) iter.get();
-
- indent();
- inst->accept(this);
- printf("\n");
- }
- indentation--;
- indent();
- printf("))\n");
- indentation--;
-}
-
-
-void ir_print_visitor::visit(ir_function *ir)
-{
- printf("(function %s\n", ir->name);
- indentation++;
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_function_signature *const sig = (ir_function_signature *) iter.get();
- indent();
- sig->accept(this);
- printf("\n");
- }
- indentation--;
- indent();
- printf(")\n\n");
-}
-
-
-void ir_print_visitor::visit(ir_expression *ir)
-{
- printf("(expression ");
-
- print_type(ir->type);
-
- printf(" %s ", ir->operator_string());
-
- for (unsigned i = 0; i < ir->get_num_operands(); i++) {
- ir->operands[i]->accept(this);
- }
-
- printf(") ");
-}
-
-
-void ir_print_visitor::visit(ir_texture *ir)
-{
- printf("(%s ", ir->opcode_string());
-
- ir->sampler->accept(this);
- printf(" ");
-
- ir->coordinate->accept(this);
-
- printf(" ");
-
- if (ir->offset != NULL) {
- ir->offset->accept(this);
- } else {
- printf("0");
- }
-
- printf(" ");
-
- if (ir->op != ir_txf) {
- if (ir->projector)
- ir->projector->accept(this);
- else
- printf("1");
-
- if (ir->shadow_comparitor) {
- printf(" ");
- ir->shadow_comparitor->accept(this);
- } else {
- printf(" ()");
- }
- }
-
- printf(" ");
- switch (ir->op)
- {
- case ir_tex:
- break;
- case ir_txb:
- ir->lod_info.bias->accept(this);
- break;
- case ir_txl:
- case ir_txf:
- ir->lod_info.lod->accept(this);
- break;
- case ir_txd:
- printf("(");
- ir->lod_info.grad.dPdx->accept(this);
- printf(" ");
- ir->lod_info.grad.dPdy->accept(this);
- printf(")");
- break;
- };
- printf(")");
-}
-
-
-void ir_print_visitor::visit(ir_swizzle *ir)
-{
- const unsigned swiz[4] = {
- ir->mask.x,
- ir->mask.y,
- ir->mask.z,
- ir->mask.w,
- };
-
- printf("(swiz ");
- for (unsigned i = 0; i < ir->mask.num_components; i++) {
- printf("%c", "xyzw"[swiz[i]]);
- }
- printf(" ");
- ir->val->accept(this);
- printf(")");
-}
-
-
-void ir_print_visitor::visit(ir_dereference_variable *ir)
-{
- ir_variable *var = ir->variable_referenced();
- printf("(var_ref %s@%p) ", var->name, (void *) var);
-}
-
-
-void ir_print_visitor::visit(ir_dereference_array *ir)
-{
- printf("(array_ref ");
- ir->array->accept(this);
- ir->array_index->accept(this);
- printf(") ");
-}
-
-
-void ir_print_visitor::visit(ir_dereference_record *ir)
-{
- printf("(record_ref ");
- ir->record->accept(this);
- printf(" %s) ", ir->field);
-}
-
-
-void ir_print_visitor::visit(ir_assignment *ir)
-{
- printf("(assign ");
-
- if (ir->condition)
- ir->condition->accept(this);
-
- char mask[5];
- unsigned j = 0;
-
- for (unsigned i = 0; i < 4; i++) {
- if ((ir->write_mask & (1 << i)) != 0) {
- mask[j] = "xyzw"[i];
- j++;
- }
- }
- mask[j] = '\0';
-
- printf(" (%s) ", mask);
-
- ir->lhs->accept(this);
-
- printf(" ");
-
- ir->rhs->accept(this);
- printf(") ");
-}
-
-
-void ir_print_visitor::visit(ir_constant *ir)
-{
- const glsl_type *const base_type = ir->type->get_base_type();
-
- printf("(constant ");
- print_type(ir->type);
- printf(" (");
-
- if (ir->type->is_array()) {
- for (unsigned i = 0; i < ir->type->length; i++)
- ir->get_array_element(i)->accept(this);
- } else if (ir->type->is_record()) {
- ir_constant *value = (ir_constant *) ir->components.get_head();
- for (unsigned i = 0; i < ir->type->length; i++) {
- printf("(%s ", ir->type->fields.structure->name);
- value->accept(this);
- printf(")");
-
- value = (ir_constant *) value->next;
- }
- } else {
- for (unsigned i = 0; i < ir->type->components(); i++) {
- if (i != 0)
- printf(" ");
- switch (base_type->base_type) {
- case GLSL_TYPE_UINT: printf("%u", ir->value.u[i]); break;
- case GLSL_TYPE_INT: printf("%d", ir->value.i[i]); break;
- case GLSL_TYPE_FLOAT: printf("%f", ir->value.f[i]); break;
- case GLSL_TYPE_BOOL: printf("%d", ir->value.b[i]); break;
- default: assert(0);
- }
- }
- }
- printf(")) ");
-}
-
-
-void
-ir_print_visitor::visit(ir_call *ir)
-{
- printf("(call %s (", ir->callee_name());
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_instruction *const inst = (ir_instruction *) iter.get();
-
- inst->accept(this);
- }
- printf("))\n");
-}
-
-
-void
-ir_print_visitor::visit(ir_return *ir)
-{
- printf("(return");
-
- ir_rvalue *const value = ir->get_value();
- if (value) {
- printf(" ");
- value->accept(this);
- }
-
- printf(")");
-}
-
-
-void
-ir_print_visitor::visit(ir_discard *ir)
-{
- printf("(discard ");
-
- if (ir->condition != NULL) {
- printf(" ");
- ir->condition->accept(this);
- }
-
- printf(")");
-}
-
-
-void
-ir_print_visitor::visit(ir_if *ir)
-{
- printf("(if ");
- ir->condition->accept(this);
-
- printf("(\n");
- indentation++;
-
- foreach_iter(exec_list_iterator, iter, ir->then_instructions) {
- ir_instruction *const inst = (ir_instruction *) iter.get();
-
- indent();
- inst->accept(this);
- printf("\n");
- }
-
- indentation--;
- indent();
- printf(")\n");
-
- indent();
- if (!ir->else_instructions.is_empty()) {
- printf("(\n");
- indentation++;
-
- foreach_iter(exec_list_iterator, iter, ir->else_instructions) {
- ir_instruction *const inst = (ir_instruction *) iter.get();
-
- indent();
- inst->accept(this);
- printf("\n");
- }
- indentation--;
- indent();
- printf("))\n");
- } else {
- printf("())\n");
- }
-}
-
-
-void
-ir_print_visitor::visit(ir_loop *ir)
-{
- printf("(loop (");
- if (ir->counter != NULL)
- ir->counter->accept(this);
- printf(") (");
- if (ir->from != NULL)
- ir->from->accept(this);
- printf(") (");
- if (ir->to != NULL)
- ir->to->accept(this);
- printf(") (");
- if (ir->increment != NULL)
- ir->increment->accept(this);
- printf(") (\n");
- indentation++;
-
- foreach_iter(exec_list_iterator, iter, ir->body_instructions) {
- ir_instruction *const inst = (ir_instruction *) iter.get();
-
- indent();
- inst->accept(this);
- printf("\n");
- }
- indentation--;
- indent();
- printf("))\n");
-}
-
-
-void
-ir_print_visitor::visit(ir_loop_jump *ir)
-{
- printf("%s", ir->is_break() ? "break" : "continue");
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include "ir_print_visitor.h"
+#include "glsl_types.h"
+#include "glsl_parser_extras.h"
+
+static void print_type(const glsl_type *t);
+
+void
+ir_instruction::print(void) const
+{
+ ir_instruction *deconsted = const_cast<ir_instruction *>(this);
+
+ ir_print_visitor v;
+ deconsted->accept(&v);
+}
+
+void
+_mesa_print_ir(exec_list *instructions,
+ struct _mesa_glsl_parse_state *state)
+{
+ if (state) {
+ for (unsigned i = 0; i < state->num_user_structures; i++) {
+ const glsl_type *const s = state->user_structures[i];
+
+ printf("(structure (%s) (%s@%p) (%u) (\n",
+ s->name, s->name, (void *) s, s->length);
+
+ for (unsigned j = 0; j < s->length; j++) {
+ printf("\t((");
+ print_type(s->fields.structure[j].type);
+ printf(")(%s))\n", s->fields.structure[j].name);
+ }
+
+ printf(")\n");
+ }
+ }
+
+ printf("(\n");
+ foreach_iter(exec_list_iterator, iter, *instructions) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+ ir->print();
+ if (ir->ir_type != ir_type_function)
+ printf("\n");
+ }
+ printf("\n)");
+}
+
+
+void ir_print_visitor::indent(void)
+{
+ for (int i = 0; i < indentation; i++)
+ printf(" ");
+}
+
+static void
+print_type(const glsl_type *t)
+{
+ if (t->base_type == GLSL_TYPE_ARRAY) {
+ printf("(array ");
+ print_type(t->fields.array);
+ printf(" %u)", t->length);
+ } else if ((t->base_type == GLSL_TYPE_STRUCT)
+ && (strncmp("gl_", t->name, 3) != 0)) {
+ printf("%s@%p", t->name, (void *) t);
+ } else {
+ printf("%s", t->name);
+ }
+}
+
+
+void ir_print_visitor::visit(ir_variable *ir)
+{
+ printf("(declare ");
+
+ const char *const cent = (ir->centroid) ? "centroid " : "";
+ const char *const inv = (ir->invariant) ? "invariant " : "";
+ const char *const mode[] = { "", "uniform ", "in ", "out ", "inout ",
+ "const_in ", "sys ", "temporary " };
+ const char *const interp[] = { "", "flat", "noperspective" };
+
+ printf("(%s%s%s%s) ",
+ cent, inv, mode[ir->mode], interp[ir->interpolation]);
+
+ print_type(ir->type);
+ printf(" %s@%p)", ir->name, (void *) ir);
+}
+
+
+void ir_print_visitor::visit(ir_function_signature *ir)
+{
+ printf("(signature ");
+ indentation++;
+
+ print_type(ir->return_type);
+ printf("\n");
+ indent();
+
+ printf("(parameters\n");
+ indentation++;
+
+ foreach_iter(exec_list_iterator, iter, ir->parameters) {
+ ir_variable *const inst = (ir_variable *) iter.get();
+
+ indent();
+ inst->accept(this);
+ printf("\n");
+ }
+ indentation--;
+
+ indent();
+ printf(")\n");
+
+ indent();
+
+ printf("(\n");
+ indentation++;
+
+ foreach_iter(exec_list_iterator, iter, ir->body) {
+ ir_instruction *const inst = (ir_instruction *) iter.get();
+
+ indent();
+ inst->accept(this);
+ printf("\n");
+ }
+ indentation--;
+ indent();
+ printf("))\n");
+ indentation--;
+}
+
+
+void ir_print_visitor::visit(ir_function *ir)
+{
+ printf("(function %s\n", ir->name);
+ indentation++;
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_function_signature *const sig = (ir_function_signature *) iter.get();
+ indent();
+ sig->accept(this);
+ printf("\n");
+ }
+ indentation--;
+ indent();
+ printf(")\n\n");
+}
+
+
+void ir_print_visitor::visit(ir_expression *ir)
+{
+ printf("(expression ");
+
+ print_type(ir->type);
+
+ printf(" %s ", ir->operator_string());
+
+ for (unsigned i = 0; i < ir->get_num_operands(); i++) {
+ ir->operands[i]->accept(this);
+ }
+
+ printf(") ");
+}
+
+
+void ir_print_visitor::visit(ir_texture *ir)
+{
+ printf("(%s ", ir->opcode_string());
+
+ ir->sampler->accept(this);
+ printf(" ");
+
+ ir->coordinate->accept(this);
+
+ printf(" ");
+
+ if (ir->offset != NULL) {
+ ir->offset->accept(this);
+ } else {
+ printf("0");
+ }
+
+ printf(" ");
+
+ if (ir->op != ir_txf) {
+ if (ir->projector)
+ ir->projector->accept(this);
+ else
+ printf("1");
+
+ if (ir->shadow_comparitor) {
+ printf(" ");
+ ir->shadow_comparitor->accept(this);
+ } else {
+ printf(" ()");
+ }
+ }
+
+ printf(" ");
+ switch (ir->op)
+ {
+ case ir_tex:
+ break;
+ case ir_txb:
+ ir->lod_info.bias->accept(this);
+ break;
+ case ir_txl:
+ case ir_txf:
+ ir->lod_info.lod->accept(this);
+ break;
+ case ir_txd:
+ printf("(");
+ ir->lod_info.grad.dPdx->accept(this);
+ printf(" ");
+ ir->lod_info.grad.dPdy->accept(this);
+ printf(")");
+ break;
+ };
+ printf(")");
+}
+
+
+void ir_print_visitor::visit(ir_swizzle *ir)
+{
+ const unsigned swiz[4] = {
+ ir->mask.x,
+ ir->mask.y,
+ ir->mask.z,
+ ir->mask.w,
+ };
+
+ printf("(swiz ");
+ for (unsigned i = 0; i < ir->mask.num_components; i++) {
+ printf("%c", "xyzw"[swiz[i]]);
+ }
+ printf(" ");
+ ir->val->accept(this);
+ printf(")");
+}
+
+
+void ir_print_visitor::visit(ir_dereference_variable *ir)
+{
+ ir_variable *var = ir->variable_referenced();
+ printf("(var_ref %s@%p) ", var->name, (void *) var);
+}
+
+
+void ir_print_visitor::visit(ir_dereference_array *ir)
+{
+ printf("(array_ref ");
+ ir->array->accept(this);
+ ir->array_index->accept(this);
+ printf(") ");
+}
+
+
+void ir_print_visitor::visit(ir_dereference_record *ir)
+{
+ printf("(record_ref ");
+ ir->record->accept(this);
+ printf(" %s) ", ir->field);
+}
+
+
+void ir_print_visitor::visit(ir_assignment *ir)
+{
+ printf("(assign ");
+
+ if (ir->condition)
+ ir->condition->accept(this);
+
+ char mask[5];
+ unsigned j = 0;
+
+ for (unsigned i = 0; i < 4; i++) {
+ if ((ir->write_mask & (1 << i)) != 0) {
+ mask[j] = "xyzw"[i];
+ j++;
+ }
+ }
+ mask[j] = '\0';
+
+ printf(" (%s) ", mask);
+
+ ir->lhs->accept(this);
+
+ printf(" ");
+
+ ir->rhs->accept(this);
+ printf(") ");
+}
+
+
+void ir_print_visitor::visit(ir_constant *ir)
+{
+ const glsl_type *const base_type = ir->type->get_base_type();
+
+ printf("(constant ");
+ print_type(ir->type);
+ printf(" (");
+
+ if (ir->type->is_array()) {
+ for (unsigned i = 0; i < ir->type->length; i++)
+ ir->get_array_element(i)->accept(this);
+ } else if (ir->type->is_record()) {
+ ir_constant *value = (ir_constant *) ir->components.get_head();
+ for (unsigned i = 0; i < ir->type->length; i++) {
+ printf("(%s ", ir->type->fields.structure->name);
+ value->accept(this);
+ printf(")");
+
+ value = (ir_constant *) value->next;
+ }
+ } else {
+ for (unsigned i = 0; i < ir->type->components(); i++) {
+ if (i != 0)
+ printf(" ");
+ switch (base_type->base_type) {
+ case GLSL_TYPE_UINT: printf("%u", ir->value.u[i]); break;
+ case GLSL_TYPE_INT: printf("%d", ir->value.i[i]); break;
+ case GLSL_TYPE_FLOAT: printf("%f", ir->value.f[i]); break;
+ case GLSL_TYPE_BOOL: printf("%d", ir->value.b[i]); break;
+ default: assert(0);
+ }
+ }
+ }
+ printf(")) ");
+}
+
+
+void
+ir_print_visitor::visit(ir_call *ir)
+{
+ printf("(call %s (", ir->callee_name());
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_instruction *const inst = (ir_instruction *) iter.get();
+
+ inst->accept(this);
+ }
+ printf("))\n");
+}
+
+
+void
+ir_print_visitor::visit(ir_return *ir)
+{
+ printf("(return");
+
+ ir_rvalue *const value = ir->get_value();
+ if (value) {
+ printf(" ");
+ value->accept(this);
+ }
+
+ printf(")");
+}
+
+
+void
+ir_print_visitor::visit(ir_discard *ir)
+{
+ printf("(discard ");
+
+ if (ir->condition != NULL) {
+ printf(" ");
+ ir->condition->accept(this);
+ }
+
+ printf(")");
+}
+
+
+void
+ir_print_visitor::visit(ir_if *ir)
+{
+ printf("(if ");
+ ir->condition->accept(this);
+
+ printf("(\n");
+ indentation++;
+
+ foreach_iter(exec_list_iterator, iter, ir->then_instructions) {
+ ir_instruction *const inst = (ir_instruction *) iter.get();
+
+ indent();
+ inst->accept(this);
+ printf("\n");
+ }
+
+ indentation--;
+ indent();
+ printf(")\n");
+
+ indent();
+ if (!ir->else_instructions.is_empty()) {
+ printf("(\n");
+ indentation++;
+
+ foreach_iter(exec_list_iterator, iter, ir->else_instructions) {
+ ir_instruction *const inst = (ir_instruction *) iter.get();
+
+ indent();
+ inst->accept(this);
+ printf("\n");
+ }
+ indentation--;
+ indent();
+ printf("))\n");
+ } else {
+ printf("())\n");
+ }
+}
+
+
+void
+ir_print_visitor::visit(ir_loop *ir)
+{
+ printf("(loop (");
+ if (ir->counter != NULL)
+ ir->counter->accept(this);
+ printf(") (");
+ if (ir->from != NULL)
+ ir->from->accept(this);
+ printf(") (");
+ if (ir->to != NULL)
+ ir->to->accept(this);
+ printf(") (");
+ if (ir->increment != NULL)
+ ir->increment->accept(this);
+ printf(") (\n");
+ indentation++;
+
+ foreach_iter(exec_list_iterator, iter, ir->body_instructions) {
+ ir_instruction *const inst = (ir_instruction *) iter.get();
+
+ indent();
+ inst->accept(this);
+ printf("\n");
+ }
+ indentation--;
+ indent();
+ printf("))\n");
+}
+
+
+void
+ir_print_visitor::visit(ir_loop_jump *ir)
+{
+ printf("%s", ir->is_break() ? "break" : "continue");
+}
diff --git a/mesalib/src/glsl/ir_validate.cpp b/mesalib/src/glsl/ir_validate.cpp
index 44d7549ea..4d9d4562c 100644
--- a/mesalib/src/glsl/ir_validate.cpp
+++ b/mesalib/src/glsl/ir_validate.cpp
@@ -1,529 +1,529 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_validate.cpp
- *
- * Attempts to verify that various invariants of the IR tree are true.
- *
- * In particular, at the moment it makes sure that no single
- * ir_instruction node except for ir_variable appears multiple times
- * in the ir tree. ir_variable does appear multiple times: Once as a
- * declaration in an exec_list, and multiple times as the endpoint of
- * a dereference chain.
- */
-
-#include <inttypes.h>
-#include "ir.h"
-#include "ir_hierarchical_visitor.h"
-#include "program/hash_table.h"
-#include "glsl_types.h"
-
-class ir_validate : public ir_hierarchical_visitor {
-public:
- ir_validate()
- {
- this->ht = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
-
- this->current_function = NULL;
-
- this->callback = ir_validate::validate_ir;
- this->data = ht;
- }
-
- ~ir_validate()
- {
- hash_table_dtor(this->ht);
- }
-
- virtual ir_visitor_status visit(ir_variable *v);
- virtual ir_visitor_status visit(ir_dereference_variable *ir);
- virtual ir_visitor_status visit(ir_if *ir);
-
- virtual ir_visitor_status visit_leave(ir_loop *ir);
- virtual ir_visitor_status visit_enter(ir_function *ir);
- virtual ir_visitor_status visit_leave(ir_function *ir);
- virtual ir_visitor_status visit_enter(ir_function_signature *ir);
-
- virtual ir_visitor_status visit_leave(ir_expression *ir);
- virtual ir_visitor_status visit_leave(ir_swizzle *ir);
-
- virtual ir_visitor_status visit_enter(ir_assignment *ir);
-
- static void validate_ir(ir_instruction *ir, void *data);
-
- ir_function *current_function;
-
- struct hash_table *ht;
-};
-
-
-ir_visitor_status
-ir_validate::visit(ir_dereference_variable *ir)
-{
- if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {
- printf("ir_dereference_variable @ %p does not specify a variable %p\n",
- (void *) ir, (void *) ir->var);
- abort();
- }
-
- if (hash_table_find(ht, ir->var) == NULL) {
- printf("ir_dereference_variable @ %p specifies undeclared variable "
- "`%s' @ %p\n",
- (void *) ir, ir->var->name, (void *) ir->var);
- abort();
- }
-
- this->validate_ir(ir, this->data);
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit(ir_if *ir)
-{
- if (ir->condition->type != glsl_type::bool_type) {
- printf("ir_if condition %s type instead of bool.\n",
- ir->condition->type->name);
- ir->print();
- printf("\n");
- abort();
- }
-
- return visit_continue;
-}
-
-
-ir_visitor_status
-ir_validate::visit_leave(ir_loop *ir)
-{
- if (ir->counter != NULL) {
- if ((ir->from == NULL) || (ir->from == NULL) || (ir->increment == NULL)) {
- printf("ir_loop has invalid loop controls:\n"
- " counter: %p\n"
- " from: %p\n"
- " to: %p\n"
- " increment: %p\n",
- (void *) ir->counter, (void *) ir->from, (void *) ir->to,
- (void *) ir->increment);
- abort();
- }
-
- if ((ir->cmp < ir_binop_less) || (ir->cmp > ir_binop_nequal)) {
- printf("ir_loop has invalid comparitor %d\n", ir->cmp);
- abort();
- }
- } else {
- if ((ir->from != NULL) || (ir->from != NULL) || (ir->increment != NULL)) {
- printf("ir_loop has invalid loop controls:\n"
- " counter: %p\n"
- " from: %p\n"
- " to: %p\n"
- " increment: %p\n",
- (void *) ir->counter, (void *) ir->from, (void *) ir->to,
- (void *) ir->increment);
- abort();
- }
- }
-
- return visit_continue;
-}
-
-
-ir_visitor_status
-ir_validate::visit_enter(ir_function *ir)
-{
- /* Function definitions cannot be nested.
- */
- if (this->current_function != NULL) {
- printf("Function definition nested inside another function "
- "definition:\n");
- printf("%s %p inside %s %p\n",
- ir->name, (void *) ir,
- this->current_function->name, (void *) this->current_function);
- abort();
- }
-
- /* Store the current function hierarchy being traversed. This is used
- * by the function signature visitor to ensure that the signatures are
- * linked with the correct functions.
- */
- this->current_function = ir;
-
- this->validate_ir(ir, this->data);
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit_leave(ir_function *ir)
-{
- assert(ralloc_parent(ir->name) == ir);
-
- this->current_function = NULL;
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit_enter(ir_function_signature *ir)
-{
- if (this->current_function != ir->function()) {
- printf("Function signature nested inside wrong function "
- "definition:\n");
- printf("%p inside %s %p instead of %s %p\n",
- (void *) ir,
- this->current_function->name, (void *) this->current_function,
- ir->function_name(), (void *) ir->function());
- abort();
- }
-
- this->validate_ir(ir, this->data);
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit_leave(ir_expression *ir)
-{
- switch (ir->operation) {
- case ir_unop_bit_not:
- assert(ir->operands[0]->type == ir->type);
- break;
- case ir_unop_logic_not:
- assert(ir->type->base_type == GLSL_TYPE_BOOL);
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
- break;
-
- case ir_unop_neg:
- case ir_unop_abs:
- case ir_unop_sign:
- case ir_unop_rcp:
- case ir_unop_rsq:
- case ir_unop_sqrt:
- assert(ir->type == ir->operands[0]->type);
- break;
-
- case ir_unop_exp:
- case ir_unop_log:
- case ir_unop_exp2:
- case ir_unop_log2:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
- assert(ir->type == ir->operands[0]->type);
- break;
-
- case ir_unop_f2i:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
- assert(ir->type->base_type == GLSL_TYPE_INT);
- break;
- case ir_unop_i2f:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_INT);
- assert(ir->type->base_type == GLSL_TYPE_FLOAT);
- break;
- case ir_unop_f2b:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
- assert(ir->type->base_type == GLSL_TYPE_BOOL);
- break;
- case ir_unop_b2f:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
- assert(ir->type->base_type == GLSL_TYPE_FLOAT);
- break;
- case ir_unop_i2b:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_INT);
- assert(ir->type->base_type == GLSL_TYPE_BOOL);
- break;
- case ir_unop_b2i:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
- assert(ir->type->base_type == GLSL_TYPE_INT);
- break;
- case ir_unop_u2f:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_UINT);
- assert(ir->type->base_type == GLSL_TYPE_FLOAT);
- break;
-
- case ir_unop_any:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
- assert(ir->type == glsl_type::bool_type);
- break;
-
- case ir_unop_trunc:
- case ir_unop_round_even:
- case ir_unop_ceil:
- case ir_unop_floor:
- case ir_unop_fract:
- case ir_unop_sin:
- case ir_unop_cos:
- case ir_unop_sin_reduced:
- case ir_unop_cos_reduced:
- case ir_unop_dFdx:
- case ir_unop_dFdy:
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
- assert(ir->operands[0]->type == ir->type);
- break;
-
- case ir_unop_noise:
- /* XXX what can we assert here? */
- break;
-
- case ir_binop_add:
- case ir_binop_sub:
- case ir_binop_mul:
- case ir_binop_div:
- case ir_binop_mod:
- case ir_binop_min:
- case ir_binop_max:
- case ir_binop_pow:
- if (ir->operands[0]->type->is_scalar())
- assert(ir->operands[1]->type == ir->type);
- else if (ir->operands[1]->type->is_scalar())
- assert(ir->operands[0]->type == ir->type);
- else if (ir->operands[0]->type->is_vector() &&
- ir->operands[1]->type->is_vector()) {
- assert(ir->operands[0]->type == ir->operands[1]->type);
- assert(ir->operands[0]->type == ir->type);
- }
- break;
-
- case ir_binop_less:
- case ir_binop_greater:
- case ir_binop_lequal:
- case ir_binop_gequal:
- case ir_binop_equal:
- case ir_binop_nequal:
- /* The semantics of the IR operators differ from the GLSL <, >, <=, >=,
- * ==, and != operators. The IR operators perform a component-wise
- * comparison on scalar or vector types and return a boolean scalar or
- * vector type of the same size.
- */
- assert(ir->type->base_type == GLSL_TYPE_BOOL);
- assert(ir->operands[0]->type == ir->operands[1]->type);
- assert(ir->operands[0]->type->is_vector()
- || ir->operands[0]->type->is_scalar());
- assert(ir->operands[0]->type->vector_elements
- == ir->type->vector_elements);
- break;
-
- case ir_binop_all_equal:
- case ir_binop_any_nequal:
- /* GLSL == and != operate on scalars, vectors, matrices and arrays, and
- * return a scalar boolean. The IR matches that.
- */
- assert(ir->type == glsl_type::bool_type);
- assert(ir->operands[0]->type == ir->operands[1]->type);
- break;
-
- case ir_binop_lshift:
- case ir_binop_rshift:
- assert(ir->operands[0]->type->is_integer() &&
- ir->operands[1]->type->is_integer());
- if (ir->operands[0]->type->is_scalar()) {
- assert(ir->operands[1]->type->is_scalar());
- }
- if (ir->operands[0]->type->is_vector() &&
- ir->operands[1]->type->is_vector()) {
- assert(ir->operands[0]->type->components() ==
- ir->operands[1]->type->components());
- }
- assert(ir->type == ir->operands[0]->type);
- break;
-
- case ir_binop_bit_and:
- case ir_binop_bit_xor:
- case ir_binop_bit_or:
- assert(ir->operands[0]->type->base_type ==
- ir->operands[1]->type->base_type);
- assert(ir->type->is_integer());
- if (ir->operands[0]->type->is_vector() &&
- ir->operands[1]->type->is_vector()) {
- assert(ir->operands[0]->type->vector_elements ==
- ir->operands[1]->type->vector_elements);
- }
- break;
-
- case ir_binop_logic_and:
- case ir_binop_logic_xor:
- case ir_binop_logic_or:
- assert(ir->type == glsl_type::bool_type);
- assert(ir->operands[0]->type == glsl_type::bool_type);
- assert(ir->operands[1]->type == glsl_type::bool_type);
- break;
-
- case ir_binop_dot:
- assert(ir->type == glsl_type::float_type);
- assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
- assert(ir->operands[0]->type->is_vector());
- assert(ir->operands[0]->type == ir->operands[1]->type);
- break;
-
- case ir_quadop_vector:
- /* The vector operator collects some number of scalars and generates a
- * vector from them.
- *
- * - All of the operands must be scalar.
- * - Number of operands must matche the size of the resulting vector.
- * - Base type of the operands must match the base type of the result.
- */
- assert(ir->type->is_vector());
- switch (ir->type->vector_elements) {
- case 2:
- assert(ir->operands[0]->type->is_scalar());
- assert(ir->operands[0]->type->base_type == ir->type->base_type);
- assert(ir->operands[1]->type->is_scalar());
- assert(ir->operands[1]->type->base_type == ir->type->base_type);
- assert(ir->operands[2] == NULL);
- assert(ir->operands[3] == NULL);
- break;
- case 3:
- assert(ir->operands[0]->type->is_scalar());
- assert(ir->operands[0]->type->base_type == ir->type->base_type);
- assert(ir->operands[1]->type->is_scalar());
- assert(ir->operands[1]->type->base_type == ir->type->base_type);
- assert(ir->operands[2]->type->is_scalar());
- assert(ir->operands[2]->type->base_type == ir->type->base_type);
- assert(ir->operands[3] == NULL);
- break;
- case 4:
- assert(ir->operands[0]->type->is_scalar());
- assert(ir->operands[0]->type->base_type == ir->type->base_type);
- assert(ir->operands[1]->type->is_scalar());
- assert(ir->operands[1]->type->base_type == ir->type->base_type);
- assert(ir->operands[2]->type->is_scalar());
- assert(ir->operands[2]->type->base_type == ir->type->base_type);
- assert(ir->operands[3]->type->is_scalar());
- assert(ir->operands[3]->type->base_type == ir->type->base_type);
- break;
- default:
- /* The is_vector assertion above should prevent execution from ever
- * getting here.
- */
- assert(!"Should not get here.");
- break;
- }
- }
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit_leave(ir_swizzle *ir)
-{
- int chans[4] = {ir->mask.x, ir->mask.y, ir->mask.z, ir->mask.w};
-
- for (unsigned int i = 0; i < ir->type->vector_elements; i++) {
- if (chans[i] >= ir->val->type->vector_elements) {
- printf("ir_swizzle @ %p specifies a channel not present "
- "in the value.\n", (void *) ir);
- ir->print();
- abort();
- }
- }
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit(ir_variable *ir)
-{
- /* An ir_variable is the one thing that can (and will) appear multiple times
- * in an IR tree. It is added to the hashtable so that it can be used
- * in the ir_dereference_variable handler to ensure that a variable is
- * declared before it is dereferenced.
- */
- if (ir->name)
- assert(ralloc_parent(ir->name) == ir);
-
- hash_table_insert(ht, ir, ir);
- return visit_continue;
-}
-
-ir_visitor_status
-ir_validate::visit_enter(ir_assignment *ir)
-{
- const ir_dereference *const lhs = ir->lhs;
- if (lhs->type->is_scalar() || lhs->type->is_vector()) {
- if (ir->write_mask == 0) {
- printf("Assignment LHS is %s, but write mask is 0:\n",
- lhs->type->is_scalar() ? "scalar" : "vector");
- ir->print();
- abort();
- }
-
- int lhs_components = 0;
- for (int i = 0; i < 4; i++) {
- if (ir->write_mask & (1 << i))
- lhs_components++;
- }
-
- if (lhs_components != ir->rhs->type->vector_elements) {
- printf("Assignment count of LHS write mask channels enabled not\n"
- "matching RHS vector size (%d LHS, %d RHS).\n",
- lhs_components, ir->rhs->type->vector_elements);
- ir->print();
- abort();
- }
- }
-
- this->validate_ir(ir, this->data);
-
- return visit_continue;
-}
-
-void
-ir_validate::validate_ir(ir_instruction *ir, void *data)
-{
- struct hash_table *ht = (struct hash_table *) data;
-
- if (hash_table_find(ht, ir)) {
- printf("Instruction node present twice in ir tree:\n");
- ir->print();
- printf("\n");
- abort();
- }
- hash_table_insert(ht, ir, ir);
-}
-
-void
-check_node_type(ir_instruction *ir, void *data)
-{
- (void) data;
-
- if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {
- printf("Instruction node with unset type\n");
- ir->print(); printf("\n");
- }
- assert(ir->type != glsl_type::error_type);
-}
-
-void
-validate_ir_tree(exec_list *instructions)
-{
- ir_validate v;
-
- v.run(instructions);
-
- foreach_iter(exec_list_iterator, iter, *instructions) {
- ir_instruction *ir = (ir_instruction *)iter.get();
-
- visit_tree(ir, check_node_type, NULL);
- }
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 ir_validate.cpp
+ *
+ * Attempts to verify that various invariants of the IR tree are true.
+ *
+ * In particular, at the moment it makes sure that no single
+ * ir_instruction node except for ir_variable appears multiple times
+ * in the ir tree. ir_variable does appear multiple times: Once as a
+ * declaration in an exec_list, and multiple times as the endpoint of
+ * a dereference chain.
+ */
+
+#include <inttypes.h>
+#include "ir.h"
+#include "ir_hierarchical_visitor.h"
+#include "program/hash_table.h"
+#include "glsl_types.h"
+
+class ir_validate : public ir_hierarchical_visitor {
+public:
+ ir_validate()
+ {
+ this->ht = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+
+ this->current_function = NULL;
+
+ this->callback = ir_validate::validate_ir;
+ this->data = ht;
+ }
+
+ ~ir_validate()
+ {
+ hash_table_dtor(this->ht);
+ }
+
+ virtual ir_visitor_status visit(ir_variable *v);
+ virtual ir_visitor_status visit(ir_dereference_variable *ir);
+ virtual ir_visitor_status visit(ir_if *ir);
+
+ virtual ir_visitor_status visit_leave(ir_loop *ir);
+ virtual ir_visitor_status visit_enter(ir_function *ir);
+ virtual ir_visitor_status visit_leave(ir_function *ir);
+ virtual ir_visitor_status visit_enter(ir_function_signature *ir);
+
+ virtual ir_visitor_status visit_leave(ir_expression *ir);
+ virtual ir_visitor_status visit_leave(ir_swizzle *ir);
+
+ virtual ir_visitor_status visit_enter(ir_assignment *ir);
+
+ static void validate_ir(ir_instruction *ir, void *data);
+
+ ir_function *current_function;
+
+ struct hash_table *ht;
+};
+
+
+ir_visitor_status
+ir_validate::visit(ir_dereference_variable *ir)
+{
+ if ((ir->var == NULL) || (ir->var->as_variable() == NULL)) {
+ printf("ir_dereference_variable @ %p does not specify a variable %p\n",
+ (void *) ir, (void *) ir->var);
+ abort();
+ }
+
+ if (hash_table_find(ht, ir->var) == NULL) {
+ printf("ir_dereference_variable @ %p specifies undeclared variable "
+ "`%s' @ %p\n",
+ (void *) ir, ir->var->name, (void *) ir->var);
+ abort();
+ }
+
+ this->validate_ir(ir, this->data);
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit(ir_if *ir)
+{
+ if (ir->condition->type != glsl_type::bool_type) {
+ printf("ir_if condition %s type instead of bool.\n",
+ ir->condition->type->name);
+ ir->print();
+ printf("\n");
+ abort();
+ }
+
+ return visit_continue;
+}
+
+
+ir_visitor_status
+ir_validate::visit_leave(ir_loop *ir)
+{
+ if (ir->counter != NULL) {
+ if ((ir->from == NULL) || (ir->from == NULL) || (ir->increment == NULL)) {
+ printf("ir_loop has invalid loop controls:\n"
+ " counter: %p\n"
+ " from: %p\n"
+ " to: %p\n"
+ " increment: %p\n",
+ (void *) ir->counter, (void *) ir->from, (void *) ir->to,
+ (void *) ir->increment);
+ abort();
+ }
+
+ if ((ir->cmp < ir_binop_less) || (ir->cmp > ir_binop_nequal)) {
+ printf("ir_loop has invalid comparitor %d\n", ir->cmp);
+ abort();
+ }
+ } else {
+ if ((ir->from != NULL) || (ir->from != NULL) || (ir->increment != NULL)) {
+ printf("ir_loop has invalid loop controls:\n"
+ " counter: %p\n"
+ " from: %p\n"
+ " to: %p\n"
+ " increment: %p\n",
+ (void *) ir->counter, (void *) ir->from, (void *) ir->to,
+ (void *) ir->increment);
+ abort();
+ }
+ }
+
+ return visit_continue;
+}
+
+
+ir_visitor_status
+ir_validate::visit_enter(ir_function *ir)
+{
+ /* Function definitions cannot be nested.
+ */
+ if (this->current_function != NULL) {
+ printf("Function definition nested inside another function "
+ "definition:\n");
+ printf("%s %p inside %s %p\n",
+ ir->name, (void *) ir,
+ this->current_function->name, (void *) this->current_function);
+ abort();
+ }
+
+ /* Store the current function hierarchy being traversed. This is used
+ * by the function signature visitor to ensure that the signatures are
+ * linked with the correct functions.
+ */
+ this->current_function = ir;
+
+ this->validate_ir(ir, this->data);
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit_leave(ir_function *ir)
+{
+ assert(ralloc_parent(ir->name) == ir);
+
+ this->current_function = NULL;
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit_enter(ir_function_signature *ir)
+{
+ if (this->current_function != ir->function()) {
+ printf("Function signature nested inside wrong function "
+ "definition:\n");
+ printf("%p inside %s %p instead of %s %p\n",
+ (void *) ir,
+ this->current_function->name, (void *) this->current_function,
+ ir->function_name(), (void *) ir->function());
+ abort();
+ }
+
+ this->validate_ir(ir, this->data);
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit_leave(ir_expression *ir)
+{
+ switch (ir->operation) {
+ case ir_unop_bit_not:
+ assert(ir->operands[0]->type == ir->type);
+ break;
+ case ir_unop_logic_not:
+ assert(ir->type->base_type == GLSL_TYPE_BOOL);
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
+ break;
+
+ case ir_unop_neg:
+ case ir_unop_abs:
+ case ir_unop_sign:
+ case ir_unop_rcp:
+ case ir_unop_rsq:
+ case ir_unop_sqrt:
+ assert(ir->type == ir->operands[0]->type);
+ break;
+
+ case ir_unop_exp:
+ case ir_unop_log:
+ case ir_unop_exp2:
+ case ir_unop_log2:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
+ assert(ir->type == ir->operands[0]->type);
+ break;
+
+ case ir_unop_f2i:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
+ assert(ir->type->base_type == GLSL_TYPE_INT);
+ break;
+ case ir_unop_i2f:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_INT);
+ assert(ir->type->base_type == GLSL_TYPE_FLOAT);
+ break;
+ case ir_unop_f2b:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
+ assert(ir->type->base_type == GLSL_TYPE_BOOL);
+ break;
+ case ir_unop_b2f:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
+ assert(ir->type->base_type == GLSL_TYPE_FLOAT);
+ break;
+ case ir_unop_i2b:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_INT);
+ assert(ir->type->base_type == GLSL_TYPE_BOOL);
+ break;
+ case ir_unop_b2i:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
+ assert(ir->type->base_type == GLSL_TYPE_INT);
+ break;
+ case ir_unop_u2f:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_UINT);
+ assert(ir->type->base_type == GLSL_TYPE_FLOAT);
+ break;
+
+ case ir_unop_any:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_BOOL);
+ assert(ir->type == glsl_type::bool_type);
+ break;
+
+ case ir_unop_trunc:
+ case ir_unop_round_even:
+ case ir_unop_ceil:
+ case ir_unop_floor:
+ case ir_unop_fract:
+ case ir_unop_sin:
+ case ir_unop_cos:
+ case ir_unop_sin_reduced:
+ case ir_unop_cos_reduced:
+ case ir_unop_dFdx:
+ case ir_unop_dFdy:
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
+ assert(ir->operands[0]->type == ir->type);
+ break;
+
+ case ir_unop_noise:
+ /* XXX what can we assert here? */
+ break;
+
+ case ir_binop_add:
+ case ir_binop_sub:
+ case ir_binop_mul:
+ case ir_binop_div:
+ case ir_binop_mod:
+ case ir_binop_min:
+ case ir_binop_max:
+ case ir_binop_pow:
+ if (ir->operands[0]->type->is_scalar())
+ assert(ir->operands[1]->type == ir->type);
+ else if (ir->operands[1]->type->is_scalar())
+ assert(ir->operands[0]->type == ir->type);
+ else if (ir->operands[0]->type->is_vector() &&
+ ir->operands[1]->type->is_vector()) {
+ assert(ir->operands[0]->type == ir->operands[1]->type);
+ assert(ir->operands[0]->type == ir->type);
+ }
+ break;
+
+ case ir_binop_less:
+ case ir_binop_greater:
+ case ir_binop_lequal:
+ case ir_binop_gequal:
+ case ir_binop_equal:
+ case ir_binop_nequal:
+ /* The semantics of the IR operators differ from the GLSL <, >, <=, >=,
+ * ==, and != operators. The IR operators perform a component-wise
+ * comparison on scalar or vector types and return a boolean scalar or
+ * vector type of the same size.
+ */
+ assert(ir->type->base_type == GLSL_TYPE_BOOL);
+ assert(ir->operands[0]->type == ir->operands[1]->type);
+ assert(ir->operands[0]->type->is_vector()
+ || ir->operands[0]->type->is_scalar());
+ assert(ir->operands[0]->type->vector_elements
+ == ir->type->vector_elements);
+ break;
+
+ case ir_binop_all_equal:
+ case ir_binop_any_nequal:
+ /* GLSL == and != operate on scalars, vectors, matrices and arrays, and
+ * return a scalar boolean. The IR matches that.
+ */
+ assert(ir->type == glsl_type::bool_type);
+ assert(ir->operands[0]->type == ir->operands[1]->type);
+ break;
+
+ case ir_binop_lshift:
+ case ir_binop_rshift:
+ assert(ir->operands[0]->type->is_integer() &&
+ ir->operands[1]->type->is_integer());
+ if (ir->operands[0]->type->is_scalar()) {
+ assert(ir->operands[1]->type->is_scalar());
+ }
+ if (ir->operands[0]->type->is_vector() &&
+ ir->operands[1]->type->is_vector()) {
+ assert(ir->operands[0]->type->components() ==
+ ir->operands[1]->type->components());
+ }
+ assert(ir->type == ir->operands[0]->type);
+ break;
+
+ case ir_binop_bit_and:
+ case ir_binop_bit_xor:
+ case ir_binop_bit_or:
+ assert(ir->operands[0]->type->base_type ==
+ ir->operands[1]->type->base_type);
+ assert(ir->type->is_integer());
+ if (ir->operands[0]->type->is_vector() &&
+ ir->operands[1]->type->is_vector()) {
+ assert(ir->operands[0]->type->vector_elements ==
+ ir->operands[1]->type->vector_elements);
+ }
+ break;
+
+ case ir_binop_logic_and:
+ case ir_binop_logic_xor:
+ case ir_binop_logic_or:
+ assert(ir->type == glsl_type::bool_type);
+ assert(ir->operands[0]->type == glsl_type::bool_type);
+ assert(ir->operands[1]->type == glsl_type::bool_type);
+ break;
+
+ case ir_binop_dot:
+ assert(ir->type == glsl_type::float_type);
+ assert(ir->operands[0]->type->base_type == GLSL_TYPE_FLOAT);
+ assert(ir->operands[0]->type->is_vector());
+ assert(ir->operands[0]->type == ir->operands[1]->type);
+ break;
+
+ case ir_quadop_vector:
+ /* The vector operator collects some number of scalars and generates a
+ * vector from them.
+ *
+ * - All of the operands must be scalar.
+ * - Number of operands must matche the size of the resulting vector.
+ * - Base type of the operands must match the base type of the result.
+ */
+ assert(ir->type->is_vector());
+ switch (ir->type->vector_elements) {
+ case 2:
+ assert(ir->operands[0]->type->is_scalar());
+ assert(ir->operands[0]->type->base_type == ir->type->base_type);
+ assert(ir->operands[1]->type->is_scalar());
+ assert(ir->operands[1]->type->base_type == ir->type->base_type);
+ assert(ir->operands[2] == NULL);
+ assert(ir->operands[3] == NULL);
+ break;
+ case 3:
+ assert(ir->operands[0]->type->is_scalar());
+ assert(ir->operands[0]->type->base_type == ir->type->base_type);
+ assert(ir->operands[1]->type->is_scalar());
+ assert(ir->operands[1]->type->base_type == ir->type->base_type);
+ assert(ir->operands[2]->type->is_scalar());
+ assert(ir->operands[2]->type->base_type == ir->type->base_type);
+ assert(ir->operands[3] == NULL);
+ break;
+ case 4:
+ assert(ir->operands[0]->type->is_scalar());
+ assert(ir->operands[0]->type->base_type == ir->type->base_type);
+ assert(ir->operands[1]->type->is_scalar());
+ assert(ir->operands[1]->type->base_type == ir->type->base_type);
+ assert(ir->operands[2]->type->is_scalar());
+ assert(ir->operands[2]->type->base_type == ir->type->base_type);
+ assert(ir->operands[3]->type->is_scalar());
+ assert(ir->operands[3]->type->base_type == ir->type->base_type);
+ break;
+ default:
+ /* The is_vector assertion above should prevent execution from ever
+ * getting here.
+ */
+ assert(!"Should not get here.");
+ break;
+ }
+ }
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit_leave(ir_swizzle *ir)
+{
+ int chans[4] = {ir->mask.x, ir->mask.y, ir->mask.z, ir->mask.w};
+
+ for (unsigned int i = 0; i < ir->type->vector_elements; i++) {
+ if (chans[i] >= ir->val->type->vector_elements) {
+ printf("ir_swizzle @ %p specifies a channel not present "
+ "in the value.\n", (void *) ir);
+ ir->print();
+ abort();
+ }
+ }
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit(ir_variable *ir)
+{
+ /* An ir_variable is the one thing that can (and will) appear multiple times
+ * in an IR tree. It is added to the hashtable so that it can be used
+ * in the ir_dereference_variable handler to ensure that a variable is
+ * declared before it is dereferenced.
+ */
+ if (ir->name)
+ assert(ralloc_parent(ir->name) == ir);
+
+ hash_table_insert(ht, ir, ir);
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_validate::visit_enter(ir_assignment *ir)
+{
+ const ir_dereference *const lhs = ir->lhs;
+ if (lhs->type->is_scalar() || lhs->type->is_vector()) {
+ if (ir->write_mask == 0) {
+ printf("Assignment LHS is %s, but write mask is 0:\n",
+ lhs->type->is_scalar() ? "scalar" : "vector");
+ ir->print();
+ abort();
+ }
+
+ int lhs_components = 0;
+ for (int i = 0; i < 4; i++) {
+ if (ir->write_mask & (1 << i))
+ lhs_components++;
+ }
+
+ if (lhs_components != ir->rhs->type->vector_elements) {
+ printf("Assignment count of LHS write mask channels enabled not\n"
+ "matching RHS vector size (%d LHS, %d RHS).\n",
+ lhs_components, ir->rhs->type->vector_elements);
+ ir->print();
+ abort();
+ }
+ }
+
+ this->validate_ir(ir, this->data);
+
+ return visit_continue;
+}
+
+void
+ir_validate::validate_ir(ir_instruction *ir, void *data)
+{
+ struct hash_table *ht = (struct hash_table *) data;
+
+ if (hash_table_find(ht, ir)) {
+ printf("Instruction node present twice in ir tree:\n");
+ ir->print();
+ printf("\n");
+ abort();
+ }
+ hash_table_insert(ht, ir, ir);
+}
+
+void
+check_node_type(ir_instruction *ir, void *data)
+{
+ (void) data;
+
+ if (ir->ir_type <= ir_type_unset || ir->ir_type >= ir_type_max) {
+ printf("Instruction node with unset type\n");
+ ir->print(); printf("\n");
+ }
+ assert(ir->type != glsl_type::error_type);
+}
+
+void
+validate_ir_tree(exec_list *instructions)
+{
+ ir_validate v;
+
+ v.run(instructions);
+
+ foreach_iter(exec_list_iterator, iter, *instructions) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+
+ visit_tree(ir, check_node_type, NULL);
+ }
+}
diff --git a/mesalib/src/glsl/link_functions.cpp b/mesalib/src/glsl/link_functions.cpp
index 5851c14d6..bc8758438 100644
--- a/mesalib/src/glsl/link_functions.cpp
+++ b/mesalib/src/glsl/link_functions.cpp
@@ -1,266 +1,266 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include "main/core.h"
-#include "glsl_symbol_table.h"
-#include "glsl_parser_extras.h"
-#include "ir.h"
-#include "program.h"
-#include "program/hash_table.h"
-#include "linker.h"
-
-static ir_function_signature *
-find_matching_signature(const char *name, const exec_list *actual_parameters,
- gl_shader **shader_list, unsigned num_shaders);
-
-class call_link_visitor : public ir_hierarchical_visitor {
-public:
- call_link_visitor(gl_shader_program *prog, gl_shader *linked,
- gl_shader **shader_list, unsigned num_shaders)
- {
- this->prog = prog;
- this->shader_list = shader_list;
- this->num_shaders = num_shaders;
- this->success = true;
- this->linked = linked;
-
- this->locals = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
- }
-
- ~call_link_visitor()
- {
- hash_table_dtor(this->locals);
- }
-
- virtual ir_visitor_status visit(ir_variable *ir)
- {
- hash_table_insert(locals, ir, ir);
- return visit_continue;
- }
-
- virtual ir_visitor_status visit_enter(ir_call *ir)
- {
- /* If ir is an ir_call from a function that was imported from another
- * shader callee will point to an ir_function_signature in the original
- * shader. In this case the function signature MUST NOT BE MODIFIED.
- * Doing so will modify the original shader. This may prevent that
- * shader from being linkable in other programs.
- */
- const ir_function_signature *const callee = ir->get_callee();
- assert(callee != NULL);
- const char *const name = callee->function_name();
-
- /* Determine if the requested function signature already exists in the
- * final linked shader. If it does, use it as the target of the call.
- */
- ir_function_signature *sig =
- find_matching_signature(name, &callee->parameters, &linked, 1);
- if (sig != NULL) {
- ir->set_callee(sig);
- return visit_continue;
- }
-
- /* Try to find the signature in one of the other shaders that is being
- * linked. If it's not found there, return an error.
- */
- sig = find_matching_signature(name, &ir->actual_parameters, shader_list,
- num_shaders);
- if (sig == NULL) {
- /* FINISHME: Log the full signature of unresolved function.
- */
- linker_error_printf(this->prog, "unresolved reference to function "
- "`%s'\n", name);
- this->success = false;
- return visit_stop;
- }
-
- /* Find the prototype information in the linked shader. Generate any
- * details that may be missing.
- */
- ir_function *f = linked->symbols->get_function(name);
- if (f == NULL)
- f = new(linked) ir_function(name);
-
- ir_function_signature *linked_sig =
- f->exact_matching_signature(&callee->parameters);
- if (linked_sig == NULL) {
- linked_sig = new(linked) ir_function_signature(callee->return_type);
- f->add_signature(linked_sig);
- }
-
- /* At this point linked_sig and called may be the same. If ir is an
- * ir_call from linked then linked_sig and callee will be
- * ir_function_signatures that have no definitions (is_defined is false).
- */
- assert(!linked_sig->is_defined);
- assert(linked_sig->body.is_empty());
-
- /* Create an in-place clone of the function definition. This multistep
- * process introduces some complexity here, but it has some advantages.
- * The parameter list and the and function body are cloned separately.
- * The clone of the parameter list is used to prime the hashtable used
- * to replace variable references in the cloned body.
- *
- * The big advantage is that the ir_function_signature does not change.
- * This means that we don't have to process the rest of the IR tree to
- * patch ir_call nodes. In addition, there is no way to remove or
- * replace signature stored in a function. One could easily be added,
- * but this avoids the need.
- */
- struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
- exec_list formal_parameters;
- foreach_list_const(node, &sig->parameters) {
- const ir_instruction *const original = (ir_instruction *) node;
- assert(const_cast<ir_instruction *>(original)->as_variable());
-
- ir_instruction *copy = original->clone(linked, ht);
- formal_parameters.push_tail(copy);
- }
-
- linked_sig->replace_parameters(&formal_parameters);
-
- foreach_list_const(node, &sig->body) {
- const ir_instruction *const original = (ir_instruction *) node;
-
- ir_instruction *copy = original->clone(linked, ht);
- linked_sig->body.push_tail(copy);
- }
-
- linked_sig->is_defined = true;
- hash_table_dtor(ht);
-
- /* Patch references inside the function to things outside the function
- * (i.e., function calls and global variables).
- */
- linked_sig->accept(this);
-
- ir->set_callee(linked_sig);
-
- return visit_continue;
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (hash_table_find(locals, ir->var) == NULL) {
- /* The non-function variable must be a global, so try to find the
- * variable in the shader's symbol table. If the variable is not
- * found, then it's a global that *MUST* be defined in the original
- * shader.
- */
- ir_variable *var = linked->symbols->get_variable(ir->var->name);
- if (var == NULL) {
- /* Clone the ir_variable that the dereference already has and add
- * it to the linked shader.
- */
- var = ir->var->clone(linked, NULL);
- linked->symbols->add_variable(var);
- linked->ir->push_head(var);
- } else if (var->type->is_array()) {
- /* It is possible to have a global array declared in multiple
- * shaders without a size. The array is implicitly sized by the
- * maximal access to it in *any* shader. Because of this, we
- * need to track the maximal access to the array as linking pulls
- * more functions in that access the array.
- */
- var->max_array_access =
- MAX2(var->max_array_access, ir->var->max_array_access);
-
- if (var->type->length == 0 && ir->var->type->length != 0)
- var->type = ir->var->type;
- }
-
- ir->var = var;
- }
-
- return visit_continue;
- }
-
- /** Was function linking successful? */
- bool success;
-
-private:
- /**
- * Shader program being linked
- *
- * This is only used for logging error messages.
- */
- gl_shader_program *prog;
-
- /** List of shaders available for linking. */
- gl_shader **shader_list;
-
- /** Number of shaders available for linking. */
- unsigned num_shaders;
-
- /**
- * Final linked shader
- *
- * This is used two ways. It is used to find global variables in the
- * linked shader that are accessed by the function. It is also used to add
- * global variables from the shader where the function originated.
- */
- gl_shader *linked;
-
- /**
- * Table of variables local to the function.
- */
- hash_table *locals;
-};
-
-
-/**
- * Searches a list of shaders for a particular function definition
- */
-ir_function_signature *
-find_matching_signature(const char *name, const exec_list *actual_parameters,
- gl_shader **shader_list, unsigned num_shaders)
-{
- for (unsigned i = 0; i < num_shaders; i++) {
- ir_function *const f = shader_list[i]->symbols->get_function(name);
-
- if (f == NULL)
- continue;
-
- ir_function_signature *sig = f->matching_signature(actual_parameters);
-
- if ((sig == NULL) || !sig->is_defined)
- continue;
-
- return sig;
- }
-
- return NULL;
-}
-
-
-bool
-link_function_calls(gl_shader_program *prog, gl_shader *main,
- gl_shader **shader_list, unsigned num_shaders)
-{
- call_link_visitor v(prog, main, shader_list, num_shaders);
-
- v.run(main->ir);
- return v.success;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include "main/core.h"
+#include "glsl_symbol_table.h"
+#include "glsl_parser_extras.h"
+#include "ir.h"
+#include "program.h"
+#include "program/hash_table.h"
+#include "linker.h"
+
+static ir_function_signature *
+find_matching_signature(const char *name, const exec_list *actual_parameters,
+ gl_shader **shader_list, unsigned num_shaders);
+
+class call_link_visitor : public ir_hierarchical_visitor {
+public:
+ call_link_visitor(gl_shader_program *prog, gl_shader *linked,
+ gl_shader **shader_list, unsigned num_shaders)
+ {
+ this->prog = prog;
+ this->shader_list = shader_list;
+ this->num_shaders = num_shaders;
+ this->success = true;
+ this->linked = linked;
+
+ this->locals = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+ }
+
+ ~call_link_visitor()
+ {
+ hash_table_dtor(this->locals);
+ }
+
+ virtual ir_visitor_status visit(ir_variable *ir)
+ {
+ hash_table_insert(locals, ir, ir);
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_call *ir)
+ {
+ /* If ir is an ir_call from a function that was imported from another
+ * shader callee will point to an ir_function_signature in the original
+ * shader. In this case the function signature MUST NOT BE MODIFIED.
+ * Doing so will modify the original shader. This may prevent that
+ * shader from being linkable in other programs.
+ */
+ const ir_function_signature *const callee = ir->get_callee();
+ assert(callee != NULL);
+ const char *const name = callee->function_name();
+
+ /* Determine if the requested function signature already exists in the
+ * final linked shader. If it does, use it as the target of the call.
+ */
+ ir_function_signature *sig =
+ find_matching_signature(name, &callee->parameters, &linked, 1);
+ if (sig != NULL) {
+ ir->set_callee(sig);
+ return visit_continue;
+ }
+
+ /* Try to find the signature in one of the other shaders that is being
+ * linked. If it's not found there, return an error.
+ */
+ sig = find_matching_signature(name, &ir->actual_parameters, shader_list,
+ num_shaders);
+ if (sig == NULL) {
+ /* FINISHME: Log the full signature of unresolved function.
+ */
+ linker_error_printf(this->prog, "unresolved reference to function "
+ "`%s'\n", name);
+ this->success = false;
+ return visit_stop;
+ }
+
+ /* Find the prototype information in the linked shader. Generate any
+ * details that may be missing.
+ */
+ ir_function *f = linked->symbols->get_function(name);
+ if (f == NULL)
+ f = new(linked) ir_function(name);
+
+ ir_function_signature *linked_sig =
+ f->exact_matching_signature(&callee->parameters);
+ if (linked_sig == NULL) {
+ linked_sig = new(linked) ir_function_signature(callee->return_type);
+ f->add_signature(linked_sig);
+ }
+
+ /* At this point linked_sig and called may be the same. If ir is an
+ * ir_call from linked then linked_sig and callee will be
+ * ir_function_signatures that have no definitions (is_defined is false).
+ */
+ assert(!linked_sig->is_defined);
+ assert(linked_sig->body.is_empty());
+
+ /* Create an in-place clone of the function definition. This multistep
+ * process introduces some complexity here, but it has some advantages.
+ * The parameter list and the and function body are cloned separately.
+ * The clone of the parameter list is used to prime the hashtable used
+ * to replace variable references in the cloned body.
+ *
+ * The big advantage is that the ir_function_signature does not change.
+ * This means that we don't have to process the rest of the IR tree to
+ * patch ir_call nodes. In addition, there is no way to remove or
+ * replace signature stored in a function. One could easily be added,
+ * but this avoids the need.
+ */
+ struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+ exec_list formal_parameters;
+ foreach_list_const(node, &sig->parameters) {
+ const ir_instruction *const original = (ir_instruction *) node;
+ assert(const_cast<ir_instruction *>(original)->as_variable());
+
+ ir_instruction *copy = original->clone(linked, ht);
+ formal_parameters.push_tail(copy);
+ }
+
+ linked_sig->replace_parameters(&formal_parameters);
+
+ foreach_list_const(node, &sig->body) {
+ const ir_instruction *const original = (ir_instruction *) node;
+
+ ir_instruction *copy = original->clone(linked, ht);
+ linked_sig->body.push_tail(copy);
+ }
+
+ linked_sig->is_defined = true;
+ hash_table_dtor(ht);
+
+ /* Patch references inside the function to things outside the function
+ * (i.e., function calls and global variables).
+ */
+ linked_sig->accept(this);
+
+ ir->set_callee(linked_sig);
+
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (hash_table_find(locals, ir->var) == NULL) {
+ /* The non-function variable must be a global, so try to find the
+ * variable in the shader's symbol table. If the variable is not
+ * found, then it's a global that *MUST* be defined in the original
+ * shader.
+ */
+ ir_variable *var = linked->symbols->get_variable(ir->var->name);
+ if (var == NULL) {
+ /* Clone the ir_variable that the dereference already has and add
+ * it to the linked shader.
+ */
+ var = ir->var->clone(linked, NULL);
+ linked->symbols->add_variable(var);
+ linked->ir->push_head(var);
+ } else if (var->type->is_array()) {
+ /* It is possible to have a global array declared in multiple
+ * shaders without a size. The array is implicitly sized by the
+ * maximal access to it in *any* shader. Because of this, we
+ * need to track the maximal access to the array as linking pulls
+ * more functions in that access the array.
+ */
+ var->max_array_access =
+ MAX2(var->max_array_access, ir->var->max_array_access);
+
+ if (var->type->length == 0 && ir->var->type->length != 0)
+ var->type = ir->var->type;
+ }
+
+ ir->var = var;
+ }
+
+ return visit_continue;
+ }
+
+ /** Was function linking successful? */
+ bool success;
+
+private:
+ /**
+ * Shader program being linked
+ *
+ * This is only used for logging error messages.
+ */
+ gl_shader_program *prog;
+
+ /** List of shaders available for linking. */
+ gl_shader **shader_list;
+
+ /** Number of shaders available for linking. */
+ unsigned num_shaders;
+
+ /**
+ * Final linked shader
+ *
+ * This is used two ways. It is used to find global variables in the
+ * linked shader that are accessed by the function. It is also used to add
+ * global variables from the shader where the function originated.
+ */
+ gl_shader *linked;
+
+ /**
+ * Table of variables local to the function.
+ */
+ hash_table *locals;
+};
+
+
+/**
+ * Searches a list of shaders for a particular function definition
+ */
+ir_function_signature *
+find_matching_signature(const char *name, const exec_list *actual_parameters,
+ gl_shader **shader_list, unsigned num_shaders)
+{
+ for (unsigned i = 0; i < num_shaders; i++) {
+ ir_function *const f = shader_list[i]->symbols->get_function(name);
+
+ if (f == NULL)
+ continue;
+
+ ir_function_signature *sig = f->matching_signature(actual_parameters);
+
+ if ((sig == NULL) || !sig->is_defined)
+ continue;
+
+ return sig;
+ }
+
+ return NULL;
+}
+
+
+bool
+link_function_calls(gl_shader_program *prog, gl_shader *main,
+ gl_shader **shader_list, unsigned num_shaders)
+{
+ call_link_visitor v(prog, main, shader_list, num_shaders);
+
+ v.run(main->ir);
+ return v.success;
+}
diff --git a/mesalib/src/glsl/linker.cpp b/mesalib/src/glsl/linker.cpp
index 7db5c5e8d..7760b4f2c 100644
--- a/mesalib/src/glsl/linker.cpp
+++ b/mesalib/src/glsl/linker.cpp
@@ -1,1709 +1,1709 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 linker.cpp
- * GLSL linker implementation
- *
- * Given a set of shaders that are to be linked to generate a final program,
- * there are three distinct stages.
- *
- * In the first stage shaders are partitioned into groups based on the shader
- * type. All shaders of a particular type (e.g., vertex shaders) are linked
- * together.
- *
- * - Undefined references in each shader are resolve to definitions in
- * another shader.
- * - Types and qualifiers of uniforms, outputs, and global variables defined
- * in multiple shaders with the same name are verified to be the same.
- * - Initializers for uniforms and global variables defined
- * in multiple shaders with the same name are verified to be the same.
- *
- * The result, in the terminology of the GLSL spec, is a set of shader
- * executables for each processing unit.
- *
- * After the first stage is complete, a series of semantic checks are performed
- * on each of the shader executables.
- *
- * - Each shader executable must define a \c main function.
- * - Each vertex shader executable must write to \c gl_Position.
- * - Each fragment shader executable must write to either \c gl_FragData or
- * \c gl_FragColor.
- *
- * In the final stage individual shader executables are linked to create a
- * complete exectuable.
- *
- * - Types of uniforms defined in multiple shader stages with the same name
- * are verified to be the same.
- * - Initializers for uniforms defined in multiple shader stages with the
- * same name are verified to be the same.
- * - Types and qualifiers of outputs defined in one stage are verified to
- * be the same as the types and qualifiers of inputs defined with the same
- * name in a later stage.
- *
- * \author Ian Romanick <ian.d.romanick@intel.com>
- */
-
-#include "main/core.h"
-#include "glsl_symbol_table.h"
-#include "ir.h"
-#include "program.h"
-#include "program/hash_table.h"
-#include "linker.h"
-#include "ir_optimization.h"
-
-extern "C" {
-#include "main/shaderobj.h"
-}
-
-/**
- * Visitor that determines whether or not a variable is ever written.
- */
-class find_assignment_visitor : public ir_hierarchical_visitor {
-public:
- find_assignment_visitor(const char *name)
- : name(name), found(false)
- {
- /* empty */
- }
-
- virtual ir_visitor_status visit_enter(ir_assignment *ir)
- {
- ir_variable *const var = ir->lhs->variable_referenced();
-
- if (strcmp(name, var->name) == 0) {
- found = true;
- return visit_stop;
- }
-
- return visit_continue_with_parent;
- }
-
- virtual ir_visitor_status visit_enter(ir_call *ir)
- {
- exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_rvalue *param_rval = (ir_rvalue *)iter.get();
- ir_variable *sig_param = (ir_variable *)sig_iter.get();
-
- if (sig_param->mode == ir_var_out ||
- sig_param->mode == ir_var_inout) {
- ir_variable *var = param_rval->variable_referenced();
- if (var && strcmp(name, var->name) == 0) {
- found = true;
- return visit_stop;
- }
- }
- sig_iter.next();
- }
-
- return visit_continue_with_parent;
- }
-
- bool variable_found()
- {
- return found;
- }
-
-private:
- const char *name; /**< Find writes to a variable with this name. */
- bool found; /**< Was a write to the variable found? */
-};
-
-
-/**
- * Visitor that determines whether or not a variable is ever read.
- */
-class find_deref_visitor : public ir_hierarchical_visitor {
-public:
- find_deref_visitor(const char *name)
- : name(name), found(false)
- {
- /* empty */
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (strcmp(this->name, ir->var->name) == 0) {
- this->found = true;
- return visit_stop;
- }
-
- return visit_continue;
- }
-
- bool variable_found() const
- {
- return this->found;
- }
-
-private:
- const char *name; /**< Find writes to a variable with this name. */
- bool found; /**< Was a write to the variable found? */
-};
-
-
-void
-linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
-{
- va_list ap;
-
- ralloc_strcat(&prog->InfoLog, "error: ");
- va_start(ap, fmt);
- ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
- va_end(ap);
-}
-
-
-void
-invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
- int generic_base)
-{
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != (unsigned) mode))
- continue;
-
- /* Only assign locations for generic attributes / varyings / etc.
- */
- if ((var->location >= generic_base) && !var->explicit_location)
- var->location = -1;
- }
-}
-
-
-/**
- * Determine the number of attribute slots required for a particular type
- *
- * This code is here because it implements the language rules of a specific
- * GLSL version. Since it's a property of the language and not a property of
- * types in general, it doesn't really belong in glsl_type.
- */
-unsigned
-count_attribute_slots(const glsl_type *t)
-{
- /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
- *
- * "A scalar input counts the same amount against this limit as a vec4,
- * so applications may want to consider packing groups of four
- * unrelated float inputs together into a vector to better utilize the
- * capabilities of the underlying hardware. A matrix input will use up
- * multiple locations. The number of locations used will equal the
- * number of columns in the matrix."
- *
- * The spec does not explicitly say how arrays are counted. However, it
- * should be safe to assume the total number of slots consumed by an array
- * is the number of entries in the array multiplied by the number of slots
- * consumed by a single element of the array.
- */
-
- if (t->is_array())
- return t->array_size() * count_attribute_slots(t->element_type());
-
- if (t->is_matrix())
- return t->matrix_columns;
-
- return 1;
-}
-
-
-/**
- * Verify that a vertex shader executable meets all semantic requirements
- *
- * \param shader Vertex shader executable to be verified
- */
-bool
-validate_vertex_shader_executable(struct gl_shader_program *prog,
- struct gl_shader *shader)
-{
- if (shader == NULL)
- return true;
-
- find_assignment_visitor find("gl_Position");
- find.run(shader->ir);
- if (!find.variable_found()) {
- linker_error_printf(prog,
- "vertex shader does not write to `gl_Position'\n");
- return false;
- }
-
- return true;
-}
-
-
-/**
- * Verify that a fragment shader executable meets all semantic requirements
- *
- * \param shader Fragment shader executable to be verified
- */
-bool
-validate_fragment_shader_executable(struct gl_shader_program *prog,
- struct gl_shader *shader)
-{
- if (shader == NULL)
- return true;
-
- find_assignment_visitor frag_color("gl_FragColor");
- find_assignment_visitor frag_data("gl_FragData");
-
- frag_color.run(shader->ir);
- frag_data.run(shader->ir);
-
- if (frag_color.variable_found() && frag_data.variable_found()) {
- linker_error_printf(prog, "fragment shader writes to both "
- "`gl_FragColor' and `gl_FragData'\n");
- return false;
- }
-
- return true;
-}
-
-
-/**
- * Generate a string describing the mode of a variable
- */
-static const char *
-mode_string(const ir_variable *var)
-{
- switch (var->mode) {
- case ir_var_auto:
- return (var->read_only) ? "global constant" : "global variable";
-
- case ir_var_uniform: return "uniform";
- case ir_var_in: return "shader input";
- case ir_var_out: return "shader output";
- case ir_var_inout: return "shader inout";
-
- case ir_var_const_in:
- case ir_var_temporary:
- default:
- assert(!"Should not get here.");
- return "invalid variable";
- }
-}
-
-
-/**
- * Perform validation of global variables used across multiple shaders
- */
-bool
-cross_validate_globals(struct gl_shader_program *prog,
- struct gl_shader **shader_list,
- unsigned num_shaders,
- bool uniforms_only)
-{
- /* Examine all of the uniforms in all of the shaders and cross validate
- * them.
- */
- glsl_symbol_table variables;
- for (unsigned i = 0; i < num_shaders; i++) {
- if (shader_list[i] == NULL)
- continue;
-
- foreach_list(node, shader_list[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if (var == NULL)
- continue;
-
- if (uniforms_only && (var->mode != ir_var_uniform))
- continue;
-
- /* Don't cross validate temporaries that are at global scope. These
- * will eventually get pulled into the shaders 'main'.
- */
- if (var->mode == ir_var_temporary)
- continue;
-
- /* If a global with this name has already been seen, verify that the
- * new instance has the same type. In addition, if the globals have
- * initializers, the values of the initializers must be the same.
- */
- ir_variable *const existing = variables.get_variable(var->name);
- if (existing != NULL) {
- if (var->type != existing->type) {
- /* Consider the types to be "the same" if both types are arrays
- * of the same type and one of the arrays is implicitly sized.
- * In addition, set the type of the linked variable to the
- * explicitly sized array.
- */
- if (var->type->is_array()
- && existing->type->is_array()
- && (var->type->fields.array == existing->type->fields.array)
- && ((var->type->length == 0)
- || (existing->type->length == 0))) {
- if (var->type->length != 0) {
- existing->type = var->type;
- }
- } else {
- linker_error_printf(prog, "%s `%s' declared as type "
- "`%s' and type `%s'\n",
- mode_string(var),
- var->name, var->type->name,
- existing->type->name);
- return false;
- }
- }
-
- if (var->explicit_location) {
- if (existing->explicit_location
- && (var->location != existing->location)) {
- linker_error_printf(prog, "explicit locations for %s "
- "`%s' have differing values\n",
- mode_string(var), var->name);
- return false;
- }
-
- existing->location = var->location;
- existing->explicit_location = true;
- }
-
- /* Validate layout qualifiers for gl_FragDepth.
- *
- * From the AMD_conservative_depth spec:
- * "If gl_FragDepth is redeclared in any fragment shader in
- * a program, it must be redeclared in all fragment shaders in that
- * program that have static assignments to gl_FragDepth. All
- * redeclarations of gl_FragDepth in all fragment shaders in
- * a single program must have the same set of qualifiers."
- */
- if (strcmp(var->name, "gl_FragDepth") == 0) {
- bool layout_declared = var->depth_layout != ir_depth_layout_none;
- bool layout_differs = var->depth_layout != existing->depth_layout;
- if (layout_declared && layout_differs) {
- linker_error_printf(prog,
- "All redeclarations of gl_FragDepth in all fragment shaders "
- "in a single program must have the same set of qualifiers.");
- }
- if (var->used && layout_differs) {
- linker_error_printf(prog,
- "If gl_FragDepth is redeclared with a layout qualifier in"
- "any fragment shader, it must be redeclared with the same"
- "layout qualifier in all fragment shaders that have"
- "assignments to gl_FragDepth");
- }
- }
-
- /* FINISHME: Handle non-constant initializers.
- */
- if (var->constant_value != NULL) {
- if (existing->constant_value != NULL) {
- if (!var->constant_value->has_value(existing->constant_value)) {
- linker_error_printf(prog, "initializers for %s "
- "`%s' have differing values\n",
- mode_string(var), var->name);
- return false;
- }
- } else
- /* If the first-seen instance of a particular uniform did not
- * have an initializer but a later instance does, copy the
- * initializer to the version stored in the symbol table.
- */
- /* FINISHME: This is wrong. The constant_value field should
- * FINISHME: not be modified! Imagine a case where a shader
- * FINISHME: without an initializer is linked in two different
- * FINISHME: programs with shaders that have differing
- * FINISHME: initializers. Linking with the first will
- * FINISHME: modify the shader, and linking with the second
- * FINISHME: will fail.
- */
- existing->constant_value =
- var->constant_value->clone(ralloc_parent(existing), NULL);
- }
-
- if (existing->invariant != var->invariant) {
- linker_error_printf(prog, "declarations for %s `%s' have "
- "mismatching invariant qualifiers\n",
- mode_string(var), var->name);
- return false;
- }
- if (existing->centroid != var->centroid) {
- linker_error_printf(prog, "declarations for %s `%s' have "
- "mismatching centroid qualifiers\n",
- mode_string(var), var->name);
- return false;
- }
- } else
- variables.add_variable(var);
- }
- }
-
- return true;
-}
-
-
-/**
- * Perform validation of uniforms used across multiple shader stages
- */
-bool
-cross_validate_uniforms(struct gl_shader_program *prog)
-{
- return cross_validate_globals(prog, prog->_LinkedShaders,
- MESA_SHADER_TYPES, true);
-}
-
-
-/**
- * Validate that outputs from one stage match inputs of another
- */
-bool
-cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
- gl_shader *producer, gl_shader *consumer)
-{
- glsl_symbol_table parameters;
- /* FINISHME: Figure these out dynamically. */
- const char *const producer_stage = "vertex";
- const char *const consumer_stage = "fragment";
-
- /* Find all shader outputs in the "producer" stage.
- */
- foreach_list(node, producer->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- /* FINISHME: For geometry shaders, this should also look for inout
- * FINISHME: variables.
- */
- if ((var == NULL) || (var->mode != ir_var_out))
- continue;
-
- parameters.add_variable(var);
- }
-
-
- /* Find all shader inputs in the "consumer" stage. Any variables that have
- * matching outputs already in the symbol table must have the same type and
- * qualifiers.
- */
- foreach_list(node, consumer->ir) {
- ir_variable *const input = ((ir_instruction *) node)->as_variable();
-
- /* FINISHME: For geometry shaders, this should also look for inout
- * FINISHME: variables.
- */
- if ((input == NULL) || (input->mode != ir_var_in))
- continue;
-
- ir_variable *const output = parameters.get_variable(input->name);
- if (output != NULL) {
- /* Check that the types match between stages.
- */
- if (input->type != output->type) {
- /* There is a bit of a special case for gl_TexCoord. This
- * built-in is unsized by default. Appliations that variable
- * access it must redeclare it with a size. There is some
- * language in the GLSL spec that implies the fragment shader
- * and vertex shader do not have to agree on this size. Other
- * driver behave this way, and one or two applications seem to
- * rely on it.
- *
- * Neither declaration needs to be modified here because the array
- * sizes are fixed later when update_array_sizes is called.
- *
- * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
- *
- * "Unlike user-defined varying variables, the built-in
- * varying variables don't have a strict one-to-one
- * correspondence between the vertex language and the
- * fragment language."
- */
- if (!output->type->is_array()
- || (strncmp("gl_", output->name, 3) != 0)) {
- linker_error_printf(prog,
- "%s shader output `%s' declared as "
- "type `%s', but %s shader input declared "
- "as type `%s'\n",
- producer_stage, output->name,
- output->type->name,
- consumer_stage, input->type->name);
- return false;
- }
- }
-
- /* Check that all of the qualifiers match between stages.
- */
- if (input->centroid != output->centroid) {
- linker_error_printf(prog,
- "%s shader output `%s' %s centroid qualifier, "
- "but %s shader input %s centroid qualifier\n",
- producer_stage,
- output->name,
- (output->centroid) ? "has" : "lacks",
- consumer_stage,
- (input->centroid) ? "has" : "lacks");
- return false;
- }
-
- if (input->invariant != output->invariant) {
- linker_error_printf(prog,
- "%s shader output `%s' %s invariant qualifier, "
- "but %s shader input %s invariant qualifier\n",
- producer_stage,
- output->name,
- (output->invariant) ? "has" : "lacks",
- consumer_stage,
- (input->invariant) ? "has" : "lacks");
- return false;
- }
-
- if (input->interpolation != output->interpolation) {
- linker_error_printf(prog,
- "%s shader output `%s' specifies %s "
- "interpolation qualifier, "
- "but %s shader input specifies %s "
- "interpolation qualifier\n",
- producer_stage,
- output->name,
- output->interpolation_string(),
- consumer_stage,
- input->interpolation_string());
- return false;
- }
- }
- }
-
- return true;
-}
-
-
-/**
- * Populates a shaders symbol table with all global declarations
- */
-static void
-populate_symbol_table(gl_shader *sh)
-{
- sh->symbols = new(sh) glsl_symbol_table;
-
- foreach_list(node, sh->ir) {
- ir_instruction *const inst = (ir_instruction *) node;
- ir_variable *var;
- ir_function *func;
-
- if ((func = inst->as_function()) != NULL) {
- sh->symbols->add_function(func);
- } else if ((var = inst->as_variable()) != NULL) {
- sh->symbols->add_variable(var);
- }
- }
-}
-
-
-/**
- * Remap variables referenced in an instruction tree
- *
- * This is used when instruction trees are cloned from one shader and placed in
- * another. These trees will contain references to \c ir_variable nodes that
- * do not exist in the target shader. This function finds these \c ir_variable
- * references and replaces the references with matching variables in the target
- * shader.
- *
- * If there is no matching variable in the target shader, a clone of the
- * \c ir_variable is made and added to the target shader. The new variable is
- * added to \b both the instruction stream and the symbol table.
- *
- * \param inst IR tree that is to be processed.
- * \param symbols Symbol table containing global scope symbols in the
- * linked shader.
- * \param instructions Instruction stream where new variable declarations
- * should be added.
- */
-void
-remap_variables(ir_instruction *inst, struct gl_shader *target,
- hash_table *temps)
-{
- class remap_visitor : public ir_hierarchical_visitor {
- public:
- remap_visitor(struct gl_shader *target,
- hash_table *temps)
- {
- this->target = target;
- this->symbols = target->symbols;
- this->instructions = target->ir;
- this->temps = temps;
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- if (ir->var->mode == ir_var_temporary) {
- ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
-
- assert(var != NULL);
- ir->var = var;
- return visit_continue;
- }
-
- ir_variable *const existing =
- this->symbols->get_variable(ir->var->name);
- if (existing != NULL)
- ir->var = existing;
- else {
- ir_variable *copy = ir->var->clone(this->target, NULL);
-
- this->symbols->add_variable(copy);
- this->instructions->push_head(copy);
- ir->var = copy;
- }
-
- return visit_continue;
- }
-
- private:
- struct gl_shader *target;
- glsl_symbol_table *symbols;
- exec_list *instructions;
- hash_table *temps;
- };
-
- remap_visitor v(target, temps);
-
- inst->accept(&v);
-}
-
-
-/**
- * Move non-declarations from one instruction stream to another
- *
- * The intended usage pattern of this function is to pass the pointer to the
- * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
- * pointer) for \c last and \c false for \c make_copies on the first
- * call. Successive calls pass the return value of the previous call for
- * \c last and \c true for \c make_copies.
- *
- * \param instructions Source instruction stream
- * \param last Instruction after which new instructions should be
- * inserted in the target instruction stream
- * \param make_copies Flag selecting whether instructions in \c instructions
- * should be copied (via \c ir_instruction::clone) into the
- * target list or moved.
- *
- * \return
- * The new "last" instruction in the target instruction stream. This pointer
- * is suitable for use as the \c last parameter of a later call to this
- * function.
- */
-exec_node *
-move_non_declarations(exec_list *instructions, exec_node *last,
- bool make_copies, gl_shader *target)
-{
- hash_table *temps = NULL;
-
- if (make_copies)
- temps = hash_table_ctor(0, hash_table_pointer_hash,
- hash_table_pointer_compare);
-
- foreach_list_safe(node, instructions) {
- ir_instruction *inst = (ir_instruction *) node;
-
- if (inst->as_function())
- continue;
-
- ir_variable *var = inst->as_variable();
- if ((var != NULL) && (var->mode != ir_var_temporary))
- continue;
-
- assert(inst->as_assignment()
- || ((var != NULL) && (var->mode == ir_var_temporary)));
-
- if (make_copies) {
- inst = inst->clone(target, NULL);
-
- if (var != NULL)
- hash_table_insert(temps, inst, var);
- else
- remap_variables(inst, target, temps);
- } else {
- inst->remove();
- }
-
- last->insert_after(inst);
- last = inst;
- }
-
- if (make_copies)
- hash_table_dtor(temps);
-
- return last;
-}
-
-/**
- * Get the function signature for main from a shader
- */
-static ir_function_signature *
-get_main_function_signature(gl_shader *sh)
-{
- ir_function *const f = sh->symbols->get_function("main");
- if (f != NULL) {
- exec_list void_parameters;
-
- /* Look for the 'void main()' signature and ensure that it's defined.
- * This keeps the linker from accidentally pick a shader that just
- * contains a prototype for main.
- *
- * We don't have to check for multiple definitions of main (in multiple
- * shaders) because that would have already been caught above.
- */
- ir_function_signature *sig = f->matching_signature(&void_parameters);
- if ((sig != NULL) && sig->is_defined) {
- return sig;
- }
- }
-
- return NULL;
-}
-
-
-/**
- * Combine a group of shaders for a single stage to generate a linked shader
- *
- * \note
- * If this function is supplied a single shader, it is cloned, and the new
- * shader is returned.
- */
-static struct gl_shader *
-link_intrastage_shaders(void *mem_ctx,
- struct gl_context *ctx,
- struct gl_shader_program *prog,
- struct gl_shader **shader_list,
- unsigned num_shaders)
-{
- /* Check that global variables defined in multiple shaders are consistent.
- */
- if (!cross_validate_globals(prog, shader_list, num_shaders, false))
- return NULL;
-
- /* Check that there is only a single definition of each function signature
- * across all shaders.
- */
- for (unsigned i = 0; i < (num_shaders - 1); i++) {
- foreach_list(node, shader_list[i]->ir) {
- ir_function *const f = ((ir_instruction *) node)->as_function();
-
- if (f == NULL)
- continue;
-
- for (unsigned j = i + 1; j < num_shaders; j++) {
- ir_function *const other =
- shader_list[j]->symbols->get_function(f->name);
-
- /* If the other shader has no function (and therefore no function
- * signatures) with the same name, skip to the next shader.
- */
- if (other == NULL)
- continue;
-
- foreach_iter (exec_list_iterator, iter, *f) {
- ir_function_signature *sig =
- (ir_function_signature *) iter.get();
-
- if (!sig->is_defined || sig->is_builtin)
- continue;
-
- ir_function_signature *other_sig =
- other->exact_matching_signature(& sig->parameters);
-
- if ((other_sig != NULL) && other_sig->is_defined
- && !other_sig->is_builtin) {
- linker_error_printf(prog,
- "function `%s' is multiply defined",
- f->name);
- return NULL;
- }
- }
- }
- }
- }
-
- /* Find the shader that defines main, and make a clone of it.
- *
- * Starting with the clone, search for undefined references. If one is
- * found, find the shader that defines it. Clone the reference and add
- * it to the shader. Repeat until there are no undefined references or
- * until a reference cannot be resolved.
- */
- gl_shader *main = NULL;
- for (unsigned i = 0; i < num_shaders; i++) {
- if (get_main_function_signature(shader_list[i]) != NULL) {
- main = shader_list[i];
- break;
- }
- }
-
- if (main == NULL) {
- linker_error_printf(prog, "%s shader lacks `main'\n",
- (shader_list[0]->Type == GL_VERTEX_SHADER)
- ? "vertex" : "fragment");
- return NULL;
- }
-
- gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
- linked->ir = new(linked) exec_list;
- clone_ir_list(mem_ctx, linked->ir, main->ir);
-
- populate_symbol_table(linked);
-
- /* The a pointer to the main function in the final linked shader (i.e., the
- * copy of the original shader that contained the main function).
- */
- ir_function_signature *const main_sig = get_main_function_signature(linked);
-
- /* Move any instructions other than variable declarations or function
- * declarations into main.
- */
- exec_node *insertion_point =
- move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
- linked);
-
- for (unsigned i = 0; i < num_shaders; i++) {
- if (shader_list[i] == main)
- continue;
-
- insertion_point = move_non_declarations(shader_list[i]->ir,
- insertion_point, true, linked);
- }
-
- /* Resolve initializers for global variables in the linked shader.
- */
- unsigned num_linking_shaders = num_shaders;
- for (unsigned i = 0; i < num_shaders; i++)
- num_linking_shaders += shader_list[i]->num_builtins_to_link;
-
- gl_shader **linking_shaders =
- (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
-
- memcpy(linking_shaders, shader_list,
- sizeof(linking_shaders[0]) * num_shaders);
-
- unsigned idx = num_shaders;
- for (unsigned i = 0; i < num_shaders; i++) {
- memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
- sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
- idx += shader_list[i]->num_builtins_to_link;
- }
-
- assert(idx == num_linking_shaders);
-
- if (!link_function_calls(prog, linked, linking_shaders,
- num_linking_shaders)) {
- ctx->Driver.DeleteShader(ctx, linked);
- linked = NULL;
- }
-
- free(linking_shaders);
-
- /* Make a pass over all variable declarations to ensure that arrays with
- * unspecified sizes have a size specified. The size is inferred from the
- * max_array_access field.
- */
- if (linked != NULL) {
- class array_sizing_visitor : public ir_hierarchical_visitor {
- public:
- virtual ir_visitor_status visit(ir_variable *var)
- {
- if (var->type->is_array() && (var->type->length == 0)) {
- const glsl_type *type =
- glsl_type::get_array_instance(var->type->fields.array,
- var->max_array_access + 1);
-
- assert(type != NULL);
- var->type = type;
- }
-
- return visit_continue;
- }
- } v;
-
- v.run(linked->ir);
- }
-
- return linked;
-}
-
-
-struct uniform_node {
- exec_node link;
- struct gl_uniform *u;
- unsigned slots;
-};
-
-/**
- * Update the sizes of linked shader uniform arrays to the maximum
- * array index used.
- *
- * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
- *
- * If one or more elements of an array are active,
- * GetActiveUniform will return the name of the array in name,
- * subject to the restrictions listed above. The type of the array
- * is returned in type. The size parameter contains the highest
- * array element index used, plus one. The compiler or linker
- * determines the highest index used. There will be only one
- * active uniform reported by the GL per uniform array.
-
- */
-static void
-update_array_sizes(struct gl_shader_program *prog)
-{
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- foreach_list(node, prog->_LinkedShaders[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_uniform &&
- var->mode != ir_var_in &&
- var->mode != ir_var_out) ||
- !var->type->is_array())
- continue;
-
- unsigned int size = var->max_array_access;
- for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
- if (prog->_LinkedShaders[j] == NULL)
- continue;
-
- foreach_list(node2, prog->_LinkedShaders[j]->ir) {
- ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
- if (!other_var)
- continue;
-
- if (strcmp(var->name, other_var->name) == 0 &&
- other_var->max_array_access > size) {
- size = other_var->max_array_access;
- }
- }
- }
-
- if (size + 1 != var->type->fields.array->length) {
- var->type = glsl_type::get_array_instance(var->type->fields.array,
- size + 1);
- /* FINISHME: We should update the types of array
- * dereferences of this variable now.
- */
- }
- }
- }
-}
-
-static void
-add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
- const char *name, const glsl_type *type, GLenum shader_type,
- unsigned *next_shader_pos, unsigned *total_uniforms)
-{
- if (type->is_record()) {
- for (unsigned int i = 0; i < type->length; i++) {
- const glsl_type *field_type = type->fields.structure[i].type;
- char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
- type->fields.structure[i].name);
-
- add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
- shader_type, next_shader_pos, total_uniforms);
- }
- } else {
- uniform_node *n = (uniform_node *) hash_table_find(ht, name);
- unsigned int vec4_slots;
- const glsl_type *array_elem_type = NULL;
-
- if (type->is_array()) {
- array_elem_type = type->fields.array;
- /* Array of structures. */
- if (array_elem_type->is_record()) {
- for (unsigned int i = 0; i < type->length; i++) {
- char *elem_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
- add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
- shader_type, next_shader_pos, total_uniforms);
- }
- return;
- }
- }
-
- /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
- * vectors to vec4 slots.
- */
- if (type->is_array()) {
- if (array_elem_type->is_sampler())
- vec4_slots = type->length;
- else
- vec4_slots = type->length * array_elem_type->matrix_columns;
- } else if (type->is_sampler()) {
- vec4_slots = 1;
- } else {
- vec4_slots = type->matrix_columns;
- }
-
- if (n == NULL) {
- n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
- n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
- n->slots = vec4_slots;
-
- n->u->Name = strdup(name);
- n->u->Type = type;
- n->u->VertPos = -1;
- n->u->FragPos = -1;
- n->u->GeomPos = -1;
- (*total_uniforms)++;
-
- hash_table_insert(ht, n, name);
- uniforms->push_tail(& n->link);
- }
-
- switch (shader_type) {
- case GL_VERTEX_SHADER:
- n->u->VertPos = *next_shader_pos;
- break;
- case GL_FRAGMENT_SHADER:
- n->u->FragPos = *next_shader_pos;
- break;
- case GL_GEOMETRY_SHADER:
- n->u->GeomPos = *next_shader_pos;
- break;
- }
-
- (*next_shader_pos) += vec4_slots;
- }
-}
-
-void
-assign_uniform_locations(struct gl_shader_program *prog)
-{
- /* */
- exec_list uniforms;
- unsigned total_uniforms = 0;
- hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
- hash_table_string_compare);
- void *mem_ctx = ralloc_context(NULL);
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- unsigned next_position = 0;
-
- foreach_list(node, prog->_LinkedShaders[i]->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_uniform))
- continue;
-
- if (strncmp(var->name, "gl_", 3) == 0) {
- /* At the moment, we don't allocate uniform locations for
- * builtin uniforms. It's permitted by spec, and we'll
- * likely switch to doing that at some point, but not yet.
- */
- continue;
- }
-
- var->location = next_position;
- add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
- prog->_LinkedShaders[i]->Type,
- &next_position, &total_uniforms);
- }
- }
-
- ralloc_free(mem_ctx);
-
- gl_uniform_list *ul = (gl_uniform_list *)
- calloc(1, sizeof(gl_uniform_list));
-
- ul->Size = total_uniforms;
- ul->NumUniforms = total_uniforms;
- ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
-
- unsigned idx = 0;
- uniform_node *next;
- for (uniform_node *node = (uniform_node *) uniforms.head
- ; node->link.next != NULL
- ; node = next) {
- next = (uniform_node *) node->link.next;
-
- node->link.remove();
- memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
- idx++;
-
- free(node->u);
- free(node);
- }
-
- hash_table_dtor(ht);
-
- prog->Uniforms = ul;
-}
-
-
-/**
- * Find a contiguous set of available bits in a bitmask
- *
- * \param used_mask Bits representing used (1) and unused (0) locations
- * \param needed_count Number of contiguous bits needed.
- *
- * \return
- * Base location of the available bits on success or -1 on failure.
- */
-int
-find_available_slots(unsigned used_mask, unsigned needed_count)
-{
- unsigned needed_mask = (1 << needed_count) - 1;
- const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
-
- /* The comparison to 32 is redundant, but without it GCC emits "warning:
- * cannot optimize possibly infinite loops" for the loop below.
- */
- if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
- return -1;
-
- for (int i = 0; i <= max_bit_to_test; i++) {
- if ((needed_mask & ~used_mask) == needed_mask)
- return i;
-
- needed_mask <<= 1;
- }
-
- return -1;
-}
-
-
-bool
-assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
-{
- /* Mark invalid attribute locations as being used.
- */
- unsigned used_locations = (max_attribute_index >= 32)
- ? ~0 : ~((1 << max_attribute_index) - 1);
-
- gl_shader *const sh = prog->_LinkedShaders[0];
- assert(sh->Type == GL_VERTEX_SHADER);
-
- /* Operate in a total of four passes.
- *
- * 1. Invalidate the location assignments for all vertex shader inputs.
- *
- * 2. Assign locations for inputs that have user-defined (via
- * glBindVertexAttribLocation) locatoins.
- *
- * 3. Sort the attributes without assigned locations by number of slots
- * required in decreasing order. Fragmentation caused by attribute
- * locations assigned by the application may prevent large attributes
- * from having enough contiguous space.
- *
- * 4. Assign locations to any inputs without assigned locations.
- */
-
- invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
-
- if (prog->Attributes != NULL) {
- for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
- ir_variable *const var =
- sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
-
- /* Note: attributes that occupy multiple slots, such as arrays or
- * matrices, may appear in the attrib array multiple times.
- */
- if ((var == NULL) || (var->location != -1))
- continue;
-
- /* From page 61 of the OpenGL 4.0 spec:
- *
- * "LinkProgram will fail if the attribute bindings assigned by
- * BindAttribLocation do not leave not enough space to assign a
- * location for an active matrix attribute or an active attribute
- * array, both of which require multiple contiguous generic
- * attributes."
- *
- * Previous versions of the spec contain similar language but omit the
- * bit about attribute arrays.
- *
- * Page 61 of the OpenGL 4.0 spec also says:
- *
- * "It is possible for an application to bind more than one
- * attribute name to the same location. This is referred to as
- * aliasing. This will only work if only one of the aliased
- * attributes is active in the executable program, or if no path
- * through the shader consumes more than one attribute of a set
- * of attributes aliased to the same location. A link error can
- * occur if the linker determines that every path through the
- * shader consumes multiple aliased attributes, but
- * implementations are not required to generate an error in this
- * case."
- *
- * These two paragraphs are either somewhat contradictory, or I don't
- * fully understand one or both of them.
- */
- /* FINISHME: The code as currently written does not support attribute
- * FINISHME: location aliasing (see comment above).
- */
- const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
- const unsigned slots = count_attribute_slots(var->type);
-
- /* Mask representing the contiguous slots that will be used by this
- * attribute.
- */
- const unsigned use_mask = (1 << slots) - 1;
-
- /* Generate a link error if the set of bits requested for this
- * attribute overlaps any previously allocated bits.
- */
- if ((~(use_mask << attr) & used_locations) != used_locations) {
- linker_error_printf(prog,
- "insufficient contiguous attribute locations "
- "available for vertex shader input `%s'",
- var->name);
- return false;
- }
-
- var->location = VERT_ATTRIB_GENERIC0 + attr;
- used_locations |= (use_mask << attr);
- }
- }
-
- /* Temporary storage for the set of attributes that need locations assigned.
- */
- struct temp_attr {
- unsigned slots;
- ir_variable *var;
-
- /* Used below in the call to qsort. */
- static int compare(const void *a, const void *b)
- {
- const temp_attr *const l = (const temp_attr *) a;
- const temp_attr *const r = (const temp_attr *) b;
-
- /* Reversed because we want a descending order sort below. */
- return r->slots - l->slots;
- }
- } to_assign[16];
-
- unsigned num_attr = 0;
-
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_in))
- continue;
-
- if (var->explicit_location) {
- const unsigned slots = count_attribute_slots(var->type);
- const unsigned use_mask = (1 << slots) - 1;
- const int attr = var->location - VERT_ATTRIB_GENERIC0;
-
- if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
- || (var->location < 0)) {
- linker_error_printf(prog,
- "invalid explicit location %d specified for "
- "`%s'\n",
- (var->location < 0) ? var->location : attr,
- var->name);
- return false;
- } else if (var->location >= VERT_ATTRIB_GENERIC0) {
- used_locations |= (use_mask << attr);
- }
- }
-
- /* The location was explicitly assigned, nothing to do here.
- */
- if (var->location != -1)
- continue;
-
- to_assign[num_attr].slots = count_attribute_slots(var->type);
- to_assign[num_attr].var = var;
- num_attr++;
- }
-
- /* If all of the attributes were assigned locations by the application (or
- * are built-in attributes with fixed locations), return early. This should
- * be the common case.
- */
- if (num_attr == 0)
- return true;
-
- qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
-
- /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
- * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
- * to prevent it from being automatically allocated below.
- */
- find_deref_visitor find("gl_Vertex");
- find.run(sh->ir);
- if (find.variable_found())
- used_locations |= (1 << 0);
-
- for (unsigned i = 0; i < num_attr; i++) {
- /* Mask representing the contiguous slots that will be used by this
- * attribute.
- */
- const unsigned use_mask = (1 << to_assign[i].slots) - 1;
-
- int location = find_available_slots(used_locations, to_assign[i].slots);
-
- if (location < 0) {
- linker_error_printf(prog,
- "insufficient contiguous attribute locations "
- "available for vertex shader input `%s'",
- to_assign[i].var->name);
- return false;
- }
-
- to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
- used_locations |= (use_mask << location);
- }
-
- return true;
-}
-
-
-/**
- * Demote shader inputs and outputs that are not used in other stages
- */
-void
-demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
-{
- foreach_list(node, sh->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != int(mode)))
- continue;
-
- /* A shader 'in' or 'out' variable is only really an input or output if
- * its value is used by other shader stages. This will cause the variable
- * to have a location assigned.
- */
- if (var->location == -1) {
- var->mode = ir_var_auto;
- }
- }
-}
-
-
-void
-assign_varying_locations(struct gl_shader_program *prog,
- gl_shader *producer, gl_shader *consumer)
-{
- /* FINISHME: Set dynamically when geometry shader support is added. */
- unsigned output_index = VERT_RESULT_VAR0;
- unsigned input_index = FRAG_ATTRIB_VAR0;
-
- /* Operate in a total of three passes.
- *
- * 1. Assign locations for any matching inputs and outputs.
- *
- * 2. Mark output variables in the producer that do not have locations as
- * not being outputs. This lets the optimizer eliminate them.
- *
- * 3. Mark input variables in the consumer that do not have locations as
- * not being inputs. This lets the optimizer eliminate them.
- */
-
- invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
- invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
-
- foreach_list(node, producer->ir) {
- ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
-
- if ((output_var == NULL) || (output_var->mode != ir_var_out)
- || (output_var->location != -1))
- continue;
-
- ir_variable *const input_var =
- consumer->symbols->get_variable(output_var->name);
-
- if ((input_var == NULL) || (input_var->mode != ir_var_in))
- continue;
-
- assert(input_var->location == -1);
-
- output_var->location = output_index;
- input_var->location = input_index;
-
- /* FINISHME: Support for "varying" records in GLSL 1.50. */
- assert(!output_var->type->is_record());
-
- if (output_var->type->is_array()) {
- const unsigned slots = output_var->type->length
- * output_var->type->fields.array->matrix_columns;
-
- output_index += slots;
- input_index += slots;
- } else {
- const unsigned slots = output_var->type->matrix_columns;
-
- output_index += slots;
- input_index += slots;
- }
- }
-
- foreach_list(node, consumer->ir) {
- ir_variable *const var = ((ir_instruction *) node)->as_variable();
-
- if ((var == NULL) || (var->mode != ir_var_in))
- continue;
-
- if (var->location == -1) {
- if (prog->Version <= 120) {
- /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
- *
- * Only those varying variables used (i.e. read) in
- * the fragment shader executable must be written to
- * by the vertex shader executable; declaring
- * superfluous varying variables in a vertex shader is
- * permissible.
- *
- * We interpret this text as meaning that the VS must
- * write the variable for the FS to read it. See
- * "glsl1-varying read but not written" in piglit.
- */
-
- linker_error_printf(prog, "fragment shader varying %s not written "
- "by vertex shader\n.", var->name);
- prog->LinkStatus = false;
- }
-
- /* An 'in' variable is only really a shader input if its
- * value is written by the previous stage.
- */
- var->mode = ir_var_auto;
- }
- }
-}
-
-
-void
-link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
-{
- void *mem_ctx = ralloc_context(NULL); // temporary linker context
-
- prog->LinkStatus = false;
- prog->Validated = false;
- prog->_Used = false;
-
- if (prog->InfoLog != NULL)
- ralloc_free(prog->InfoLog);
-
- prog->InfoLog = ralloc_strdup(NULL, "");
-
- /* Separate the shaders into groups based on their type.
- */
- struct gl_shader **vert_shader_list;
- unsigned num_vert_shaders = 0;
- struct gl_shader **frag_shader_list;
- unsigned num_frag_shaders = 0;
-
- vert_shader_list = (struct gl_shader **)
- calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
- frag_shader_list = &vert_shader_list[prog->NumShaders];
-
- unsigned min_version = UINT_MAX;
- unsigned max_version = 0;
- for (unsigned i = 0; i < prog->NumShaders; i++) {
- min_version = MIN2(min_version, prog->Shaders[i]->Version);
- max_version = MAX2(max_version, prog->Shaders[i]->Version);
-
- switch (prog->Shaders[i]->Type) {
- case GL_VERTEX_SHADER:
- vert_shader_list[num_vert_shaders] = prog->Shaders[i];
- num_vert_shaders++;
- break;
- case GL_FRAGMENT_SHADER:
- frag_shader_list[num_frag_shaders] = prog->Shaders[i];
- num_frag_shaders++;
- break;
- case GL_GEOMETRY_SHADER:
- /* FINISHME: Support geometry shaders. */
- assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
- break;
- }
- }
-
- /* Previous to GLSL version 1.30, different compilation units could mix and
- * match shading language versions. With GLSL 1.30 and later, the versions
- * of all shaders must match.
- */
- assert(min_version >= 100);
- assert(max_version <= 130);
- if ((max_version >= 130 || min_version == 100)
- && min_version != max_version) {
- linker_error_printf(prog, "all shaders must use same shading "
- "language version\n");
- goto done;
- }
-
- prog->Version = max_version;
-
- for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] != NULL)
- ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
-
- prog->_LinkedShaders[i] = NULL;
- }
-
- /* Link all shaders for a particular stage and validate the result.
- */
- if (num_vert_shaders > 0) {
- gl_shader *const sh =
- link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
- num_vert_shaders);
-
- if (sh == NULL)
- goto done;
-
- if (!validate_vertex_shader_executable(prog, sh))
- goto done;
-
- _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
- sh);
- }
-
- if (num_frag_shaders > 0) {
- gl_shader *const sh =
- link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
- num_frag_shaders);
-
- if (sh == NULL)
- goto done;
-
- if (!validate_fragment_shader_executable(prog, sh))
- goto done;
-
- _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
- sh);
- }
-
- /* Here begins the inter-stage linking phase. Some initial validation is
- * performed, then locations are assigned for uniforms, attributes, and
- * varyings.
- */
- if (cross_validate_uniforms(prog)) {
- unsigned prev;
-
- for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
- if (prog->_LinkedShaders[prev] != NULL)
- break;
- }
-
- /* Validate the inputs of each stage with the output of the preceeding
- * stage.
- */
- for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- if (!cross_validate_outputs_to_inputs(prog,
- prog->_LinkedShaders[prev],
- prog->_LinkedShaders[i]))
- goto done;
-
- prev = i;
- }
-
- prog->LinkStatus = true;
- }
-
- /* Do common optimization before assigning storage for attributes,
- * uniforms, and varyings. Later optimization could possibly make
- * some of that unused.
- */
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
- ;
- }
-
- update_array_sizes(prog);
-
- assign_uniform_locations(prog);
-
- if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
- /* FINISHME: The value of the max_attribute_index parameter is
- * FINISHME: implementation dependent based on the value of
- * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
- * FINISHME: at least 16, so hardcode 16 for now.
- */
- if (!assign_attribute_locations(prog, 16)) {
- prog->LinkStatus = false;
- goto done;
- }
- }
-
- unsigned prev;
- for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
- if (prog->_LinkedShaders[prev] != NULL)
- break;
- }
-
- for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- assign_varying_locations(prog,
- prog->_LinkedShaders[prev],
- prog->_LinkedShaders[i]);
- prev = i;
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
- demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
- ir_var_out);
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
- gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
-
- demote_shader_inputs_and_outputs(sh, ir_var_in);
- demote_shader_inputs_and_outputs(sh, ir_var_inout);
- demote_shader_inputs_and_outputs(sh, ir_var_out);
- }
-
- if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
- gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
-
- demote_shader_inputs_and_outputs(sh, ir_var_in);
- }
-
- /* OpenGL ES requires that a vertex shader and a fragment shader both be
- * present in a linked program. By checking for use of shading language
- * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
- */
- if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
- if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
- linker_error_printf(prog, "program lacks a vertex shader\n");
- prog->LinkStatus = false;
- } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
- linker_error_printf(prog, "program lacks a fragment shader\n");
- prog->LinkStatus = false;
- }
- }
-
- /* FINISHME: Assign fragment shader output locations. */
-
-done:
- free(vert_shader_list);
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
- if (prog->_LinkedShaders[i] == NULL)
- continue;
-
- /* Retain any live IR, but trash the rest. */
- reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
- }
-
- ralloc_free(mem_ctx);
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 linker.cpp
+ * GLSL linker implementation
+ *
+ * Given a set of shaders that are to be linked to generate a final program,
+ * there are three distinct stages.
+ *
+ * In the first stage shaders are partitioned into groups based on the shader
+ * type. All shaders of a particular type (e.g., vertex shaders) are linked
+ * together.
+ *
+ * - Undefined references in each shader are resolve to definitions in
+ * another shader.
+ * - Types and qualifiers of uniforms, outputs, and global variables defined
+ * in multiple shaders with the same name are verified to be the same.
+ * - Initializers for uniforms and global variables defined
+ * in multiple shaders with the same name are verified to be the same.
+ *
+ * The result, in the terminology of the GLSL spec, is a set of shader
+ * executables for each processing unit.
+ *
+ * After the first stage is complete, a series of semantic checks are performed
+ * on each of the shader executables.
+ *
+ * - Each shader executable must define a \c main function.
+ * - Each vertex shader executable must write to \c gl_Position.
+ * - Each fragment shader executable must write to either \c gl_FragData or
+ * \c gl_FragColor.
+ *
+ * In the final stage individual shader executables are linked to create a
+ * complete exectuable.
+ *
+ * - Types of uniforms defined in multiple shader stages with the same name
+ * are verified to be the same.
+ * - Initializers for uniforms defined in multiple shader stages with the
+ * same name are verified to be the same.
+ * - Types and qualifiers of outputs defined in one stage are verified to
+ * be the same as the types and qualifiers of inputs defined with the same
+ * name in a later stage.
+ *
+ * \author Ian Romanick <ian.d.romanick@intel.com>
+ */
+
+#include "main/core.h"
+#include "glsl_symbol_table.h"
+#include "ir.h"
+#include "program.h"
+#include "program/hash_table.h"
+#include "linker.h"
+#include "ir_optimization.h"
+
+extern "C" {
+#include "main/shaderobj.h"
+}
+
+/**
+ * Visitor that determines whether or not a variable is ever written.
+ */
+class find_assignment_visitor : public ir_hierarchical_visitor {
+public:
+ find_assignment_visitor(const char *name)
+ : name(name), found(false)
+ {
+ /* empty */
+ }
+
+ virtual ir_visitor_status visit_enter(ir_assignment *ir)
+ {
+ ir_variable *const var = ir->lhs->variable_referenced();
+
+ if (strcmp(name, var->name) == 0) {
+ found = true;
+ return visit_stop;
+ }
+
+ return visit_continue_with_parent;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_call *ir)
+ {
+ exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_rvalue *param_rval = (ir_rvalue *)iter.get();
+ ir_variable *sig_param = (ir_variable *)sig_iter.get();
+
+ if (sig_param->mode == ir_var_out ||
+ sig_param->mode == ir_var_inout) {
+ ir_variable *var = param_rval->variable_referenced();
+ if (var && strcmp(name, var->name) == 0) {
+ found = true;
+ return visit_stop;
+ }
+ }
+ sig_iter.next();
+ }
+
+ return visit_continue_with_parent;
+ }
+
+ bool variable_found()
+ {
+ return found;
+ }
+
+private:
+ const char *name; /**< Find writes to a variable with this name. */
+ bool found; /**< Was a write to the variable found? */
+};
+
+
+/**
+ * Visitor that determines whether or not a variable is ever read.
+ */
+class find_deref_visitor : public ir_hierarchical_visitor {
+public:
+ find_deref_visitor(const char *name)
+ : name(name), found(false)
+ {
+ /* empty */
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (strcmp(this->name, ir->var->name) == 0) {
+ this->found = true;
+ return visit_stop;
+ }
+
+ return visit_continue;
+ }
+
+ bool variable_found() const
+ {
+ return this->found;
+ }
+
+private:
+ const char *name; /**< Find writes to a variable with this name. */
+ bool found; /**< Was a write to the variable found? */
+};
+
+
+void
+linker_error_printf(gl_shader_program *prog, const char *fmt, ...)
+{
+ va_list ap;
+
+ ralloc_strcat(&prog->InfoLog, "error: ");
+ va_start(ap, fmt);
+ ralloc_vasprintf_append(&prog->InfoLog, fmt, ap);
+ va_end(ap);
+}
+
+
+void
+invalidate_variable_locations(gl_shader *sh, enum ir_variable_mode mode,
+ int generic_base)
+{
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != (unsigned) mode))
+ continue;
+
+ /* Only assign locations for generic attributes / varyings / etc.
+ */
+ if ((var->location >= generic_base) && !var->explicit_location)
+ var->location = -1;
+ }
+}
+
+
+/**
+ * Determine the number of attribute slots required for a particular type
+ *
+ * This code is here because it implements the language rules of a specific
+ * GLSL version. Since it's a property of the language and not a property of
+ * types in general, it doesn't really belong in glsl_type.
+ */
+unsigned
+count_attribute_slots(const glsl_type *t)
+{
+ /* From page 31 (page 37 of the PDF) of the GLSL 1.50 spec:
+ *
+ * "A scalar input counts the same amount against this limit as a vec4,
+ * so applications may want to consider packing groups of four
+ * unrelated float inputs together into a vector to better utilize the
+ * capabilities of the underlying hardware. A matrix input will use up
+ * multiple locations. The number of locations used will equal the
+ * number of columns in the matrix."
+ *
+ * The spec does not explicitly say how arrays are counted. However, it
+ * should be safe to assume the total number of slots consumed by an array
+ * is the number of entries in the array multiplied by the number of slots
+ * consumed by a single element of the array.
+ */
+
+ if (t->is_array())
+ return t->array_size() * count_attribute_slots(t->element_type());
+
+ if (t->is_matrix())
+ return t->matrix_columns;
+
+ return 1;
+}
+
+
+/**
+ * Verify that a vertex shader executable meets all semantic requirements
+ *
+ * \param shader Vertex shader executable to be verified
+ */
+bool
+validate_vertex_shader_executable(struct gl_shader_program *prog,
+ struct gl_shader *shader)
+{
+ if (shader == NULL)
+ return true;
+
+ find_assignment_visitor find("gl_Position");
+ find.run(shader->ir);
+ if (!find.variable_found()) {
+ linker_error_printf(prog,
+ "vertex shader does not write to `gl_Position'\n");
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Verify that a fragment shader executable meets all semantic requirements
+ *
+ * \param shader Fragment shader executable to be verified
+ */
+bool
+validate_fragment_shader_executable(struct gl_shader_program *prog,
+ struct gl_shader *shader)
+{
+ if (shader == NULL)
+ return true;
+
+ find_assignment_visitor frag_color("gl_FragColor");
+ find_assignment_visitor frag_data("gl_FragData");
+
+ frag_color.run(shader->ir);
+ frag_data.run(shader->ir);
+
+ if (frag_color.variable_found() && frag_data.variable_found()) {
+ linker_error_printf(prog, "fragment shader writes to both "
+ "`gl_FragColor' and `gl_FragData'\n");
+ return false;
+ }
+
+ return true;
+}
+
+
+/**
+ * Generate a string describing the mode of a variable
+ */
+static const char *
+mode_string(const ir_variable *var)
+{
+ switch (var->mode) {
+ case ir_var_auto:
+ return (var->read_only) ? "global constant" : "global variable";
+
+ case ir_var_uniform: return "uniform";
+ case ir_var_in: return "shader input";
+ case ir_var_out: return "shader output";
+ case ir_var_inout: return "shader inout";
+
+ case ir_var_const_in:
+ case ir_var_temporary:
+ default:
+ assert(!"Should not get here.");
+ return "invalid variable";
+ }
+}
+
+
+/**
+ * Perform validation of global variables used across multiple shaders
+ */
+bool
+cross_validate_globals(struct gl_shader_program *prog,
+ struct gl_shader **shader_list,
+ unsigned num_shaders,
+ bool uniforms_only)
+{
+ /* Examine all of the uniforms in all of the shaders and cross validate
+ * them.
+ */
+ glsl_symbol_table variables;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (shader_list[i] == NULL)
+ continue;
+
+ foreach_list(node, shader_list[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if (var == NULL)
+ continue;
+
+ if (uniforms_only && (var->mode != ir_var_uniform))
+ continue;
+
+ /* Don't cross validate temporaries that are at global scope. These
+ * will eventually get pulled into the shaders 'main'.
+ */
+ if (var->mode == ir_var_temporary)
+ continue;
+
+ /* If a global with this name has already been seen, verify that the
+ * new instance has the same type. In addition, if the globals have
+ * initializers, the values of the initializers must be the same.
+ */
+ ir_variable *const existing = variables.get_variable(var->name);
+ if (existing != NULL) {
+ if (var->type != existing->type) {
+ /* Consider the types to be "the same" if both types are arrays
+ * of the same type and one of the arrays is implicitly sized.
+ * In addition, set the type of the linked variable to the
+ * explicitly sized array.
+ */
+ if (var->type->is_array()
+ && existing->type->is_array()
+ && (var->type->fields.array == existing->type->fields.array)
+ && ((var->type->length == 0)
+ || (existing->type->length == 0))) {
+ if (var->type->length != 0) {
+ existing->type = var->type;
+ }
+ } else {
+ linker_error_printf(prog, "%s `%s' declared as type "
+ "`%s' and type `%s'\n",
+ mode_string(var),
+ var->name, var->type->name,
+ existing->type->name);
+ return false;
+ }
+ }
+
+ if (var->explicit_location) {
+ if (existing->explicit_location
+ && (var->location != existing->location)) {
+ linker_error_printf(prog, "explicit locations for %s "
+ "`%s' have differing values\n",
+ mode_string(var), var->name);
+ return false;
+ }
+
+ existing->location = var->location;
+ existing->explicit_location = true;
+ }
+
+ /* Validate layout qualifiers for gl_FragDepth.
+ *
+ * From the AMD_conservative_depth spec:
+ * "If gl_FragDepth is redeclared in any fragment shader in
+ * a program, it must be redeclared in all fragment shaders in that
+ * program that have static assignments to gl_FragDepth. All
+ * redeclarations of gl_FragDepth in all fragment shaders in
+ * a single program must have the same set of qualifiers."
+ */
+ if (strcmp(var->name, "gl_FragDepth") == 0) {
+ bool layout_declared = var->depth_layout != ir_depth_layout_none;
+ bool layout_differs = var->depth_layout != existing->depth_layout;
+ if (layout_declared && layout_differs) {
+ linker_error_printf(prog,
+ "All redeclarations of gl_FragDepth in all fragment shaders "
+ "in a single program must have the same set of qualifiers.");
+ }
+ if (var->used && layout_differs) {
+ linker_error_printf(prog,
+ "If gl_FragDepth is redeclared with a layout qualifier in"
+ "any fragment shader, it must be redeclared with the same"
+ "layout qualifier in all fragment shaders that have"
+ "assignments to gl_FragDepth");
+ }
+ }
+
+ /* FINISHME: Handle non-constant initializers.
+ */
+ if (var->constant_value != NULL) {
+ if (existing->constant_value != NULL) {
+ if (!var->constant_value->has_value(existing->constant_value)) {
+ linker_error_printf(prog, "initializers for %s "
+ "`%s' have differing values\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ } else
+ /* If the first-seen instance of a particular uniform did not
+ * have an initializer but a later instance does, copy the
+ * initializer to the version stored in the symbol table.
+ */
+ /* FINISHME: This is wrong. The constant_value field should
+ * FINISHME: not be modified! Imagine a case where a shader
+ * FINISHME: without an initializer is linked in two different
+ * FINISHME: programs with shaders that have differing
+ * FINISHME: initializers. Linking with the first will
+ * FINISHME: modify the shader, and linking with the second
+ * FINISHME: will fail.
+ */
+ existing->constant_value =
+ var->constant_value->clone(ralloc_parent(existing), NULL);
+ }
+
+ if (existing->invariant != var->invariant) {
+ linker_error_printf(prog, "declarations for %s `%s' have "
+ "mismatching invariant qualifiers\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ if (existing->centroid != var->centroid) {
+ linker_error_printf(prog, "declarations for %s `%s' have "
+ "mismatching centroid qualifiers\n",
+ mode_string(var), var->name);
+ return false;
+ }
+ } else
+ variables.add_variable(var);
+ }
+ }
+
+ return true;
+}
+
+
+/**
+ * Perform validation of uniforms used across multiple shader stages
+ */
+bool
+cross_validate_uniforms(struct gl_shader_program *prog)
+{
+ return cross_validate_globals(prog, prog->_LinkedShaders,
+ MESA_SHADER_TYPES, true);
+}
+
+
+/**
+ * Validate that outputs from one stage match inputs of another
+ */
+bool
+cross_validate_outputs_to_inputs(struct gl_shader_program *prog,
+ gl_shader *producer, gl_shader *consumer)
+{
+ glsl_symbol_table parameters;
+ /* FINISHME: Figure these out dynamically. */
+ const char *const producer_stage = "vertex";
+ const char *const consumer_stage = "fragment";
+
+ /* Find all shader outputs in the "producer" stage.
+ */
+ foreach_list(node, producer->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ /* FINISHME: For geometry shaders, this should also look for inout
+ * FINISHME: variables.
+ */
+ if ((var == NULL) || (var->mode != ir_var_out))
+ continue;
+
+ parameters.add_variable(var);
+ }
+
+
+ /* Find all shader inputs in the "consumer" stage. Any variables that have
+ * matching outputs already in the symbol table must have the same type and
+ * qualifiers.
+ */
+ foreach_list(node, consumer->ir) {
+ ir_variable *const input = ((ir_instruction *) node)->as_variable();
+
+ /* FINISHME: For geometry shaders, this should also look for inout
+ * FINISHME: variables.
+ */
+ if ((input == NULL) || (input->mode != ir_var_in))
+ continue;
+
+ ir_variable *const output = parameters.get_variable(input->name);
+ if (output != NULL) {
+ /* Check that the types match between stages.
+ */
+ if (input->type != output->type) {
+ /* There is a bit of a special case for gl_TexCoord. This
+ * built-in is unsized by default. Appliations that variable
+ * access it must redeclare it with a size. There is some
+ * language in the GLSL spec that implies the fragment shader
+ * and vertex shader do not have to agree on this size. Other
+ * driver behave this way, and one or two applications seem to
+ * rely on it.
+ *
+ * Neither declaration needs to be modified here because the array
+ * sizes are fixed later when update_array_sizes is called.
+ *
+ * From page 48 (page 54 of the PDF) of the GLSL 1.10 spec:
+ *
+ * "Unlike user-defined varying variables, the built-in
+ * varying variables don't have a strict one-to-one
+ * correspondence between the vertex language and the
+ * fragment language."
+ */
+ if (!output->type->is_array()
+ || (strncmp("gl_", output->name, 3) != 0)) {
+ linker_error_printf(prog,
+ "%s shader output `%s' declared as "
+ "type `%s', but %s shader input declared "
+ "as type `%s'\n",
+ producer_stage, output->name,
+ output->type->name,
+ consumer_stage, input->type->name);
+ return false;
+ }
+ }
+
+ /* Check that all of the qualifiers match between stages.
+ */
+ if (input->centroid != output->centroid) {
+ linker_error_printf(prog,
+ "%s shader output `%s' %s centroid qualifier, "
+ "but %s shader input %s centroid qualifier\n",
+ producer_stage,
+ output->name,
+ (output->centroid) ? "has" : "lacks",
+ consumer_stage,
+ (input->centroid) ? "has" : "lacks");
+ return false;
+ }
+
+ if (input->invariant != output->invariant) {
+ linker_error_printf(prog,
+ "%s shader output `%s' %s invariant qualifier, "
+ "but %s shader input %s invariant qualifier\n",
+ producer_stage,
+ output->name,
+ (output->invariant) ? "has" : "lacks",
+ consumer_stage,
+ (input->invariant) ? "has" : "lacks");
+ return false;
+ }
+
+ if (input->interpolation != output->interpolation) {
+ linker_error_printf(prog,
+ "%s shader output `%s' specifies %s "
+ "interpolation qualifier, "
+ "but %s shader input specifies %s "
+ "interpolation qualifier\n",
+ producer_stage,
+ output->name,
+ output->interpolation_string(),
+ consumer_stage,
+ input->interpolation_string());
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+
+/**
+ * Populates a shaders symbol table with all global declarations
+ */
+static void
+populate_symbol_table(gl_shader *sh)
+{
+ sh->symbols = new(sh) glsl_symbol_table;
+
+ foreach_list(node, sh->ir) {
+ ir_instruction *const inst = (ir_instruction *) node;
+ ir_variable *var;
+ ir_function *func;
+
+ if ((func = inst->as_function()) != NULL) {
+ sh->symbols->add_function(func);
+ } else if ((var = inst->as_variable()) != NULL) {
+ sh->symbols->add_variable(var);
+ }
+ }
+}
+
+
+/**
+ * Remap variables referenced in an instruction tree
+ *
+ * This is used when instruction trees are cloned from one shader and placed in
+ * another. These trees will contain references to \c ir_variable nodes that
+ * do not exist in the target shader. This function finds these \c ir_variable
+ * references and replaces the references with matching variables in the target
+ * shader.
+ *
+ * If there is no matching variable in the target shader, a clone of the
+ * \c ir_variable is made and added to the target shader. The new variable is
+ * added to \b both the instruction stream and the symbol table.
+ *
+ * \param inst IR tree that is to be processed.
+ * \param symbols Symbol table containing global scope symbols in the
+ * linked shader.
+ * \param instructions Instruction stream where new variable declarations
+ * should be added.
+ */
+void
+remap_variables(ir_instruction *inst, struct gl_shader *target,
+ hash_table *temps)
+{
+ class remap_visitor : public ir_hierarchical_visitor {
+ public:
+ remap_visitor(struct gl_shader *target,
+ hash_table *temps)
+ {
+ this->target = target;
+ this->symbols = target->symbols;
+ this->instructions = target->ir;
+ this->temps = temps;
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ if (ir->var->mode == ir_var_temporary) {
+ ir_variable *var = (ir_variable *) hash_table_find(temps, ir->var);
+
+ assert(var != NULL);
+ ir->var = var;
+ return visit_continue;
+ }
+
+ ir_variable *const existing =
+ this->symbols->get_variable(ir->var->name);
+ if (existing != NULL)
+ ir->var = existing;
+ else {
+ ir_variable *copy = ir->var->clone(this->target, NULL);
+
+ this->symbols->add_variable(copy);
+ this->instructions->push_head(copy);
+ ir->var = copy;
+ }
+
+ return visit_continue;
+ }
+
+ private:
+ struct gl_shader *target;
+ glsl_symbol_table *symbols;
+ exec_list *instructions;
+ hash_table *temps;
+ };
+
+ remap_visitor v(target, temps);
+
+ inst->accept(&v);
+}
+
+
+/**
+ * Move non-declarations from one instruction stream to another
+ *
+ * The intended usage pattern of this function is to pass the pointer to the
+ * head sentinel of a list (i.e., a pointer to the list cast to an \c exec_node
+ * pointer) for \c last and \c false for \c make_copies on the first
+ * call. Successive calls pass the return value of the previous call for
+ * \c last and \c true for \c make_copies.
+ *
+ * \param instructions Source instruction stream
+ * \param last Instruction after which new instructions should be
+ * inserted in the target instruction stream
+ * \param make_copies Flag selecting whether instructions in \c instructions
+ * should be copied (via \c ir_instruction::clone) into the
+ * target list or moved.
+ *
+ * \return
+ * The new "last" instruction in the target instruction stream. This pointer
+ * is suitable for use as the \c last parameter of a later call to this
+ * function.
+ */
+exec_node *
+move_non_declarations(exec_list *instructions, exec_node *last,
+ bool make_copies, gl_shader *target)
+{
+ hash_table *temps = NULL;
+
+ if (make_copies)
+ temps = hash_table_ctor(0, hash_table_pointer_hash,
+ hash_table_pointer_compare);
+
+ foreach_list_safe(node, instructions) {
+ ir_instruction *inst = (ir_instruction *) node;
+
+ if (inst->as_function())
+ continue;
+
+ ir_variable *var = inst->as_variable();
+ if ((var != NULL) && (var->mode != ir_var_temporary))
+ continue;
+
+ assert(inst->as_assignment()
+ || ((var != NULL) && (var->mode == ir_var_temporary)));
+
+ if (make_copies) {
+ inst = inst->clone(target, NULL);
+
+ if (var != NULL)
+ hash_table_insert(temps, inst, var);
+ else
+ remap_variables(inst, target, temps);
+ } else {
+ inst->remove();
+ }
+
+ last->insert_after(inst);
+ last = inst;
+ }
+
+ if (make_copies)
+ hash_table_dtor(temps);
+
+ return last;
+}
+
+/**
+ * Get the function signature for main from a shader
+ */
+static ir_function_signature *
+get_main_function_signature(gl_shader *sh)
+{
+ ir_function *const f = sh->symbols->get_function("main");
+ if (f != NULL) {
+ exec_list void_parameters;
+
+ /* Look for the 'void main()' signature and ensure that it's defined.
+ * This keeps the linker from accidentally pick a shader that just
+ * contains a prototype for main.
+ *
+ * We don't have to check for multiple definitions of main (in multiple
+ * shaders) because that would have already been caught above.
+ */
+ ir_function_signature *sig = f->matching_signature(&void_parameters);
+ if ((sig != NULL) && sig->is_defined) {
+ return sig;
+ }
+ }
+
+ return NULL;
+}
+
+
+/**
+ * Combine a group of shaders for a single stage to generate a linked shader
+ *
+ * \note
+ * If this function is supplied a single shader, it is cloned, and the new
+ * shader is returned.
+ */
+static struct gl_shader *
+link_intrastage_shaders(void *mem_ctx,
+ struct gl_context *ctx,
+ struct gl_shader_program *prog,
+ struct gl_shader **shader_list,
+ unsigned num_shaders)
+{
+ /* Check that global variables defined in multiple shaders are consistent.
+ */
+ if (!cross_validate_globals(prog, shader_list, num_shaders, false))
+ return NULL;
+
+ /* Check that there is only a single definition of each function signature
+ * across all shaders.
+ */
+ for (unsigned i = 0; i < (num_shaders - 1); i++) {
+ foreach_list(node, shader_list[i]->ir) {
+ ir_function *const f = ((ir_instruction *) node)->as_function();
+
+ if (f == NULL)
+ continue;
+
+ for (unsigned j = i + 1; j < num_shaders; j++) {
+ ir_function *const other =
+ shader_list[j]->symbols->get_function(f->name);
+
+ /* If the other shader has no function (and therefore no function
+ * signatures) with the same name, skip to the next shader.
+ */
+ if (other == NULL)
+ continue;
+
+ foreach_iter (exec_list_iterator, iter, *f) {
+ ir_function_signature *sig =
+ (ir_function_signature *) iter.get();
+
+ if (!sig->is_defined || sig->is_builtin)
+ continue;
+
+ ir_function_signature *other_sig =
+ other->exact_matching_signature(& sig->parameters);
+
+ if ((other_sig != NULL) && other_sig->is_defined
+ && !other_sig->is_builtin) {
+ linker_error_printf(prog,
+ "function `%s' is multiply defined",
+ f->name);
+ return NULL;
+ }
+ }
+ }
+ }
+ }
+
+ /* Find the shader that defines main, and make a clone of it.
+ *
+ * Starting with the clone, search for undefined references. If one is
+ * found, find the shader that defines it. Clone the reference and add
+ * it to the shader. Repeat until there are no undefined references or
+ * until a reference cannot be resolved.
+ */
+ gl_shader *main = NULL;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (get_main_function_signature(shader_list[i]) != NULL) {
+ main = shader_list[i];
+ break;
+ }
+ }
+
+ if (main == NULL) {
+ linker_error_printf(prog, "%s shader lacks `main'\n",
+ (shader_list[0]->Type == GL_VERTEX_SHADER)
+ ? "vertex" : "fragment");
+ return NULL;
+ }
+
+ gl_shader *linked = ctx->Driver.NewShader(NULL, 0, main->Type);
+ linked->ir = new(linked) exec_list;
+ clone_ir_list(mem_ctx, linked->ir, main->ir);
+
+ populate_symbol_table(linked);
+
+ /* The a pointer to the main function in the final linked shader (i.e., the
+ * copy of the original shader that contained the main function).
+ */
+ ir_function_signature *const main_sig = get_main_function_signature(linked);
+
+ /* Move any instructions other than variable declarations or function
+ * declarations into main.
+ */
+ exec_node *insertion_point =
+ move_non_declarations(linked->ir, (exec_node *) &main_sig->body, false,
+ linked);
+
+ for (unsigned i = 0; i < num_shaders; i++) {
+ if (shader_list[i] == main)
+ continue;
+
+ insertion_point = move_non_declarations(shader_list[i]->ir,
+ insertion_point, true, linked);
+ }
+
+ /* Resolve initializers for global variables in the linked shader.
+ */
+ unsigned num_linking_shaders = num_shaders;
+ for (unsigned i = 0; i < num_shaders; i++)
+ num_linking_shaders += shader_list[i]->num_builtins_to_link;
+
+ gl_shader **linking_shaders =
+ (gl_shader **) calloc(num_linking_shaders, sizeof(gl_shader *));
+
+ memcpy(linking_shaders, shader_list,
+ sizeof(linking_shaders[0]) * num_shaders);
+
+ unsigned idx = num_shaders;
+ for (unsigned i = 0; i < num_shaders; i++) {
+ memcpy(&linking_shaders[idx], shader_list[i]->builtins_to_link,
+ sizeof(linking_shaders[0]) * shader_list[i]->num_builtins_to_link);
+ idx += shader_list[i]->num_builtins_to_link;
+ }
+
+ assert(idx == num_linking_shaders);
+
+ if (!link_function_calls(prog, linked, linking_shaders,
+ num_linking_shaders)) {
+ ctx->Driver.DeleteShader(ctx, linked);
+ linked = NULL;
+ }
+
+ free(linking_shaders);
+
+ /* Make a pass over all variable declarations to ensure that arrays with
+ * unspecified sizes have a size specified. The size is inferred from the
+ * max_array_access field.
+ */
+ if (linked != NULL) {
+ class array_sizing_visitor : public ir_hierarchical_visitor {
+ public:
+ virtual ir_visitor_status visit(ir_variable *var)
+ {
+ if (var->type->is_array() && (var->type->length == 0)) {
+ const glsl_type *type =
+ glsl_type::get_array_instance(var->type->fields.array,
+ var->max_array_access + 1);
+
+ assert(type != NULL);
+ var->type = type;
+ }
+
+ return visit_continue;
+ }
+ } v;
+
+ v.run(linked->ir);
+ }
+
+ return linked;
+}
+
+
+struct uniform_node {
+ exec_node link;
+ struct gl_uniform *u;
+ unsigned slots;
+};
+
+/**
+ * Update the sizes of linked shader uniform arrays to the maximum
+ * array index used.
+ *
+ * From page 81 (page 95 of the PDF) of the OpenGL 2.1 spec:
+ *
+ * If one or more elements of an array are active,
+ * GetActiveUniform will return the name of the array in name,
+ * subject to the restrictions listed above. The type of the array
+ * is returned in type. The size parameter contains the highest
+ * array element index used, plus one. The compiler or linker
+ * determines the highest index used. There will be only one
+ * active uniform reported by the GL per uniform array.
+
+ */
+static void
+update_array_sizes(struct gl_shader_program *prog)
+{
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ foreach_list(node, prog->_LinkedShaders[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_uniform &&
+ var->mode != ir_var_in &&
+ var->mode != ir_var_out) ||
+ !var->type->is_array())
+ continue;
+
+ unsigned int size = var->max_array_access;
+ for (unsigned j = 0; j < MESA_SHADER_TYPES; j++) {
+ if (prog->_LinkedShaders[j] == NULL)
+ continue;
+
+ foreach_list(node2, prog->_LinkedShaders[j]->ir) {
+ ir_variable *other_var = ((ir_instruction *) node2)->as_variable();
+ if (!other_var)
+ continue;
+
+ if (strcmp(var->name, other_var->name) == 0 &&
+ other_var->max_array_access > size) {
+ size = other_var->max_array_access;
+ }
+ }
+ }
+
+ if (size + 1 != var->type->fields.array->length) {
+ var->type = glsl_type::get_array_instance(var->type->fields.array,
+ size + 1);
+ /* FINISHME: We should update the types of array
+ * dereferences of this variable now.
+ */
+ }
+ }
+ }
+}
+
+static void
+add_uniform(void *mem_ctx, exec_list *uniforms, struct hash_table *ht,
+ const char *name, const glsl_type *type, GLenum shader_type,
+ unsigned *next_shader_pos, unsigned *total_uniforms)
+{
+ if (type->is_record()) {
+ for (unsigned int i = 0; i < type->length; i++) {
+ const glsl_type *field_type = type->fields.structure[i].type;
+ char *field_name = ralloc_asprintf(mem_ctx, "%s.%s", name,
+ type->fields.structure[i].name);
+
+ add_uniform(mem_ctx, uniforms, ht, field_name, field_type,
+ shader_type, next_shader_pos, total_uniforms);
+ }
+ } else {
+ uniform_node *n = (uniform_node *) hash_table_find(ht, name);
+ unsigned int vec4_slots;
+ const glsl_type *array_elem_type = NULL;
+
+ if (type->is_array()) {
+ array_elem_type = type->fields.array;
+ /* Array of structures. */
+ if (array_elem_type->is_record()) {
+ for (unsigned int i = 0; i < type->length; i++) {
+ char *elem_name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
+ add_uniform(mem_ctx, uniforms, ht, elem_name, array_elem_type,
+ shader_type, next_shader_pos, total_uniforms);
+ }
+ return;
+ }
+ }
+
+ /* Fix the storage size of samplers at 1 vec4 each. Be sure to pad out
+ * vectors to vec4 slots.
+ */
+ if (type->is_array()) {
+ if (array_elem_type->is_sampler())
+ vec4_slots = type->length;
+ else
+ vec4_slots = type->length * array_elem_type->matrix_columns;
+ } else if (type->is_sampler()) {
+ vec4_slots = 1;
+ } else {
+ vec4_slots = type->matrix_columns;
+ }
+
+ if (n == NULL) {
+ n = (uniform_node *) calloc(1, sizeof(struct uniform_node));
+ n->u = (gl_uniform *) calloc(1, sizeof(struct gl_uniform));
+ n->slots = vec4_slots;
+
+ n->u->Name = strdup(name);
+ n->u->Type = type;
+ n->u->VertPos = -1;
+ n->u->FragPos = -1;
+ n->u->GeomPos = -1;
+ (*total_uniforms)++;
+
+ hash_table_insert(ht, n, name);
+ uniforms->push_tail(& n->link);
+ }
+
+ switch (shader_type) {
+ case GL_VERTEX_SHADER:
+ n->u->VertPos = *next_shader_pos;
+ break;
+ case GL_FRAGMENT_SHADER:
+ n->u->FragPos = *next_shader_pos;
+ break;
+ case GL_GEOMETRY_SHADER:
+ n->u->GeomPos = *next_shader_pos;
+ break;
+ }
+
+ (*next_shader_pos) += vec4_slots;
+ }
+}
+
+void
+assign_uniform_locations(struct gl_shader_program *prog)
+{
+ /* */
+ exec_list uniforms;
+ unsigned total_uniforms = 0;
+ hash_table *ht = hash_table_ctor(32, hash_table_string_hash,
+ hash_table_string_compare);
+ void *mem_ctx = ralloc_context(NULL);
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ unsigned next_position = 0;
+
+ foreach_list(node, prog->_LinkedShaders[i]->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_uniform))
+ continue;
+
+ if (strncmp(var->name, "gl_", 3) == 0) {
+ /* At the moment, we don't allocate uniform locations for
+ * builtin uniforms. It's permitted by spec, and we'll
+ * likely switch to doing that at some point, but not yet.
+ */
+ continue;
+ }
+
+ var->location = next_position;
+ add_uniform(mem_ctx, &uniforms, ht, var->name, var->type,
+ prog->_LinkedShaders[i]->Type,
+ &next_position, &total_uniforms);
+ }
+ }
+
+ ralloc_free(mem_ctx);
+
+ gl_uniform_list *ul = (gl_uniform_list *)
+ calloc(1, sizeof(gl_uniform_list));
+
+ ul->Size = total_uniforms;
+ ul->NumUniforms = total_uniforms;
+ ul->Uniforms = (gl_uniform *) calloc(total_uniforms, sizeof(gl_uniform));
+
+ unsigned idx = 0;
+ uniform_node *next;
+ for (uniform_node *node = (uniform_node *) uniforms.head
+ ; node->link.next != NULL
+ ; node = next) {
+ next = (uniform_node *) node->link.next;
+
+ node->link.remove();
+ memcpy(&ul->Uniforms[idx], node->u, sizeof(gl_uniform));
+ idx++;
+
+ free(node->u);
+ free(node);
+ }
+
+ hash_table_dtor(ht);
+
+ prog->Uniforms = ul;
+}
+
+
+/**
+ * Find a contiguous set of available bits in a bitmask
+ *
+ * \param used_mask Bits representing used (1) and unused (0) locations
+ * \param needed_count Number of contiguous bits needed.
+ *
+ * \return
+ * Base location of the available bits on success or -1 on failure.
+ */
+int
+find_available_slots(unsigned used_mask, unsigned needed_count)
+{
+ unsigned needed_mask = (1 << needed_count) - 1;
+ const int max_bit_to_test = (8 * sizeof(used_mask)) - needed_count;
+
+ /* The comparison to 32 is redundant, but without it GCC emits "warning:
+ * cannot optimize possibly infinite loops" for the loop below.
+ */
+ if ((needed_count == 0) || (max_bit_to_test < 0) || (max_bit_to_test > 32))
+ return -1;
+
+ for (int i = 0; i <= max_bit_to_test; i++) {
+ if ((needed_mask & ~used_mask) == needed_mask)
+ return i;
+
+ needed_mask <<= 1;
+ }
+
+ return -1;
+}
+
+
+bool
+assign_attribute_locations(gl_shader_program *prog, unsigned max_attribute_index)
+{
+ /* Mark invalid attribute locations as being used.
+ */
+ unsigned used_locations = (max_attribute_index >= 32)
+ ? ~0 : ~((1 << max_attribute_index) - 1);
+
+ gl_shader *const sh = prog->_LinkedShaders[0];
+ assert(sh->Type == GL_VERTEX_SHADER);
+
+ /* Operate in a total of four passes.
+ *
+ * 1. Invalidate the location assignments for all vertex shader inputs.
+ *
+ * 2. Assign locations for inputs that have user-defined (via
+ * glBindVertexAttribLocation) locatoins.
+ *
+ * 3. Sort the attributes without assigned locations by number of slots
+ * required in decreasing order. Fragmentation caused by attribute
+ * locations assigned by the application may prevent large attributes
+ * from having enough contiguous space.
+ *
+ * 4. Assign locations to any inputs without assigned locations.
+ */
+
+ invalidate_variable_locations(sh, ir_var_in, VERT_ATTRIB_GENERIC0);
+
+ if (prog->Attributes != NULL) {
+ for (unsigned i = 0; i < prog->Attributes->NumParameters; i++) {
+ ir_variable *const var =
+ sh->symbols->get_variable(prog->Attributes->Parameters[i].Name);
+
+ /* Note: attributes that occupy multiple slots, such as arrays or
+ * matrices, may appear in the attrib array multiple times.
+ */
+ if ((var == NULL) || (var->location != -1))
+ continue;
+
+ /* From page 61 of the OpenGL 4.0 spec:
+ *
+ * "LinkProgram will fail if the attribute bindings assigned by
+ * BindAttribLocation do not leave not enough space to assign a
+ * location for an active matrix attribute or an active attribute
+ * array, both of which require multiple contiguous generic
+ * attributes."
+ *
+ * Previous versions of the spec contain similar language but omit the
+ * bit about attribute arrays.
+ *
+ * Page 61 of the OpenGL 4.0 spec also says:
+ *
+ * "It is possible for an application to bind more than one
+ * attribute name to the same location. This is referred to as
+ * aliasing. This will only work if only one of the aliased
+ * attributes is active in the executable program, or if no path
+ * through the shader consumes more than one attribute of a set
+ * of attributes aliased to the same location. A link error can
+ * occur if the linker determines that every path through the
+ * shader consumes multiple aliased attributes, but
+ * implementations are not required to generate an error in this
+ * case."
+ *
+ * These two paragraphs are either somewhat contradictory, or I don't
+ * fully understand one or both of them.
+ */
+ /* FINISHME: The code as currently written does not support attribute
+ * FINISHME: location aliasing (see comment above).
+ */
+ const int attr = prog->Attributes->Parameters[i].StateIndexes[0];
+ const unsigned slots = count_attribute_slots(var->type);
+
+ /* Mask representing the contiguous slots that will be used by this
+ * attribute.
+ */
+ const unsigned use_mask = (1 << slots) - 1;
+
+ /* Generate a link error if the set of bits requested for this
+ * attribute overlaps any previously allocated bits.
+ */
+ if ((~(use_mask << attr) & used_locations) != used_locations) {
+ linker_error_printf(prog,
+ "insufficient contiguous attribute locations "
+ "available for vertex shader input `%s'",
+ var->name);
+ return false;
+ }
+
+ var->location = VERT_ATTRIB_GENERIC0 + attr;
+ used_locations |= (use_mask << attr);
+ }
+ }
+
+ /* Temporary storage for the set of attributes that need locations assigned.
+ */
+ struct temp_attr {
+ unsigned slots;
+ ir_variable *var;
+
+ /* Used below in the call to qsort. */
+ static int compare(const void *a, const void *b)
+ {
+ const temp_attr *const l = (const temp_attr *) a;
+ const temp_attr *const r = (const temp_attr *) b;
+
+ /* Reversed because we want a descending order sort below. */
+ return r->slots - l->slots;
+ }
+ } to_assign[16];
+
+ unsigned num_attr = 0;
+
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_in))
+ continue;
+
+ if (var->explicit_location) {
+ const unsigned slots = count_attribute_slots(var->type);
+ const unsigned use_mask = (1 << slots) - 1;
+ const int attr = var->location - VERT_ATTRIB_GENERIC0;
+
+ if ((var->location >= (int)(max_attribute_index + VERT_ATTRIB_GENERIC0))
+ || (var->location < 0)) {
+ linker_error_printf(prog,
+ "invalid explicit location %d specified for "
+ "`%s'\n",
+ (var->location < 0) ? var->location : attr,
+ var->name);
+ return false;
+ } else if (var->location >= VERT_ATTRIB_GENERIC0) {
+ used_locations |= (use_mask << attr);
+ }
+ }
+
+ /* The location was explicitly assigned, nothing to do here.
+ */
+ if (var->location != -1)
+ continue;
+
+ to_assign[num_attr].slots = count_attribute_slots(var->type);
+ to_assign[num_attr].var = var;
+ num_attr++;
+ }
+
+ /* If all of the attributes were assigned locations by the application (or
+ * are built-in attributes with fixed locations), return early. This should
+ * be the common case.
+ */
+ if (num_attr == 0)
+ return true;
+
+ qsort(to_assign, num_attr, sizeof(to_assign[0]), temp_attr::compare);
+
+ /* VERT_ATTRIB_GENERIC0 is a psdueo-alias for VERT_ATTRIB_POS. It can only
+ * be explicitly assigned by via glBindAttribLocation. Mark it as reserved
+ * to prevent it from being automatically allocated below.
+ */
+ find_deref_visitor find("gl_Vertex");
+ find.run(sh->ir);
+ if (find.variable_found())
+ used_locations |= (1 << 0);
+
+ for (unsigned i = 0; i < num_attr; i++) {
+ /* Mask representing the contiguous slots that will be used by this
+ * attribute.
+ */
+ const unsigned use_mask = (1 << to_assign[i].slots) - 1;
+
+ int location = find_available_slots(used_locations, to_assign[i].slots);
+
+ if (location < 0) {
+ linker_error_printf(prog,
+ "insufficient contiguous attribute locations "
+ "available for vertex shader input `%s'",
+ to_assign[i].var->name);
+ return false;
+ }
+
+ to_assign[i].var->location = VERT_ATTRIB_GENERIC0 + location;
+ used_locations |= (use_mask << location);
+ }
+
+ return true;
+}
+
+
+/**
+ * Demote shader inputs and outputs that are not used in other stages
+ */
+void
+demote_shader_inputs_and_outputs(gl_shader *sh, enum ir_variable_mode mode)
+{
+ foreach_list(node, sh->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != int(mode)))
+ continue;
+
+ /* A shader 'in' or 'out' variable is only really an input or output if
+ * its value is used by other shader stages. This will cause the variable
+ * to have a location assigned.
+ */
+ if (var->location == -1) {
+ var->mode = ir_var_auto;
+ }
+ }
+}
+
+
+void
+assign_varying_locations(struct gl_shader_program *prog,
+ gl_shader *producer, gl_shader *consumer)
+{
+ /* FINISHME: Set dynamically when geometry shader support is added. */
+ unsigned output_index = VERT_RESULT_VAR0;
+ unsigned input_index = FRAG_ATTRIB_VAR0;
+
+ /* Operate in a total of three passes.
+ *
+ * 1. Assign locations for any matching inputs and outputs.
+ *
+ * 2. Mark output variables in the producer that do not have locations as
+ * not being outputs. This lets the optimizer eliminate them.
+ *
+ * 3. Mark input variables in the consumer that do not have locations as
+ * not being inputs. This lets the optimizer eliminate them.
+ */
+
+ invalidate_variable_locations(producer, ir_var_out, VERT_RESULT_VAR0);
+ invalidate_variable_locations(consumer, ir_var_in, FRAG_ATTRIB_VAR0);
+
+ foreach_list(node, producer->ir) {
+ ir_variable *const output_var = ((ir_instruction *) node)->as_variable();
+
+ if ((output_var == NULL) || (output_var->mode != ir_var_out)
+ || (output_var->location != -1))
+ continue;
+
+ ir_variable *const input_var =
+ consumer->symbols->get_variable(output_var->name);
+
+ if ((input_var == NULL) || (input_var->mode != ir_var_in))
+ continue;
+
+ assert(input_var->location == -1);
+
+ output_var->location = output_index;
+ input_var->location = input_index;
+
+ /* FINISHME: Support for "varying" records in GLSL 1.50. */
+ assert(!output_var->type->is_record());
+
+ if (output_var->type->is_array()) {
+ const unsigned slots = output_var->type->length
+ * output_var->type->fields.array->matrix_columns;
+
+ output_index += slots;
+ input_index += slots;
+ } else {
+ const unsigned slots = output_var->type->matrix_columns;
+
+ output_index += slots;
+ input_index += slots;
+ }
+ }
+
+ foreach_list(node, consumer->ir) {
+ ir_variable *const var = ((ir_instruction *) node)->as_variable();
+
+ if ((var == NULL) || (var->mode != ir_var_in))
+ continue;
+
+ if (var->location == -1) {
+ if (prog->Version <= 120) {
+ /* On page 25 (page 31 of the PDF) of the GLSL 1.20 spec:
+ *
+ * Only those varying variables used (i.e. read) in
+ * the fragment shader executable must be written to
+ * by the vertex shader executable; declaring
+ * superfluous varying variables in a vertex shader is
+ * permissible.
+ *
+ * We interpret this text as meaning that the VS must
+ * write the variable for the FS to read it. See
+ * "glsl1-varying read but not written" in piglit.
+ */
+
+ linker_error_printf(prog, "fragment shader varying %s not written "
+ "by vertex shader\n.", var->name);
+ prog->LinkStatus = false;
+ }
+
+ /* An 'in' variable is only really a shader input if its
+ * value is written by the previous stage.
+ */
+ var->mode = ir_var_auto;
+ }
+ }
+}
+
+
+void
+link_shaders(struct gl_context *ctx, struct gl_shader_program *prog)
+{
+ void *mem_ctx = ralloc_context(NULL); // temporary linker context
+
+ prog->LinkStatus = false;
+ prog->Validated = false;
+ prog->_Used = false;
+
+ if (prog->InfoLog != NULL)
+ ralloc_free(prog->InfoLog);
+
+ prog->InfoLog = ralloc_strdup(NULL, "");
+
+ /* Separate the shaders into groups based on their type.
+ */
+ struct gl_shader **vert_shader_list;
+ unsigned num_vert_shaders = 0;
+ struct gl_shader **frag_shader_list;
+ unsigned num_frag_shaders = 0;
+
+ vert_shader_list = (struct gl_shader **)
+ calloc(2 * prog->NumShaders, sizeof(struct gl_shader *));
+ frag_shader_list = &vert_shader_list[prog->NumShaders];
+
+ unsigned min_version = UINT_MAX;
+ unsigned max_version = 0;
+ for (unsigned i = 0; i < prog->NumShaders; i++) {
+ min_version = MIN2(min_version, prog->Shaders[i]->Version);
+ max_version = MAX2(max_version, prog->Shaders[i]->Version);
+
+ switch (prog->Shaders[i]->Type) {
+ case GL_VERTEX_SHADER:
+ vert_shader_list[num_vert_shaders] = prog->Shaders[i];
+ num_vert_shaders++;
+ break;
+ case GL_FRAGMENT_SHADER:
+ frag_shader_list[num_frag_shaders] = prog->Shaders[i];
+ num_frag_shaders++;
+ break;
+ case GL_GEOMETRY_SHADER:
+ /* FINISHME: Support geometry shaders. */
+ assert(prog->Shaders[i]->Type != GL_GEOMETRY_SHADER);
+ break;
+ }
+ }
+
+ /* Previous to GLSL version 1.30, different compilation units could mix and
+ * match shading language versions. With GLSL 1.30 and later, the versions
+ * of all shaders must match.
+ */
+ assert(min_version >= 100);
+ assert(max_version <= 130);
+ if ((max_version >= 130 || min_version == 100)
+ && min_version != max_version) {
+ linker_error_printf(prog, "all shaders must use same shading "
+ "language version\n");
+ goto done;
+ }
+
+ prog->Version = max_version;
+
+ for (unsigned int i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] != NULL)
+ ctx->Driver.DeleteShader(ctx, prog->_LinkedShaders[i]);
+
+ prog->_LinkedShaders[i] = NULL;
+ }
+
+ /* Link all shaders for a particular stage and validate the result.
+ */
+ if (num_vert_shaders > 0) {
+ gl_shader *const sh =
+ link_intrastage_shaders(mem_ctx, ctx, prog, vert_shader_list,
+ num_vert_shaders);
+
+ if (sh == NULL)
+ goto done;
+
+ if (!validate_vertex_shader_executable(prog, sh))
+ goto done;
+
+ _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_VERTEX],
+ sh);
+ }
+
+ if (num_frag_shaders > 0) {
+ gl_shader *const sh =
+ link_intrastage_shaders(mem_ctx, ctx, prog, frag_shader_list,
+ num_frag_shaders);
+
+ if (sh == NULL)
+ goto done;
+
+ if (!validate_fragment_shader_executable(prog, sh))
+ goto done;
+
+ _mesa_reference_shader(ctx, &prog->_LinkedShaders[MESA_SHADER_FRAGMENT],
+ sh);
+ }
+
+ /* Here begins the inter-stage linking phase. Some initial validation is
+ * performed, then locations are assigned for uniforms, attributes, and
+ * varyings.
+ */
+ if (cross_validate_uniforms(prog)) {
+ unsigned prev;
+
+ for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
+ if (prog->_LinkedShaders[prev] != NULL)
+ break;
+ }
+
+ /* Validate the inputs of each stage with the output of the preceeding
+ * stage.
+ */
+ for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ if (!cross_validate_outputs_to_inputs(prog,
+ prog->_LinkedShaders[prev],
+ prog->_LinkedShaders[i]))
+ goto done;
+
+ prev = i;
+ }
+
+ prog->LinkStatus = true;
+ }
+
+ /* Do common optimization before assigning storage for attributes,
+ * uniforms, and varyings. Later optimization could possibly make
+ * some of that unused.
+ */
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ while (do_common_optimization(prog->_LinkedShaders[i]->ir, true, 32))
+ ;
+ }
+
+ update_array_sizes(prog);
+
+ assign_uniform_locations(prog);
+
+ if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
+ /* FINISHME: The value of the max_attribute_index parameter is
+ * FINISHME: implementation dependent based on the value of
+ * FINISHME: GL_MAX_VERTEX_ATTRIBS. GL_MAX_VERTEX_ATTRIBS must be
+ * FINISHME: at least 16, so hardcode 16 for now.
+ */
+ if (!assign_attribute_locations(prog, 16)) {
+ prog->LinkStatus = false;
+ goto done;
+ }
+ }
+
+ unsigned prev;
+ for (prev = 0; prev < MESA_SHADER_TYPES; prev++) {
+ if (prog->_LinkedShaders[prev] != NULL)
+ break;
+ }
+
+ for (unsigned i = prev + 1; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ assign_varying_locations(prog,
+ prog->_LinkedShaders[prev],
+ prog->_LinkedShaders[i]);
+ prev = i;
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_VERTEX] != NULL) {
+ demote_shader_inputs_and_outputs(prog->_LinkedShaders[MESA_SHADER_VERTEX],
+ ir_var_out);
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_GEOMETRY] != NULL) {
+ gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_GEOMETRY];
+
+ demote_shader_inputs_and_outputs(sh, ir_var_in);
+ demote_shader_inputs_and_outputs(sh, ir_var_inout);
+ demote_shader_inputs_and_outputs(sh, ir_var_out);
+ }
+
+ if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] != NULL) {
+ gl_shader *const sh = prog->_LinkedShaders[MESA_SHADER_FRAGMENT];
+
+ demote_shader_inputs_and_outputs(sh, ir_var_in);
+ }
+
+ /* OpenGL ES requires that a vertex shader and a fragment shader both be
+ * present in a linked program. By checking for use of shading language
+ * version 1.00, we also catch the GL_ARB_ES2_compatibility case.
+ */
+ if (ctx->API == API_OPENGLES2 || prog->Version == 100) {
+ if (prog->_LinkedShaders[MESA_SHADER_VERTEX] == NULL) {
+ linker_error_printf(prog, "program lacks a vertex shader\n");
+ prog->LinkStatus = false;
+ } else if (prog->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL) {
+ linker_error_printf(prog, "program lacks a fragment shader\n");
+ prog->LinkStatus = false;
+ }
+ }
+
+ /* FINISHME: Assign fragment shader output locations. */
+
+done:
+ free(vert_shader_list);
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (prog->_LinkedShaders[i] == NULL)
+ continue;
+
+ /* Retain any live IR, but trash the rest. */
+ reparent_ir(prog->_LinkedShaders[i]->ir, prog->_LinkedShaders[i]->ir);
+ }
+
+ ralloc_free(mem_ctx);
+}
diff --git a/mesalib/src/glsl/list.h b/mesalib/src/glsl/list.h
index 1d46365fa..fb6f0fbba 100644
--- a/mesalib/src/glsl/list.h
+++ b/mesalib/src/glsl/list.h
@@ -90,6 +90,10 @@ struct exec_node {
/* If the user *does* call delete, that's OK, we will just
* ralloc_free in that case. */
+ static void operator delete(void *node, void *ctx)
+ {
+ ralloc_free(node);
+ }
static void operator delete(void *node)
{
ralloc_free(node);
@@ -299,6 +303,10 @@ struct exec_list {
/* If the user *does* call delete, that's OK, we will just
* ralloc_free in that case. */
+ static void operator delete(void *node, void *ctx)
+ {
+ ralloc_free(node);
+ }
static void operator delete(void *node)
{
ralloc_free(node);
diff --git a/mesalib/src/glsl/loop_controls.cpp b/mesalib/src/glsl/loop_controls.cpp
index 9acbadc50..9b77ef460 100644
--- a/mesalib/src/glsl/loop_controls.cpp
+++ b/mesalib/src/glsl/loop_controls.cpp
@@ -1,304 +1,304 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include <limits.h>
-#include "main/compiler.h"
-#include "glsl_types.h"
-#include "loop_analysis.h"
-#include "ir_hierarchical_visitor.h"
-
-/**
- * Find an initializer of a variable outside a loop
- *
- * Works backwards from the loop to find the pre-loop value of the variable.
- * This is used, for example, to find the initial value of loop induction
- * variables.
- *
- * \param loop Loop where \c var is an induction variable
- * \param var Variable whose initializer is to be found
- *
- * \return
- * The \c ir_rvalue assigned to the variable outside the loop. May return
- * \c NULL if no initializer can be found.
- */
-ir_rvalue *
-find_initial_value(ir_loop *loop, ir_variable *var)
-{
- for (exec_node *node = loop->prev;
- !node->is_head_sentinel();
- node = node->prev) {
- ir_instruction *ir = (ir_instruction *) node;
-
- switch (ir->ir_type) {
- case ir_type_call:
- case ir_type_loop:
- case ir_type_loop_jump:
- case ir_type_return:
- case ir_type_if:
- return NULL;
-
- case ir_type_function:
- case ir_type_function_signature:
- assert(!"Should not get here.");
- return NULL;
-
- case ir_type_assignment: {
- ir_assignment *assign = ir->as_assignment();
- ir_variable *assignee = assign->lhs->whole_variable_referenced();
-
- if (assignee == var)
- return (assign->condition != NULL) ? NULL : assign->rhs;
-
- break;
- }
-
- default:
- break;
- }
- }
-
- return NULL;
-}
-
-
-int
-calculate_iterations(ir_rvalue *from, ir_rvalue *to, ir_rvalue *increment,
- enum ir_expression_operation op)
-{
- if (from == NULL || to == NULL || increment == NULL)
- return -1;
-
- void *mem_ctx = ralloc_context(NULL);
-
- ir_expression *const sub =
- new(mem_ctx) ir_expression(ir_binop_sub, from->type, to, from);
-
- ir_expression *const div =
- new(mem_ctx) ir_expression(ir_binop_div, sub->type, sub, increment);
-
- ir_constant *iter = div->constant_expression_value();
-
- if (iter == NULL)
- return -1;
-
- if (!iter->type->is_integer()) {
- ir_rvalue *cast =
- new(mem_ctx) ir_expression(ir_unop_f2i, glsl_type::int_type, iter,
- NULL);
-
- iter = cast->constant_expression_value();
- }
-
- int iter_value = iter->get_int_component(0);
-
- /* Make sure that the calculated number of iterations satisfies the exit
- * condition. This is needed to catch off-by-one errors and some types of
- * ill-formed loops. For example, we need to detect that the following
- * loop does not have a maximum iteration count.
- *
- * for (float x = 0.0; x != 0.9; x += 0.2)
- * ;
- */
- const int bias[] = { -1, 0, 1 };
- bool valid_loop = false;
-
- for (unsigned i = 0; i < Elements(bias); i++) {
- iter = (increment->type->is_integer())
- ? new(mem_ctx) ir_constant(iter_value + bias[i])
- : new(mem_ctx) ir_constant(float(iter_value + bias[i]));
-
- ir_expression *const mul =
- new(mem_ctx) ir_expression(ir_binop_mul, increment->type, iter,
- increment);
-
- ir_expression *const add =
- new(mem_ctx) ir_expression(ir_binop_add, mul->type, mul, from);
-
- ir_expression *const cmp =
- new(mem_ctx) ir_expression(op, glsl_type::bool_type, add, to);
-
- ir_constant *const cmp_result = cmp->constant_expression_value();
-
- assert(cmp_result != NULL);
- if (cmp_result->get_bool_component(0)) {
- iter_value += bias[i];
- valid_loop = true;
- break;
- }
- }
-
- ralloc_free(mem_ctx);
- return (valid_loop) ? iter_value : -1;
-}
-
-
-class loop_control_visitor : public ir_hierarchical_visitor {
-public:
- loop_control_visitor(loop_state *state)
- {
- this->state = state;
- this->progress = false;
- }
-
- virtual ir_visitor_status visit_leave(ir_loop *ir);
-
- loop_state *state;
-
- bool progress;
-};
-
-
-ir_visitor_status
-loop_control_visitor::visit_leave(ir_loop *ir)
-{
- loop_variable_state *const ls = this->state->get(ir);
-
- /* If we've entered a loop that hasn't been analyzed, something really,
- * really bad has happened.
- */
- if (ls == NULL) {
- assert(ls != NULL);
- return visit_continue;
- }
-
- /* Search the loop terminating conditions for one of the form 'i < c' where
- * i is a loop induction variable, c is a constant, and < is any relative
- * operator.
- */
- int max_iterations = ls->max_iterations;
-
- if(ir->from && ir->to && ir->increment)
- max_iterations = calculate_iterations(ir->from, ir->to, ir->increment, (ir_expression_operation)ir->cmp);
-
- if(max_iterations < 0)
- max_iterations = INT_MAX;
-
- foreach_list(node, &ls->terminators) {
- loop_terminator *t = (loop_terminator *) node;
- ir_if *if_stmt = t->ir;
-
- /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care
- * about the former here.
- */
- ir_expression *cond = if_stmt->condition->as_expression();
- if (cond == NULL)
- continue;
-
- switch (cond->operation) {
- case ir_binop_less:
- case ir_binop_greater:
- case ir_binop_lequal:
- case ir_binop_gequal: {
- /* The expressions that we care about will either be of the form
- * 'counter < limit' or 'limit < counter'. Figure out which is
- * which.
- */
- ir_rvalue *counter = cond->operands[0]->as_dereference_variable();
- ir_constant *limit = cond->operands[1]->as_constant();
- enum ir_expression_operation cmp = cond->operation;
-
- if (limit == NULL) {
- counter = cond->operands[1]->as_dereference_variable();
- limit = cond->operands[0]->as_constant();
-
- switch (cmp) {
- case ir_binop_less: cmp = ir_binop_gequal; break;
- case ir_binop_greater: cmp = ir_binop_lequal; break;
- case ir_binop_lequal: cmp = ir_binop_greater; break;
- case ir_binop_gequal: cmp = ir_binop_less; break;
- default: assert(!"Should not get here.");
- }
- }
-
- if ((counter == NULL) || (limit == NULL))
- break;
-
- ir_variable *var = counter->variable_referenced();
-
- ir_rvalue *init = find_initial_value(ir, var);
-
- foreach_list(iv_node, &ls->induction_variables) {
- loop_variable *lv = (loop_variable *) iv_node;
-
- if (lv->var == var) {
- const int iterations = calculate_iterations(init, limit,
- lv->increment,
- cmp);
- if (iterations >= 0) {
- /* If the new iteration count is lower than the previously
- * believed iteration count, update the loop control values.
- */
- if (iterations < max_iterations) {
- ir->from = init->clone(ir, NULL);
- ir->to = limit->clone(ir, NULL);
- ir->increment = lv->increment->clone(ir, NULL);
- ir->counter = lv->var;
- ir->cmp = cmp;
-
- max_iterations = iterations;
- }
-
- /* Remove the conditional break statement. The loop
- * controls are now set such that the exit condition will be
- * satisfied.
- */
- if_stmt->remove();
-
- assert(ls->num_loop_jumps > 0);
- ls->num_loop_jumps--;
-
- this->progress = true;
- }
-
- break;
- }
- }
- break;
- }
-
- default:
- break;
- }
- }
-
- /* If we have proven the one of the loop exit conditions is satisifed before
- * running the loop once, remove the loop.
- */
- if (max_iterations == 0)
- ir->remove();
- else
- ls->max_iterations = max_iterations;
-
- return visit_continue;
-}
-
-
-bool
-set_loop_controls(exec_list *instructions, loop_state *ls)
-{
- loop_control_visitor v(ls);
-
- v.run(instructions);
-
- return v.progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include <limits.h>
+#include "main/compiler.h"
+#include "glsl_types.h"
+#include "loop_analysis.h"
+#include "ir_hierarchical_visitor.h"
+
+/**
+ * Find an initializer of a variable outside a loop
+ *
+ * Works backwards from the loop to find the pre-loop value of the variable.
+ * This is used, for example, to find the initial value of loop induction
+ * variables.
+ *
+ * \param loop Loop where \c var is an induction variable
+ * \param var Variable whose initializer is to be found
+ *
+ * \return
+ * The \c ir_rvalue assigned to the variable outside the loop. May return
+ * \c NULL if no initializer can be found.
+ */
+ir_rvalue *
+find_initial_value(ir_loop *loop, ir_variable *var)
+{
+ for (exec_node *node = loop->prev;
+ !node->is_head_sentinel();
+ node = node->prev) {
+ ir_instruction *ir = (ir_instruction *) node;
+
+ switch (ir->ir_type) {
+ case ir_type_call:
+ case ir_type_loop:
+ case ir_type_loop_jump:
+ case ir_type_return:
+ case ir_type_if:
+ return NULL;
+
+ case ir_type_function:
+ case ir_type_function_signature:
+ assert(!"Should not get here.");
+ return NULL;
+
+ case ir_type_assignment: {
+ ir_assignment *assign = ir->as_assignment();
+ ir_variable *assignee = assign->lhs->whole_variable_referenced();
+
+ if (assignee == var)
+ return (assign->condition != NULL) ? NULL : assign->rhs;
+
+ break;
+ }
+
+ default:
+ break;
+ }
+ }
+
+ return NULL;
+}
+
+
+int
+calculate_iterations(ir_rvalue *from, ir_rvalue *to, ir_rvalue *increment,
+ enum ir_expression_operation op)
+{
+ if (from == NULL || to == NULL || increment == NULL)
+ return -1;
+
+ void *mem_ctx = ralloc_context(NULL);
+
+ ir_expression *const sub =
+ new(mem_ctx) ir_expression(ir_binop_sub, from->type, to, from);
+
+ ir_expression *const div =
+ new(mem_ctx) ir_expression(ir_binop_div, sub->type, sub, increment);
+
+ ir_constant *iter = div->constant_expression_value();
+
+ if (iter == NULL)
+ return -1;
+
+ if (!iter->type->is_integer()) {
+ ir_rvalue *cast =
+ new(mem_ctx) ir_expression(ir_unop_f2i, glsl_type::int_type, iter,
+ NULL);
+
+ iter = cast->constant_expression_value();
+ }
+
+ int iter_value = iter->get_int_component(0);
+
+ /* Make sure that the calculated number of iterations satisfies the exit
+ * condition. This is needed to catch off-by-one errors and some types of
+ * ill-formed loops. For example, we need to detect that the following
+ * loop does not have a maximum iteration count.
+ *
+ * for (float x = 0.0; x != 0.9; x += 0.2)
+ * ;
+ */
+ const int bias[] = { -1, 0, 1 };
+ bool valid_loop = false;
+
+ for (unsigned i = 0; i < Elements(bias); i++) {
+ iter = (increment->type->is_integer())
+ ? new(mem_ctx) ir_constant(iter_value + bias[i])
+ : new(mem_ctx) ir_constant(float(iter_value + bias[i]));
+
+ ir_expression *const mul =
+ new(mem_ctx) ir_expression(ir_binop_mul, increment->type, iter,
+ increment);
+
+ ir_expression *const add =
+ new(mem_ctx) ir_expression(ir_binop_add, mul->type, mul, from);
+
+ ir_expression *const cmp =
+ new(mem_ctx) ir_expression(op, glsl_type::bool_type, add, to);
+
+ ir_constant *const cmp_result = cmp->constant_expression_value();
+
+ assert(cmp_result != NULL);
+ if (cmp_result->get_bool_component(0)) {
+ iter_value += bias[i];
+ valid_loop = true;
+ break;
+ }
+ }
+
+ ralloc_free(mem_ctx);
+ return (valid_loop) ? iter_value : -1;
+}
+
+
+class loop_control_visitor : public ir_hierarchical_visitor {
+public:
+ loop_control_visitor(loop_state *state)
+ {
+ this->state = state;
+ this->progress = false;
+ }
+
+ virtual ir_visitor_status visit_leave(ir_loop *ir);
+
+ loop_state *state;
+
+ bool progress;
+};
+
+
+ir_visitor_status
+loop_control_visitor::visit_leave(ir_loop *ir)
+{
+ loop_variable_state *const ls = this->state->get(ir);
+
+ /* If we've entered a loop that hasn't been analyzed, something really,
+ * really bad has happened.
+ */
+ if (ls == NULL) {
+ assert(ls != NULL);
+ return visit_continue;
+ }
+
+ /* Search the loop terminating conditions for one of the form 'i < c' where
+ * i is a loop induction variable, c is a constant, and < is any relative
+ * operator.
+ */
+ int max_iterations = ls->max_iterations;
+
+ if(ir->from && ir->to && ir->increment)
+ max_iterations = calculate_iterations(ir->from, ir->to, ir->increment, (ir_expression_operation)ir->cmp);
+
+ if(max_iterations < 0)
+ max_iterations = INT_MAX;
+
+ foreach_list(node, &ls->terminators) {
+ loop_terminator *t = (loop_terminator *) node;
+ ir_if *if_stmt = t->ir;
+
+ /* If-statements can be either 'if (expr)' or 'if (deref)'. We only care
+ * about the former here.
+ */
+ ir_expression *cond = if_stmt->condition->as_expression();
+ if (cond == NULL)
+ continue;
+
+ switch (cond->operation) {
+ case ir_binop_less:
+ case ir_binop_greater:
+ case ir_binop_lequal:
+ case ir_binop_gequal: {
+ /* The expressions that we care about will either be of the form
+ * 'counter < limit' or 'limit < counter'. Figure out which is
+ * which.
+ */
+ ir_rvalue *counter = cond->operands[0]->as_dereference_variable();
+ ir_constant *limit = cond->operands[1]->as_constant();
+ enum ir_expression_operation cmp = cond->operation;
+
+ if (limit == NULL) {
+ counter = cond->operands[1]->as_dereference_variable();
+ limit = cond->operands[0]->as_constant();
+
+ switch (cmp) {
+ case ir_binop_less: cmp = ir_binop_gequal; break;
+ case ir_binop_greater: cmp = ir_binop_lequal; break;
+ case ir_binop_lequal: cmp = ir_binop_greater; break;
+ case ir_binop_gequal: cmp = ir_binop_less; break;
+ default: assert(!"Should not get here.");
+ }
+ }
+
+ if ((counter == NULL) || (limit == NULL))
+ break;
+
+ ir_variable *var = counter->variable_referenced();
+
+ ir_rvalue *init = find_initial_value(ir, var);
+
+ foreach_list(iv_node, &ls->induction_variables) {
+ loop_variable *lv = (loop_variable *) iv_node;
+
+ if (lv->var == var) {
+ const int iterations = calculate_iterations(init, limit,
+ lv->increment,
+ cmp);
+ if (iterations >= 0) {
+ /* If the new iteration count is lower than the previously
+ * believed iteration count, update the loop control values.
+ */
+ if (iterations < max_iterations) {
+ ir->from = init->clone(ir, NULL);
+ ir->to = limit->clone(ir, NULL);
+ ir->increment = lv->increment->clone(ir, NULL);
+ ir->counter = lv->var;
+ ir->cmp = cmp;
+
+ max_iterations = iterations;
+ }
+
+ /* Remove the conditional break statement. The loop
+ * controls are now set such that the exit condition will be
+ * satisfied.
+ */
+ if_stmt->remove();
+
+ assert(ls->num_loop_jumps > 0);
+ ls->num_loop_jumps--;
+
+ this->progress = true;
+ }
+
+ break;
+ }
+ }
+ break;
+ }
+
+ default:
+ break;
+ }
+ }
+
+ /* If we have proven the one of the loop exit conditions is satisifed before
+ * running the loop once, remove the loop.
+ */
+ if (max_iterations == 0)
+ ir->remove();
+ else
+ ls->max_iterations = max_iterations;
+
+ return visit_continue;
+}
+
+
+bool
+set_loop_controls(exec_list *instructions, loop_state *ls)
+{
+ loop_control_visitor v(ls);
+
+ v.run(instructions);
+
+ return v.progress;
+}
diff --git a/mesalib/src/glsl/lower_mat_op_to_vec.cpp b/mesalib/src/glsl/lower_mat_op_to_vec.cpp
index 8cbbfa713..dc46ed417 100644
--- a/mesalib/src/glsl/lower_mat_op_to_vec.cpp
+++ b/mesalib/src/glsl/lower_mat_op_to_vec.cpp
@@ -1,490 +1,490 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 lower_mat_op_to_vec.cpp
- *
- * Breaks matrix operation expressions down to a series of vector operations.
- *
- * Generally this is how we have to codegen matrix operations for a
- * GPU, so this gives us the chance to constant fold operations on a
- * column or row.
- */
-
-#include "ir.h"
-#include "ir_expression_flattening.h"
-#include "glsl_types.h"
-
-class ir_mat_op_to_vec_visitor : public ir_hierarchical_visitor {
-public:
- ir_mat_op_to_vec_visitor()
- {
- this->made_progress = false;
- this->mem_ctx = NULL;
- }
-
- ir_visitor_status visit_leave(ir_assignment *);
-
- ir_dereference *get_column(ir_variable *var, int col);
- ir_rvalue *get_element(ir_variable *var, int col, int row);
-
- void do_mul_mat_mat(ir_variable *result_var,
- ir_variable *a_var, ir_variable *b_var);
- void do_mul_mat_vec(ir_variable *result_var,
- ir_variable *a_var, ir_variable *b_var);
- void do_mul_vec_mat(ir_variable *result_var,
- ir_variable *a_var, ir_variable *b_var);
- void do_mul_mat_scalar(ir_variable *result_var,
- ir_variable *a_var, ir_variable *b_var);
- void do_equal_mat_mat(ir_variable *result_var, ir_variable *a_var,
- ir_variable *b_var, bool test_equal);
-
- void *mem_ctx;
- bool made_progress;
-};
-
-static bool
-mat_op_to_vec_predicate(ir_instruction *ir)
-{
- ir_expression *expr = ir->as_expression();
- unsigned int i;
-
- if (!expr)
- return false;
-
- for (i = 0; i < expr->get_num_operands(); i++) {
- if (expr->operands[i]->type->is_matrix())
- return true;
- }
-
- return false;
-}
-
-bool
-do_mat_op_to_vec(exec_list *instructions)
-{
- ir_mat_op_to_vec_visitor v;
-
- /* Pull out any matrix expression to a separate assignment to a
- * temp. This will make our handling of the breakdown to
- * operations on the matrix's vector components much easier.
- */
- do_expression_flattening(instructions, mat_op_to_vec_predicate);
-
- visit_list_elements(&v, instructions);
-
- return v.made_progress;
-}
-
-ir_rvalue *
-ir_mat_op_to_vec_visitor::get_element(ir_variable *var, int col, int row)
-{
- ir_dereference *deref;
-
- deref = new(mem_ctx) ir_dereference_variable(var);
-
- if (var->type->is_matrix()) {
- deref = new(mem_ctx) ir_dereference_array(var,
- new(mem_ctx) ir_constant(col));
- } else {
- assert(col == 0);
- }
-
- return new(mem_ctx) ir_swizzle(deref, row, 0, 0, 0, 1);
-}
-
-ir_dereference *
-ir_mat_op_to_vec_visitor::get_column(ir_variable *var, int row)
-{
- ir_dereference *deref;
-
- if (!var->type->is_matrix()) {
- deref = new(mem_ctx) ir_dereference_variable(var);
- } else {
- deref = new(mem_ctx) ir_dereference_variable(var);
- deref = new(mem_ctx) ir_dereference_array(deref,
- new(mem_ctx) ir_constant(row));
- }
-
- return deref;
-}
-
-void
-ir_mat_op_to_vec_visitor::do_mul_mat_mat(ir_variable *result_var,
- ir_variable *a_var,
- ir_variable *b_var)
-{
- int b_col, i;
- ir_assignment *assign;
- ir_expression *expr;
-
- for (b_col = 0; b_col < b_var->type->matrix_columns; b_col++) {
- ir_rvalue *a = get_column(a_var, 0);
- ir_rvalue *b = get_element(b_var, b_col, 0);
-
- /* first column */
- expr = new(mem_ctx) ir_expression(ir_binop_mul,
- a->type,
- a,
- b);
-
- /* following columns */
- for (i = 1; i < a_var->type->matrix_columns; i++) {
- ir_expression *mul_expr;
-
- a = get_column(a_var, i);
- b = get_element(b_var, b_col, i);
-
- mul_expr = new(mem_ctx) ir_expression(ir_binop_mul,
- a->type,
- a,
- b);
- expr = new(mem_ctx) ir_expression(ir_binop_add,
- a->type,
- expr,
- mul_expr);
- }
-
- ir_rvalue *result = get_column(result_var, b_col);
- assign = new(mem_ctx) ir_assignment(result,
- expr,
- NULL);
- base_ir->insert_before(assign);
- }
-}
-
-void
-ir_mat_op_to_vec_visitor::do_mul_mat_vec(ir_variable *result_var,
- ir_variable *a_var,
- ir_variable *b_var)
-{
- int i;
- ir_rvalue *a = get_column(a_var, 0);
- ir_rvalue *b = get_element(b_var, 0, 0);
- ir_assignment *assign;
- ir_expression *expr;
-
- /* first column */
- expr = new(mem_ctx) ir_expression(ir_binop_mul,
- result_var->type,
- a,
- b);
-
- /* following columns */
- for (i = 1; i < a_var->type->matrix_columns; i++) {
- ir_expression *mul_expr;
-
- a = get_column(a_var, i);
- b = get_element(b_var, 0, i);
-
- mul_expr = new(mem_ctx) ir_expression(ir_binop_mul,
- result_var->type,
- a,
- b);
- expr = new(mem_ctx) ir_expression(ir_binop_add,
- result_var->type,
- expr,
- mul_expr);
- }
-
- ir_rvalue *result = new(mem_ctx) ir_dereference_variable(result_var);
- assign = new(mem_ctx) ir_assignment(result,
- expr,
- NULL);
- base_ir->insert_before(assign);
-}
-
-void
-ir_mat_op_to_vec_visitor::do_mul_vec_mat(ir_variable *result_var,
- ir_variable *a_var,
- ir_variable *b_var)
-{
- int i;
-
- for (i = 0; i < b_var->type->matrix_columns; i++) {
- ir_rvalue *a = new(mem_ctx) ir_dereference_variable(a_var);
- ir_rvalue *b = get_column(b_var, i);
- ir_rvalue *result;
- ir_expression *column_expr;
- ir_assignment *column_assign;
-
- result = new(mem_ctx) ir_dereference_variable(result_var);
- result = new(mem_ctx) ir_swizzle(result, i, 0, 0, 0, 1);
-
- column_expr = new(mem_ctx) ir_expression(ir_binop_dot,
- result->type,
- a,
- b);
-
- column_assign = new(mem_ctx) ir_assignment(result,
- column_expr,
- NULL);
- base_ir->insert_before(column_assign);
- }
-}
-
-void
-ir_mat_op_to_vec_visitor::do_mul_mat_scalar(ir_variable *result_var,
- ir_variable *a_var,
- ir_variable *b_var)
-{
- int i;
-
- for (i = 0; i < a_var->type->matrix_columns; i++) {
- ir_rvalue *a = get_column(a_var, i);
- ir_rvalue *b = new(mem_ctx) ir_dereference_variable(b_var);
- ir_rvalue *result = get_column(result_var, i);
- ir_expression *column_expr;
- ir_assignment *column_assign;
-
- column_expr = new(mem_ctx) ir_expression(ir_binop_mul,
- result->type,
- a,
- b);
-
- column_assign = new(mem_ctx) ir_assignment(result,
- column_expr,
- NULL);
- base_ir->insert_before(column_assign);
- }
-}
-
-void
-ir_mat_op_to_vec_visitor::do_equal_mat_mat(ir_variable *result_var,
- ir_variable *a_var,
- ir_variable *b_var,
- bool test_equal)
-{
- /* This essentially implements the following GLSL:
- *
- * bool equal(mat4 a, mat4 b)
- * {
- * return !any(bvec4(a[0] != b[0],
- * a[1] != b[1],
- * a[2] != b[2],
- * a[3] != b[3]);
- * }
- *
- * bool nequal(mat4 a, mat4 b)
- * {
- * return any(bvec4(a[0] != b[0],
- * a[1] != b[1],
- * a[2] != b[2],
- * a[3] != b[3]);
- * }
- */
- const unsigned columns = a_var->type->matrix_columns;
- const glsl_type *const bvec_type =
- glsl_type::get_instance(GLSL_TYPE_BOOL, columns, 1);
-
- ir_variable *const tmp_bvec =
- new(this->mem_ctx) ir_variable(bvec_type, "mat_cmp_bvec",
- ir_var_temporary);
- this->base_ir->insert_before(tmp_bvec);
-
- for (unsigned i = 0; i < columns; i++) {
- ir_dereference *const op0 = get_column(a_var, i);
- ir_dereference *const op1 = get_column(b_var, i);
-
- ir_expression *const cmp =
- new(this->mem_ctx) ir_expression(ir_binop_any_nequal,
- glsl_type::bool_type, op0, op1);
-
- ir_dereference *const lhs =
- new(this->mem_ctx) ir_dereference_variable(tmp_bvec);
-
- ir_assignment *const assign =
- new(this->mem_ctx) ir_assignment(lhs, cmp, NULL, (1U << i));
-
- this->base_ir->insert_before(assign);
- }
-
- ir_rvalue *const val =
- new(this->mem_ctx) ir_dereference_variable(tmp_bvec);
-
- ir_expression *any =
- new(this->mem_ctx) ir_expression(ir_unop_any, glsl_type::bool_type,
- val, NULL);
-
- if (test_equal)
- any = new(this->mem_ctx) ir_expression(ir_unop_logic_not,
- glsl_type::bool_type,
- any, NULL);
-
- ir_rvalue *const result =
- new(this->mem_ctx) ir_dereference_variable(result_var);
-
- ir_assignment *const assign =
- new(mem_ctx) ir_assignment(result, any, NULL);
- base_ir->insert_before(assign);
-}
-
-static bool
-has_matrix_operand(const ir_expression *expr, unsigned &columns)
-{
- for (unsigned i = 0; i < expr->get_num_operands(); i++) {
- if (expr->operands[i]->type->is_matrix()) {
- columns = expr->operands[i]->type->matrix_columns;
- return true;
- }
- }
-
- return false;
-}
-
-
-ir_visitor_status
-ir_mat_op_to_vec_visitor::visit_leave(ir_assignment *orig_assign)
-{
- ir_expression *orig_expr = orig_assign->rhs->as_expression();
- unsigned int i, matrix_columns = 1;
- ir_variable *op_var[2];
-
- if (!orig_expr)
- return visit_continue;
-
- if (!has_matrix_operand(orig_expr, matrix_columns))
- return visit_continue;
-
- assert(orig_expr->get_num_operands() <= 2);
-
- mem_ctx = ralloc_parent(orig_assign);
-
- ir_dereference_variable *lhs_deref =
- orig_assign->lhs->as_dereference_variable();
- assert(lhs_deref);
-
- ir_variable *result_var = lhs_deref->var;
-
- /* Store the expression operands in temps so we can use them
- * multiple times.
- */
- for (i = 0; i < orig_expr->get_num_operands(); i++) {
- ir_assignment *assign;
-
- op_var[i] = new(mem_ctx) ir_variable(orig_expr->operands[i]->type,
- "mat_op_to_vec",
- ir_var_temporary);
- base_ir->insert_before(op_var[i]);
-
- lhs_deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
- assign = new(mem_ctx) ir_assignment(lhs_deref,
- orig_expr->operands[i],
- NULL);
- base_ir->insert_before(assign);
- }
-
- /* OK, time to break down this matrix operation. */
- switch (orig_expr->operation) {
- case ir_unop_neg: {
- const unsigned mask = (1U << result_var->type->vector_elements) - 1;
-
- /* Apply the operation to each column.*/
- for (i = 0; i < matrix_columns; i++) {
- ir_rvalue *op0 = get_column(op_var[0], i);
- ir_dereference *result = get_column(result_var, i);
- ir_expression *column_expr;
- ir_assignment *column_assign;
-
- column_expr = new(mem_ctx) ir_expression(orig_expr->operation,
- result->type,
- op0,
- NULL);
-
- column_assign = new(mem_ctx) ir_assignment(result,
- column_expr,
- NULL,
- mask);
- assert(column_assign->write_mask != 0);
- base_ir->insert_before(column_assign);
- }
- break;
- }
- case ir_binop_add:
- case ir_binop_sub:
- case ir_binop_div:
- case ir_binop_mod: {
- const unsigned mask = (1U << result_var->type->vector_elements) - 1;
-
- /* For most operations, the matrix version is just going
- * column-wise through and applying the operation to each column
- * if available.
- */
- for (i = 0; i < matrix_columns; i++) {
- ir_rvalue *op0 = get_column(op_var[0], i);
- ir_rvalue *op1 = get_column(op_var[1], i);
- ir_dereference *result = get_column(result_var, i);
- ir_expression *column_expr;
- ir_assignment *column_assign;
-
- column_expr = new(mem_ctx) ir_expression(orig_expr->operation,
- result->type,
- op0,
- op1);
-
- column_assign = new(mem_ctx) ir_assignment(result,
- column_expr,
- NULL,
- mask);
- assert(column_assign->write_mask != 0);
- base_ir->insert_before(column_assign);
- }
- break;
- }
- case ir_binop_mul:
- if (op_var[0]->type->is_matrix()) {
- if (op_var[1]->type->is_matrix()) {
- do_mul_mat_mat(result_var, op_var[0], op_var[1]);
- } else if (op_var[1]->type->is_vector()) {
- do_mul_mat_vec(result_var, op_var[0], op_var[1]);
- } else {
- assert(op_var[1]->type->is_scalar());
- do_mul_mat_scalar(result_var, op_var[0], op_var[1]);
- }
- } else {
- assert(op_var[1]->type->is_matrix());
- if (op_var[0]->type->is_vector()) {
- do_mul_vec_mat(result_var, op_var[0], op_var[1]);
- } else {
- assert(op_var[0]->type->is_scalar());
- do_mul_mat_scalar(result_var, op_var[1], op_var[0]);
- }
- }
- break;
-
- case ir_binop_all_equal:
- case ir_binop_any_nequal:
- do_equal_mat_mat(result_var, op_var[1], op_var[0],
- (orig_expr->operation == ir_binop_all_equal));
- break;
-
- default:
- printf("FINISHME: Handle matrix operation for %s\n",
- orig_expr->operator_string());
- abort();
- }
- orig_assign->remove();
- this->made_progress = true;
-
- return visit_continue;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 lower_mat_op_to_vec.cpp
+ *
+ * Breaks matrix operation expressions down to a series of vector operations.
+ *
+ * Generally this is how we have to codegen matrix operations for a
+ * GPU, so this gives us the chance to constant fold operations on a
+ * column or row.
+ */
+
+#include "ir.h"
+#include "ir_expression_flattening.h"
+#include "glsl_types.h"
+
+class ir_mat_op_to_vec_visitor : public ir_hierarchical_visitor {
+public:
+ ir_mat_op_to_vec_visitor()
+ {
+ this->made_progress = false;
+ this->mem_ctx = NULL;
+ }
+
+ ir_visitor_status visit_leave(ir_assignment *);
+
+ ir_dereference *get_column(ir_variable *var, int col);
+ ir_rvalue *get_element(ir_variable *var, int col, int row);
+
+ void do_mul_mat_mat(ir_variable *result_var,
+ ir_variable *a_var, ir_variable *b_var);
+ void do_mul_mat_vec(ir_variable *result_var,
+ ir_variable *a_var, ir_variable *b_var);
+ void do_mul_vec_mat(ir_variable *result_var,
+ ir_variable *a_var, ir_variable *b_var);
+ void do_mul_mat_scalar(ir_variable *result_var,
+ ir_variable *a_var, ir_variable *b_var);
+ void do_equal_mat_mat(ir_variable *result_var, ir_variable *a_var,
+ ir_variable *b_var, bool test_equal);
+
+ void *mem_ctx;
+ bool made_progress;
+};
+
+static bool
+mat_op_to_vec_predicate(ir_instruction *ir)
+{
+ ir_expression *expr = ir->as_expression();
+ unsigned int i;
+
+ if (!expr)
+ return false;
+
+ for (i = 0; i < expr->get_num_operands(); i++) {
+ if (expr->operands[i]->type->is_matrix())
+ return true;
+ }
+
+ return false;
+}
+
+bool
+do_mat_op_to_vec(exec_list *instructions)
+{
+ ir_mat_op_to_vec_visitor v;
+
+ /* Pull out any matrix expression to a separate assignment to a
+ * temp. This will make our handling of the breakdown to
+ * operations on the matrix's vector components much easier.
+ */
+ do_expression_flattening(instructions, mat_op_to_vec_predicate);
+
+ visit_list_elements(&v, instructions);
+
+ return v.made_progress;
+}
+
+ir_rvalue *
+ir_mat_op_to_vec_visitor::get_element(ir_variable *var, int col, int row)
+{
+ ir_dereference *deref;
+
+ deref = new(mem_ctx) ir_dereference_variable(var);
+
+ if (var->type->is_matrix()) {
+ deref = new(mem_ctx) ir_dereference_array(var,
+ new(mem_ctx) ir_constant(col));
+ } else {
+ assert(col == 0);
+ }
+
+ return new(mem_ctx) ir_swizzle(deref, row, 0, 0, 0, 1);
+}
+
+ir_dereference *
+ir_mat_op_to_vec_visitor::get_column(ir_variable *var, int row)
+{
+ ir_dereference *deref;
+
+ if (!var->type->is_matrix()) {
+ deref = new(mem_ctx) ir_dereference_variable(var);
+ } else {
+ deref = new(mem_ctx) ir_dereference_variable(var);
+ deref = new(mem_ctx) ir_dereference_array(deref,
+ new(mem_ctx) ir_constant(row));
+ }
+
+ return deref;
+}
+
+void
+ir_mat_op_to_vec_visitor::do_mul_mat_mat(ir_variable *result_var,
+ ir_variable *a_var,
+ ir_variable *b_var)
+{
+ int b_col, i;
+ ir_assignment *assign;
+ ir_expression *expr;
+
+ for (b_col = 0; b_col < b_var->type->matrix_columns; b_col++) {
+ ir_rvalue *a = get_column(a_var, 0);
+ ir_rvalue *b = get_element(b_var, b_col, 0);
+
+ /* first column */
+ expr = new(mem_ctx) ir_expression(ir_binop_mul,
+ a->type,
+ a,
+ b);
+
+ /* following columns */
+ for (i = 1; i < a_var->type->matrix_columns; i++) {
+ ir_expression *mul_expr;
+
+ a = get_column(a_var, i);
+ b = get_element(b_var, b_col, i);
+
+ mul_expr = new(mem_ctx) ir_expression(ir_binop_mul,
+ a->type,
+ a,
+ b);
+ expr = new(mem_ctx) ir_expression(ir_binop_add,
+ a->type,
+ expr,
+ mul_expr);
+ }
+
+ ir_rvalue *result = get_column(result_var, b_col);
+ assign = new(mem_ctx) ir_assignment(result,
+ expr,
+ NULL);
+ base_ir->insert_before(assign);
+ }
+}
+
+void
+ir_mat_op_to_vec_visitor::do_mul_mat_vec(ir_variable *result_var,
+ ir_variable *a_var,
+ ir_variable *b_var)
+{
+ int i;
+ ir_rvalue *a = get_column(a_var, 0);
+ ir_rvalue *b = get_element(b_var, 0, 0);
+ ir_assignment *assign;
+ ir_expression *expr;
+
+ /* first column */
+ expr = new(mem_ctx) ir_expression(ir_binop_mul,
+ result_var->type,
+ a,
+ b);
+
+ /* following columns */
+ for (i = 1; i < a_var->type->matrix_columns; i++) {
+ ir_expression *mul_expr;
+
+ a = get_column(a_var, i);
+ b = get_element(b_var, 0, i);
+
+ mul_expr = new(mem_ctx) ir_expression(ir_binop_mul,
+ result_var->type,
+ a,
+ b);
+ expr = new(mem_ctx) ir_expression(ir_binop_add,
+ result_var->type,
+ expr,
+ mul_expr);
+ }
+
+ ir_rvalue *result = new(mem_ctx) ir_dereference_variable(result_var);
+ assign = new(mem_ctx) ir_assignment(result,
+ expr,
+ NULL);
+ base_ir->insert_before(assign);
+}
+
+void
+ir_mat_op_to_vec_visitor::do_mul_vec_mat(ir_variable *result_var,
+ ir_variable *a_var,
+ ir_variable *b_var)
+{
+ int i;
+
+ for (i = 0; i < b_var->type->matrix_columns; i++) {
+ ir_rvalue *a = new(mem_ctx) ir_dereference_variable(a_var);
+ ir_rvalue *b = get_column(b_var, i);
+ ir_rvalue *result;
+ ir_expression *column_expr;
+ ir_assignment *column_assign;
+
+ result = new(mem_ctx) ir_dereference_variable(result_var);
+ result = new(mem_ctx) ir_swizzle(result, i, 0, 0, 0, 1);
+
+ column_expr = new(mem_ctx) ir_expression(ir_binop_dot,
+ result->type,
+ a,
+ b);
+
+ column_assign = new(mem_ctx) ir_assignment(result,
+ column_expr,
+ NULL);
+ base_ir->insert_before(column_assign);
+ }
+}
+
+void
+ir_mat_op_to_vec_visitor::do_mul_mat_scalar(ir_variable *result_var,
+ ir_variable *a_var,
+ ir_variable *b_var)
+{
+ int i;
+
+ for (i = 0; i < a_var->type->matrix_columns; i++) {
+ ir_rvalue *a = get_column(a_var, i);
+ ir_rvalue *b = new(mem_ctx) ir_dereference_variable(b_var);
+ ir_rvalue *result = get_column(result_var, i);
+ ir_expression *column_expr;
+ ir_assignment *column_assign;
+
+ column_expr = new(mem_ctx) ir_expression(ir_binop_mul,
+ result->type,
+ a,
+ b);
+
+ column_assign = new(mem_ctx) ir_assignment(result,
+ column_expr,
+ NULL);
+ base_ir->insert_before(column_assign);
+ }
+}
+
+void
+ir_mat_op_to_vec_visitor::do_equal_mat_mat(ir_variable *result_var,
+ ir_variable *a_var,
+ ir_variable *b_var,
+ bool test_equal)
+{
+ /* This essentially implements the following GLSL:
+ *
+ * bool equal(mat4 a, mat4 b)
+ * {
+ * return !any(bvec4(a[0] != b[0],
+ * a[1] != b[1],
+ * a[2] != b[2],
+ * a[3] != b[3]);
+ * }
+ *
+ * bool nequal(mat4 a, mat4 b)
+ * {
+ * return any(bvec4(a[0] != b[0],
+ * a[1] != b[1],
+ * a[2] != b[2],
+ * a[3] != b[3]);
+ * }
+ */
+ const unsigned columns = a_var->type->matrix_columns;
+ const glsl_type *const bvec_type =
+ glsl_type::get_instance(GLSL_TYPE_BOOL, columns, 1);
+
+ ir_variable *const tmp_bvec =
+ new(this->mem_ctx) ir_variable(bvec_type, "mat_cmp_bvec",
+ ir_var_temporary);
+ this->base_ir->insert_before(tmp_bvec);
+
+ for (unsigned i = 0; i < columns; i++) {
+ ir_dereference *const op0 = get_column(a_var, i);
+ ir_dereference *const op1 = get_column(b_var, i);
+
+ ir_expression *const cmp =
+ new(this->mem_ctx) ir_expression(ir_binop_any_nequal,
+ glsl_type::bool_type, op0, op1);
+
+ ir_dereference *const lhs =
+ new(this->mem_ctx) ir_dereference_variable(tmp_bvec);
+
+ ir_assignment *const assign =
+ new(this->mem_ctx) ir_assignment(lhs, cmp, NULL, (1U << i));
+
+ this->base_ir->insert_before(assign);
+ }
+
+ ir_rvalue *const val =
+ new(this->mem_ctx) ir_dereference_variable(tmp_bvec);
+
+ ir_expression *any =
+ new(this->mem_ctx) ir_expression(ir_unop_any, glsl_type::bool_type,
+ val, NULL);
+
+ if (test_equal)
+ any = new(this->mem_ctx) ir_expression(ir_unop_logic_not,
+ glsl_type::bool_type,
+ any, NULL);
+
+ ir_rvalue *const result =
+ new(this->mem_ctx) ir_dereference_variable(result_var);
+
+ ir_assignment *const assign =
+ new(mem_ctx) ir_assignment(result, any, NULL);
+ base_ir->insert_before(assign);
+}
+
+static bool
+has_matrix_operand(const ir_expression *expr, unsigned &columns)
+{
+ for (unsigned i = 0; i < expr->get_num_operands(); i++) {
+ if (expr->operands[i]->type->is_matrix()) {
+ columns = expr->operands[i]->type->matrix_columns;
+ return true;
+ }
+ }
+
+ return false;
+}
+
+
+ir_visitor_status
+ir_mat_op_to_vec_visitor::visit_leave(ir_assignment *orig_assign)
+{
+ ir_expression *orig_expr = orig_assign->rhs->as_expression();
+ unsigned int i, matrix_columns = 1;
+ ir_variable *op_var[2];
+
+ if (!orig_expr)
+ return visit_continue;
+
+ if (!has_matrix_operand(orig_expr, matrix_columns))
+ return visit_continue;
+
+ assert(orig_expr->get_num_operands() <= 2);
+
+ mem_ctx = ralloc_parent(orig_assign);
+
+ ir_dereference_variable *lhs_deref =
+ orig_assign->lhs->as_dereference_variable();
+ assert(lhs_deref);
+
+ ir_variable *result_var = lhs_deref->var;
+
+ /* Store the expression operands in temps so we can use them
+ * multiple times.
+ */
+ for (i = 0; i < orig_expr->get_num_operands(); i++) {
+ ir_assignment *assign;
+
+ op_var[i] = new(mem_ctx) ir_variable(orig_expr->operands[i]->type,
+ "mat_op_to_vec",
+ ir_var_temporary);
+ base_ir->insert_before(op_var[i]);
+
+ lhs_deref = new(mem_ctx) ir_dereference_variable(op_var[i]);
+ assign = new(mem_ctx) ir_assignment(lhs_deref,
+ orig_expr->operands[i],
+ NULL);
+ base_ir->insert_before(assign);
+ }
+
+ /* OK, time to break down this matrix operation. */
+ switch (orig_expr->operation) {
+ case ir_unop_neg: {
+ const unsigned mask = (1U << result_var->type->vector_elements) - 1;
+
+ /* Apply the operation to each column.*/
+ for (i = 0; i < matrix_columns; i++) {
+ ir_rvalue *op0 = get_column(op_var[0], i);
+ ir_dereference *result = get_column(result_var, i);
+ ir_expression *column_expr;
+ ir_assignment *column_assign;
+
+ column_expr = new(mem_ctx) ir_expression(orig_expr->operation,
+ result->type,
+ op0,
+ NULL);
+
+ column_assign = new(mem_ctx) ir_assignment(result,
+ column_expr,
+ NULL,
+ mask);
+ assert(column_assign->write_mask != 0);
+ base_ir->insert_before(column_assign);
+ }
+ break;
+ }
+ case ir_binop_add:
+ case ir_binop_sub:
+ case ir_binop_div:
+ case ir_binop_mod: {
+ const unsigned mask = (1U << result_var->type->vector_elements) - 1;
+
+ /* For most operations, the matrix version is just going
+ * column-wise through and applying the operation to each column
+ * if available.
+ */
+ for (i = 0; i < matrix_columns; i++) {
+ ir_rvalue *op0 = get_column(op_var[0], i);
+ ir_rvalue *op1 = get_column(op_var[1], i);
+ ir_dereference *result = get_column(result_var, i);
+ ir_expression *column_expr;
+ ir_assignment *column_assign;
+
+ column_expr = new(mem_ctx) ir_expression(orig_expr->operation,
+ result->type,
+ op0,
+ op1);
+
+ column_assign = new(mem_ctx) ir_assignment(result,
+ column_expr,
+ NULL,
+ mask);
+ assert(column_assign->write_mask != 0);
+ base_ir->insert_before(column_assign);
+ }
+ break;
+ }
+ case ir_binop_mul:
+ if (op_var[0]->type->is_matrix()) {
+ if (op_var[1]->type->is_matrix()) {
+ do_mul_mat_mat(result_var, op_var[0], op_var[1]);
+ } else if (op_var[1]->type->is_vector()) {
+ do_mul_mat_vec(result_var, op_var[0], op_var[1]);
+ } else {
+ assert(op_var[1]->type->is_scalar());
+ do_mul_mat_scalar(result_var, op_var[0], op_var[1]);
+ }
+ } else {
+ assert(op_var[1]->type->is_matrix());
+ if (op_var[0]->type->is_vector()) {
+ do_mul_vec_mat(result_var, op_var[0], op_var[1]);
+ } else {
+ assert(op_var[0]->type->is_scalar());
+ do_mul_mat_scalar(result_var, op_var[1], op_var[0]);
+ }
+ }
+ break;
+
+ case ir_binop_all_equal:
+ case ir_binop_any_nequal:
+ do_equal_mat_mat(result_var, op_var[1], op_var[0],
+ (orig_expr->operation == ir_binop_all_equal));
+ break;
+
+ default:
+ printf("FINISHME: Handle matrix operation for %s\n",
+ orig_expr->operator_string());
+ abort();
+ }
+ orig_assign->remove();
+ this->made_progress = true;
+
+ return visit_continue;
+}
diff --git a/mesalib/src/glsl/main.cpp b/mesalib/src/glsl/main.cpp
index 096da93dc..873a4fa16 100644
--- a/mesalib/src/glsl/main.cpp
+++ b/mesalib/src/glsl/main.cpp
@@ -1,334 +1,345 @@
-/*
- * Copyright © 2008, 2009 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-#include <getopt.h>
-
-#include "ast.h"
-#include "glsl_parser_extras.h"
-#include "glsl_parser.h"
-#include "ir_optimization.h"
-#include "ir_print_visitor.h"
-#include "program.h"
-#include "loop_analysis.h"
-
-extern "C" struct gl_shader *
-_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type);
-
-extern "C" void
-_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
- struct gl_shader *sh);
-
-/* Copied from shader_api.c for the stand-alone compiler.
- */
-void
-_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
- struct gl_shader *sh)
-{
- *ptr = sh;
-}
-
-struct gl_shader *
-_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)
-{
- struct gl_shader *shader;
-
- (void) ctx;
-
- assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);
- shader = rzalloc(NULL, struct gl_shader);
- if (shader) {
- shader->Type = type;
- shader->Name = name;
- shader->RefCount = 1;
- }
- return shader;
-}
-
-static void
-initialize_context(struct gl_context *ctx, gl_api api)
-{
- memset(ctx, 0, sizeof(*ctx));
-
- ctx->API = api;
-
- ctx->Extensions.ARB_ES2_compatibility = GL_TRUE;
- ctx->Extensions.ARB_draw_buffers = GL_TRUE;
- ctx->Extensions.ARB_draw_instanced = GL_TRUE;
- ctx->Extensions.ARB_fragment_coord_conventions = GL_TRUE;
- ctx->Extensions.EXT_texture_array = GL_TRUE;
- ctx->Extensions.NV_texture_rectangle = GL_TRUE;
-
- /* GLSL 1.30 isn't fully supported, but we need to advertise 1.30 so that
- * the built-in functions for 1.30 can be built.
- */
- ctx->Const.GLSLVersion = 130;
-
- /* 1.10 minimums. */
- ctx->Const.MaxLights = 8;
- ctx->Const.MaxClipPlanes = 8;
- ctx->Const.MaxTextureUnits = 2;
-
- /* More than the 1.10 minimum to appease parser tests taken from
- * apps that (hopefully) already checked the number of coords.
- */
- ctx->Const.MaxTextureCoordUnits = 4;
-
- ctx->Const.VertexProgram.MaxAttribs = 16;
- ctx->Const.VertexProgram.MaxUniformComponents = 512;
- ctx->Const.MaxVarying = 8;
- ctx->Const.MaxVertexTextureImageUnits = 0;
- ctx->Const.MaxCombinedTextureImageUnits = 2;
- ctx->Const.MaxTextureImageUnits = 2;
- ctx->Const.FragmentProgram.MaxUniformComponents = 64;
-
- ctx->Const.MaxDrawBuffers = 2;
-
- ctx->Driver.NewShader = _mesa_new_shader;
-}
-
-/* Returned string will have 'ctx' as its ralloc owner. */
-static char *
-load_text_file(void *ctx, const char *file_name)
-{
- char *text = NULL;
- size_t size;
- size_t total_read = 0;
- FILE *fp = fopen(file_name, "rb");
-
- if (!fp) {
- return NULL;
- }
-
- fseek(fp, 0L, SEEK_END);
- size = ftell(fp);
- fseek(fp, 0L, SEEK_SET);
-
- text = (char *) ralloc_size(ctx, size + 1);
- if (text != NULL) {
- do {
- size_t bytes = fread(text + total_read,
- 1, size - total_read, fp);
- if (bytes < size - total_read) {
- free(text);
- text = NULL;
- break;
- }
-
- if (bytes == 0) {
- break;
- }
-
- total_read += bytes;
- } while (total_read < size);
-
- text[total_read] = '\0';
- }
-
- fclose(fp);
-
- return text;
-}
-
-int glsl_es = 0;
-int dump_ast = 0;
-int dump_hir = 0;
-int dump_lir = 0;
-int do_link = 0;
-
-const struct option compiler_opts[] = {
- { "glsl-es", 0, &glsl_es, 1 },
- { "dump-ast", 0, &dump_ast, 1 },
- { "dump-hir", 0, &dump_hir, 1 },
- { "dump-lir", 0, &dump_lir, 1 },
- { "link", 0, &do_link, 1 },
- { NULL, 0, NULL, 0 }
-};
-
-/**
- * \brief Print proper usage and exit with failure.
- */
-void
-usage_fail(const char *name)
-{
-
- const char *header =
- "usage: %s [options] <file.vert | file.geom | file.frag>\n"
- "\n"
- "Possible options are:\n";
- printf(header, name, name);
- for (const struct option *o = compiler_opts; o->name != 0; ++o) {
- printf(" --%s\n", o->name);
- }
- exit(EXIT_FAILURE);
-}
-
-
-void
-compile_shader(struct gl_context *ctx, struct gl_shader *shader)
-{
- struct _mesa_glsl_parse_state *state =
- new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
-
- const char *source = shader->Source;
- state->error = preprocess(state, &source, &state->info_log,
- state->extensions, ctx->API) != 0;
-
- if (!state->error) {
- _mesa_glsl_lexer_ctor(state, source);
- _mesa_glsl_parse(state);
- _mesa_glsl_lexer_dtor(state);
- }
-
- if (dump_ast) {
- foreach_list_const(n, &state->translation_unit) {
- ast_node *ast = exec_node_data(ast_node, n, link);
- ast->print();
- }
- printf("\n\n");
- }
-
- shader->ir = new(shader) exec_list;
- if (!state->error && !state->translation_unit.is_empty())
- _mesa_ast_to_hir(shader->ir, state);
-
- /* Print out the unoptimized IR. */
- if (!state->error && dump_hir) {
- validate_ir_tree(shader->ir);
- _mesa_print_ir(shader->ir, state);
- }
-
- /* Optimization passes */
- if (!state->error && !shader->ir->is_empty()) {
- bool progress;
- do {
- progress = do_common_optimization(shader->ir, false, 32);
- } while (progress);
-
- validate_ir_tree(shader->ir);
- }
-
-
- /* Print out the resulting IR */
- if (!state->error && dump_lir) {
- _mesa_print_ir(shader->ir, state);
- }
-
- shader->symbols = state->symbols;
- shader->CompileStatus = !state->error;
- shader->Version = state->language_version;
- memcpy(shader->builtins_to_link, state->builtins_to_link,
- sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
- shader->num_builtins_to_link = state->num_builtins_to_link;
-
- if (shader->InfoLog)
- ralloc_free(shader->InfoLog);
-
- shader->InfoLog = state->info_log;
-
- /* Retain any live IR, but trash the rest. */
- reparent_ir(shader->ir, shader);
-
- ralloc_free(state);
-
- return;
-}
-
-int
-main(int argc, char **argv)
-{
- int status = EXIT_SUCCESS;
- struct gl_context local_ctx;
- struct gl_context *ctx = &local_ctx;
-
- int c;
- int idx = 0;
- while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
- /* empty */ ;
-
-
- if (argc <= optind)
- usage_fail(argv[0]);
-
- initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);
-
- struct gl_shader_program *whole_program;
-
- whole_program = rzalloc (NULL, struct gl_shader_program);
- assert(whole_program != NULL);
-
- for (/* empty */; argc > optind; optind++) {
- whole_program->Shaders =
- reralloc(whole_program, whole_program->Shaders,
- struct gl_shader *, whole_program->NumShaders + 1);
- assert(whole_program->Shaders != NULL);
-
- struct gl_shader *shader = rzalloc(whole_program, gl_shader);
-
- whole_program->Shaders[whole_program->NumShaders] = shader;
- whole_program->NumShaders++;
-
- const unsigned len = strlen(argv[optind]);
- if (len < 6)
- usage_fail(argv[0]);
-
- const char *const ext = & argv[optind][len - 5];
- if (strncmp(".vert", ext, 5) == 0)
- shader->Type = GL_VERTEX_SHADER;
- else if (strncmp(".geom", ext, 5) == 0)
- shader->Type = GL_GEOMETRY_SHADER;
- else if (strncmp(".frag", ext, 5) == 0)
- shader->Type = GL_FRAGMENT_SHADER;
- else
- usage_fail(argv[0]);
-
- shader->Source = load_text_file(whole_program, argv[optind]);
- if (shader->Source == NULL) {
- printf("File \"%s\" does not exist.\n", argv[optind]);
- exit(EXIT_FAILURE);
- }
-
- compile_shader(ctx, shader);
-
- if (!shader->CompileStatus) {
- printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
- status = EXIT_FAILURE;
- break;
- }
- }
-
- if ((status == EXIT_SUCCESS) && do_link) {
- link_shaders(ctx, whole_program);
- status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
-
- if (strlen(whole_program->InfoLog) > 0)
- printf("Info log for linking:\n%s\n", whole_program->InfoLog);
- }
-
- for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)
- ralloc_free(whole_program->_LinkedShaders[i]);
-
- ralloc_free(whole_program);
- _mesa_glsl_release_types();
- _mesa_glsl_release_functions();
-
- return status;
-}
+/*
+ * Copyright © 2008, 2009 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+#include <io.h>
+
+#ifdef _MSC_VER
+#define __STDC__ 1
+#include <getopt.h>
+#define open _open
+#define read _read
+#define fstat _fstat
+#define stat _stat
+#define close _close
+#define O_RDONLY _O_RDONLY
+#endif
+
+#include "ast.h"
+#include "glsl_parser_extras.h"
+#include "glsl_parser.h"
+#include "ir_optimization.h"
+#include "ir_print_visitor.h"
+#include "program.h"
+#include "loop_analysis.h"
+
+extern "C" struct gl_shader *
+_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type);
+
+extern "C" void
+_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
+ struct gl_shader *sh);
+
+/* Copied from shader_api.c for the stand-alone compiler.
+ */
+void
+_mesa_reference_shader(struct gl_context *ctx, struct gl_shader **ptr,
+ struct gl_shader *sh)
+{
+ *ptr = sh;
+}
+
+struct gl_shader *
+_mesa_new_shader(struct gl_context *ctx, GLuint name, GLenum type)
+{
+ struct gl_shader *shader;
+
+ (void) ctx;
+
+ assert(type == GL_FRAGMENT_SHADER || type == GL_VERTEX_SHADER);
+ shader = rzalloc(NULL, struct gl_shader);
+ if (shader) {
+ shader->Type = type;
+ shader->Name = name;
+ shader->RefCount = 1;
+ }
+ return shader;
+}
+
+static void
+initialize_context(struct gl_context *ctx, gl_api api)
+{
+ memset(ctx, 0, sizeof(*ctx));
+
+ ctx->API = api;
+
+ ctx->Extensions.ARB_ES2_compatibility = GL_TRUE;
+ ctx->Extensions.ARB_draw_buffers = GL_TRUE;
+ ctx->Extensions.ARB_draw_instanced = GL_TRUE;
+ ctx->Extensions.ARB_fragment_coord_conventions = GL_TRUE;
+ ctx->Extensions.EXT_texture_array = GL_TRUE;
+ ctx->Extensions.NV_texture_rectangle = GL_TRUE;
+
+ /* GLSL 1.30 isn't fully supported, but we need to advertise 1.30 so that
+ * the built-in functions for 1.30 can be built.
+ */
+ ctx->Const.GLSLVersion = 130;
+
+ /* 1.10 minimums. */
+ ctx->Const.MaxLights = 8;
+ ctx->Const.MaxClipPlanes = 8;
+ ctx->Const.MaxTextureUnits = 2;
+
+ /* More than the 1.10 minimum to appease parser tests taken from
+ * apps that (hopefully) already checked the number of coords.
+ */
+ ctx->Const.MaxTextureCoordUnits = 4;
+
+ ctx->Const.VertexProgram.MaxAttribs = 16;
+ ctx->Const.VertexProgram.MaxUniformComponents = 512;
+ ctx->Const.MaxVarying = 8;
+ ctx->Const.MaxVertexTextureImageUnits = 0;
+ ctx->Const.MaxCombinedTextureImageUnits = 2;
+ ctx->Const.MaxTextureImageUnits = 2;
+ ctx->Const.FragmentProgram.MaxUniformComponents = 64;
+
+ ctx->Const.MaxDrawBuffers = 2;
+
+ ctx->Driver.NewShader = _mesa_new_shader;
+}
+
+/* Returned string will have 'ctx' as its ralloc owner. */
+static char *
+load_text_file(void *ctx, const char *file_name)
+{
+ char *text = NULL;
+ size_t size;
+ size_t total_read = 0;
+ FILE *fp = fopen(file_name, "rb");
+
+ if (!fp) {
+ return NULL;
+ }
+
+ fseek(fp, 0L, SEEK_END);
+ size = ftell(fp);
+ fseek(fp, 0L, SEEK_SET);
+
+ text = (char *) ralloc_size(ctx, size + 1);
+ if (text != NULL) {
+ do {
+ size_t bytes = fread(text + total_read,
+ 1, size - total_read, fp);
+ if (bytes < size - total_read) {
+ free(text);
+ text = NULL;
+ break;
+ }
+
+ if (bytes == 0) {
+ break;
+ }
+
+ total_read += bytes;
+ } while (total_read < size);
+
+ text[total_read] = '\0';
+ }
+
+ fclose(fp);
+
+ return text;
+}
+
+int glsl_es = 0;
+int dump_ast = 0;
+int dump_hir = 0;
+int dump_lir = 0;
+int do_link = 0;
+
+const struct option compiler_opts[] = {
+ { "glsl-es", 0, &glsl_es, 1 },
+ { "dump-ast", 0, &dump_ast, 1 },
+ { "dump-hir", 0, &dump_hir, 1 },
+ { "dump-lir", 0, &dump_lir, 1 },
+ { "link", 0, &do_link, 1 },
+ { NULL, 0, NULL, 0 }
+};
+
+/**
+ * \brief Print proper usage and exit with failure.
+ */
+void
+usage_fail(const char *name)
+{
+
+ const char *header =
+ "usage: %s [options] <file.vert | file.geom | file.frag>\n"
+ "\n"
+ "Possible options are:\n";
+ printf(header, name, name);
+ for (const struct option *o = compiler_opts; o->name != 0; ++o) {
+ printf(" --%s\n", o->name);
+ }
+ exit(EXIT_FAILURE);
+}
+
+
+void
+compile_shader(struct gl_context *ctx, struct gl_shader *shader)
+{
+ struct _mesa_glsl_parse_state *state =
+ new(shader) _mesa_glsl_parse_state(ctx, shader->Type, shader);
+
+ const char *source = shader->Source;
+ state->error = preprocess(state, &source, &state->info_log,
+ state->extensions, ctx->API) != 0;
+
+ if (!state->error) {
+ _mesa_glsl_lexer_ctor(state, source);
+ _mesa_glsl_parse(state);
+ _mesa_glsl_lexer_dtor(state);
+ }
+
+ if (dump_ast) {
+ foreach_list_const(n, &state->translation_unit) {
+ ast_node *ast = exec_node_data(ast_node, n, link);
+ ast->print();
+ }
+ printf("\n\n");
+ }
+
+ shader->ir = new(shader) exec_list;
+ if (!state->error && !state->translation_unit.is_empty())
+ _mesa_ast_to_hir(shader->ir, state);
+
+ /* Print out the unoptimized IR. */
+ if (!state->error && dump_hir) {
+ validate_ir_tree(shader->ir);
+ _mesa_print_ir(shader->ir, state);
+ }
+
+ /* Optimization passes */
+ if (!state->error && !shader->ir->is_empty()) {
+ bool progress;
+ do {
+ progress = do_common_optimization(shader->ir, false, 32);
+ } while (progress);
+
+ validate_ir_tree(shader->ir);
+ }
+
+
+ /* Print out the resulting IR */
+ if (!state->error && dump_lir) {
+ _mesa_print_ir(shader->ir, state);
+ }
+
+ shader->symbols = state->symbols;
+ shader->CompileStatus = !state->error;
+ shader->Version = state->language_version;
+ memcpy(shader->builtins_to_link, state->builtins_to_link,
+ sizeof(shader->builtins_to_link[0]) * state->num_builtins_to_link);
+ shader->num_builtins_to_link = state->num_builtins_to_link;
+
+ if (shader->InfoLog)
+ ralloc_free(shader->InfoLog);
+
+ shader->InfoLog = state->info_log;
+
+ /* Retain any live IR, but trash the rest. */
+ reparent_ir(shader->ir, shader);
+
+ ralloc_free(state);
+
+ return;
+}
+
+int
+main(int argc, char **argv)
+{
+ int status = EXIT_SUCCESS;
+ struct gl_context local_ctx;
+ struct gl_context *ctx = &local_ctx;
+
+ int c;
+ int idx = 0;
+ while ((c = getopt_long(argc, argv, "", compiler_opts, &idx)) != -1)
+ /* empty */ ;
+
+
+ if (argc <= optind)
+ usage_fail(argv[0]);
+
+ initialize_context(ctx, (glsl_es) ? API_OPENGLES2 : API_OPENGL);
+
+ struct gl_shader_program *whole_program;
+
+ whole_program = rzalloc (NULL, struct gl_shader_program);
+ assert(whole_program != NULL);
+
+ for (/* empty */; argc > optind; optind++) {
+ whole_program->Shaders =
+ reralloc(whole_program, whole_program->Shaders,
+ struct gl_shader *, whole_program->NumShaders + 1);
+ assert(whole_program->Shaders != NULL);
+
+ struct gl_shader *shader = rzalloc(whole_program, gl_shader);
+
+ whole_program->Shaders[whole_program->NumShaders] = shader;
+ whole_program->NumShaders++;
+
+ const unsigned len = strlen(argv[optind]);
+ if (len < 6)
+ usage_fail(argv[0]);
+
+ const char *const ext = & argv[optind][len - 5];
+ if (strncmp(".vert", ext, 5) == 0)
+ shader->Type = GL_VERTEX_SHADER;
+ else if (strncmp(".geom", ext, 5) == 0)
+ shader->Type = GL_GEOMETRY_SHADER;
+ else if (strncmp(".frag", ext, 5) == 0)
+ shader->Type = GL_FRAGMENT_SHADER;
+ else
+ usage_fail(argv[0]);
+
+ shader->Source = load_text_file(whole_program, argv[optind]);
+ if (shader->Source == NULL) {
+ printf("File \"%s\" does not exist.\n", argv[optind]);
+ exit(EXIT_FAILURE);
+ }
+
+ compile_shader(ctx, shader);
+
+ if (!shader->CompileStatus) {
+ printf("Info log for %s:\n%s\n", argv[optind], shader->InfoLog);
+ status = EXIT_FAILURE;
+ break;
+ }
+ }
+
+ if ((status == EXIT_SUCCESS) && do_link) {
+ link_shaders(ctx, whole_program);
+ status = (whole_program->LinkStatus) ? EXIT_SUCCESS : EXIT_FAILURE;
+
+ if (strlen(whole_program->InfoLog) > 0)
+ printf("Info log for linking:\n%s\n", whole_program->InfoLog);
+ }
+
+ for (unsigned i = 0; i < MESA_SHADER_TYPES; i++)
+ ralloc_free(whole_program->_LinkedShaders[i]);
+
+ ralloc_free(whole_program);
+ _mesa_glsl_release_types();
+ _mesa_glsl_release_functions();
+
+ return status;
+}
diff --git a/mesalib/src/glsl/opt_constant_propagation.cpp b/mesalib/src/glsl/opt_constant_propagation.cpp
index 4425f4211..55c271200 100644
--- a/mesalib/src/glsl/opt_constant_propagation.cpp
+++ b/mesalib/src/glsl/opt_constant_propagation.cpp
@@ -1,434 +1,434 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * constant of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, constant, 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 constantright notice and this permission notice (including the next
- * paragraph) 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
- * THE AUTHORS OR CONSTANTRIGHT HOLDERS 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 opt_constant_propagation.cpp
- *
- * Tracks assignments of constants to channels of variables, and
- * usage of those constant channels with direct usage of the constants.
- *
- * This can lead to constant folding and algebraic optimizations in
- * those later expressions, while causing no increase in instruction
- * count (due to constants being generally free to load from a
- * constant push buffer or as instruction immediate values) and
- * possibly reducing register pressure.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_rvalue_visitor.h"
-#include "ir_basic_block.h"
-#include "ir_optimization.h"
-#include "glsl_types.h"
-
-class acp_entry : public exec_node
-{
-public:
- acp_entry(ir_variable *var, unsigned write_mask, ir_constant *constant)
- {
- assert(var);
- assert(constant);
- this->var = var;
- this->write_mask = write_mask;
- this->constant = constant;
- }
-
- ir_variable *var;
- ir_constant *constant;
- unsigned write_mask;
-};
-
-
-class kill_entry : public exec_node
-{
-public:
- kill_entry(ir_variable *var, unsigned write_mask)
- {
- assert(var);
- this->var = var;
- this->write_mask = write_mask;
- }
-
- ir_variable *var;
- unsigned write_mask;
-};
-
-class ir_constant_propagation_visitor : public ir_rvalue_visitor {
-public:
- ir_constant_propagation_visitor()
- {
- progress = false;
- mem_ctx = ralloc_context(0);
- this->acp = new(mem_ctx) exec_list;
- this->kills = new(mem_ctx) exec_list;
- }
- ~ir_constant_propagation_visitor()
- {
- ralloc_free(mem_ctx);
- }
-
- virtual ir_visitor_status visit_enter(class ir_loop *);
- virtual ir_visitor_status visit_enter(class ir_function_signature *);
- virtual ir_visitor_status visit_enter(class ir_function *);
- virtual ir_visitor_status visit_leave(class ir_assignment *);
- virtual ir_visitor_status visit_enter(class ir_call *);
- virtual ir_visitor_status visit_enter(class ir_if *);
-
- void add_constant(ir_assignment *ir);
- void kill(ir_variable *ir, unsigned write_mask);
- void handle_if_block(exec_list *instructions);
- void handle_rvalue(ir_rvalue **rvalue);
-
- /** List of acp_entry: The available constants to propagate */
- exec_list *acp;
-
- /**
- * List of kill_entry: The masks of variables whose values were
- * killed in this block.
- */
- exec_list *kills;
-
- bool progress;
-
- bool killed_all;
-
- void *mem_ctx;
-};
-
-
-void
-ir_constant_propagation_visitor::handle_rvalue(ir_rvalue **rvalue)
-{
- if (this->in_assignee || !*rvalue)
- return;
-
- const glsl_type *type = (*rvalue)->type;
- if (!type->is_scalar() && !type->is_vector())
- return;
-
- ir_swizzle *swiz = NULL;
- ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
- if (!deref) {
- swiz = (*rvalue)->as_swizzle();
- if (!swiz)
- return;
-
- deref = swiz->val->as_dereference_variable();
- if (!deref)
- return;
- }
-
- ir_constant_data data;
- memset(&data, 0, sizeof(data));
-
- for (unsigned int i = 0; i < type->components(); i++) {
- int channel;
- acp_entry *found = NULL;
-
- if (swiz) {
- switch (i) {
- case 0: channel = swiz->mask.x; break;
- case 1: channel = swiz->mask.y; break;
- case 2: channel = swiz->mask.z; break;
- case 3: channel = swiz->mask.w; break;
- default: assert(!"shouldn't be reached"); channel = 0; break;
- }
- } else {
- channel = i;
- }
-
- foreach_iter(exec_list_iterator, iter, *this->acp) {
- acp_entry *entry = (acp_entry *)iter.get();
- if (entry->var == deref->var && entry->write_mask & (1 << channel)) {
- found = entry;
- break;
- }
- }
-
- if (!found)
- return;
-
- int rhs_channel = 0;
- for (int j = 0; j < 4; j++) {
- if (j == channel)
- break;
- if (found->write_mask & (1 << j))
- rhs_channel++;
- }
-
- switch (type->base_type) {
- case GLSL_TYPE_FLOAT:
- data.f[i] = found->constant->value.f[rhs_channel];
- break;
- case GLSL_TYPE_INT:
- data.i[i] = found->constant->value.i[rhs_channel];
- break;
- case GLSL_TYPE_UINT:
- data.u[i] = found->constant->value.u[rhs_channel];
- break;
- case GLSL_TYPE_BOOL:
- data.b[i] = found->constant->value.b[rhs_channel];
- break;
- default:
- assert(!"not reached");
- break;
- }
- }
-
- *rvalue = new(ralloc_parent(deref)) ir_constant(type, &data);
- this->progress = true;
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_enter(ir_function_signature *ir)
-{
- /* Treat entry into a function signature as a completely separate
- * block. Any instructions at global scope will be shuffled into
- * main() at link time, so they're irrelevant to us.
- */
- exec_list *orig_acp = this->acp;
- exec_list *orig_kills = this->kills;
- bool orig_killed_all = this->killed_all;
-
- this->acp = new(mem_ctx) exec_list;
- this->kills = new(mem_ctx) exec_list;
- this->killed_all = false;
-
- visit_list_elements(this, &ir->body);
-
- this->kills = orig_kills;
- this->acp = orig_acp;
- this->killed_all = orig_killed_all;
-
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_leave(ir_assignment *ir)
-{
- if (this->in_assignee)
- return visit_continue;
-
- kill(ir->lhs->variable_referenced(), ir->write_mask);
-
- add_constant(ir);
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_enter(ir_function *ir)
-{
- (void) ir;
- return visit_continue;
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_enter(ir_call *ir)
-{
- /* Do constant propagation on call parameters, but skip any out params */
- exec_list_iterator sig_param_iter = ir->get_callee()->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, ir->actual_parameters) {
- ir_variable *sig_param = (ir_variable *)sig_param_iter.get();
- ir_rvalue *param = (ir_rvalue *)iter.get();
- if (sig_param->mode != ir_var_out && sig_param->mode != ir_var_inout) {
- ir_rvalue *new_param = param;
- handle_rvalue(&new_param);
- if (new_param != param)
- param->replace_with(new_param);
- else
- param->accept(this);
- }
- sig_param_iter.next();
- }
-
- /* Since we're unlinked, we don't (necssarily) know the side effects of
- * this call. So kill all copies.
- */
- acp->make_empty();
- this->killed_all = true;
-
- return visit_continue_with_parent;
-}
-
-void
-ir_constant_propagation_visitor::handle_if_block(exec_list *instructions)
-{
- exec_list *orig_acp = this->acp;
- exec_list *orig_kills = this->kills;
- bool orig_killed_all = this->killed_all;
-
- this->acp = new(mem_ctx) exec_list;
- this->kills = new(mem_ctx) exec_list;
- this->killed_all = false;
-
- /* Populate the initial acp with a constant of the original */
- foreach_iter(exec_list_iterator, iter, *orig_acp) {
- acp_entry *a = (acp_entry *)iter.get();
- this->acp->push_tail(new(this->mem_ctx) acp_entry(a->var, a->write_mask,
- a->constant));
- }
-
- visit_list_elements(this, instructions);
-
- if (this->killed_all) {
- orig_acp->make_empty();
- }
-
- exec_list *new_kills = this->kills;
- this->kills = orig_kills;
- this->acp = orig_acp;
- this->killed_all = this->killed_all || orig_killed_all;
-
- foreach_iter(exec_list_iterator, iter, *new_kills) {
- kill_entry *k = (kill_entry *)iter.get();
- kill(k->var, k->write_mask);
- }
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_enter(ir_if *ir)
-{
- ir->condition->accept(this);
- handle_rvalue(&ir->condition);
-
- handle_if_block(&ir->then_instructions);
- handle_if_block(&ir->else_instructions);
-
- /* handle_if_block() already descended into the children. */
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_constant_propagation_visitor::visit_enter(ir_loop *ir)
-{
- exec_list *orig_acp = this->acp;
- exec_list *orig_kills = this->kills;
- bool orig_killed_all = this->killed_all;
-
- /* FINISHME: For now, the initial acp for loops is totally empty.
- * We could go through once, then go through again with the acp
- * cloned minus the killed entries after the first run through.
- */
- this->acp = new(mem_ctx) exec_list;
- this->kills = new(mem_ctx) exec_list;
- this->killed_all = false;
-
- visit_list_elements(this, &ir->body_instructions);
-
- if (this->killed_all) {
- orig_acp->make_empty();
- }
-
- exec_list *new_kills = this->kills;
- this->kills = orig_kills;
- this->acp = orig_acp;
- this->killed_all = this->killed_all || orig_killed_all;
-
- foreach_iter(exec_list_iterator, iter, *new_kills) {
- kill_entry *k = (kill_entry *)iter.get();
- kill(k->var, k->write_mask);
- }
-
- /* already descended into the children. */
- return visit_continue_with_parent;
-}
-
-void
-ir_constant_propagation_visitor::kill(ir_variable *var, unsigned write_mask)
-{
- assert(var != NULL);
-
- /* We don't track non-vectors. */
- if (!var->type->is_vector() && !var->type->is_scalar())
- return;
-
- /* Remove any entries currently in the ACP for this kill. */
- foreach_iter(exec_list_iterator, iter, *this->acp) {
- acp_entry *entry = (acp_entry *)iter.get();
-
- if (entry->var == var) {
- entry->write_mask &= ~write_mask;
- if (entry->write_mask == 0)
- entry->remove();
- }
- }
-
- /* Add this writemask of the variable to the list of killed
- * variables in this block.
- */
- foreach_iter(exec_list_iterator, iter, *this->kills) {
- kill_entry *entry = (kill_entry *)iter.get();
-
- if (entry->var == var) {
- entry->write_mask |= write_mask;
- return;
- }
- }
- /* Not already in the list. Make new entry. */
- this->kills->push_tail(new(this->mem_ctx) kill_entry(var, write_mask));
-}
-
-/**
- * Adds an entry to the available constant list if it's a plain assignment
- * of a variable to a variable.
- */
-void
-ir_constant_propagation_visitor::add_constant(ir_assignment *ir)
-{
- acp_entry *entry;
-
- if (ir->condition)
- return;
-
- if (!ir->write_mask)
- return;
-
- ir_dereference_variable *deref = ir->lhs->as_dereference_variable();
- ir_constant *constant = ir->rhs->as_constant();
-
- if (!deref || !constant)
- return;
-
- /* Only do constant propagation on vectors. Constant matrices,
- * arrays, or structures would require more work elsewhere.
- */
- if (!deref->var->type->is_vector() && !deref->var->type->is_scalar())
- return;
-
- entry = new(this->mem_ctx) acp_entry(deref->var, ir->write_mask, constant);
- this->acp->push_tail(entry);
-}
-
-/**
- * Does a constant propagation pass on the code present in the instruction stream.
- */
-bool
-do_constant_propagation(exec_list *instructions)
-{
- ir_constant_propagation_visitor v;
-
- visit_list_elements(&v, instructions);
-
- return v.progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * constant of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, constant, 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 constantright notice and this permission notice (including the next
+ * paragraph) 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
+ * THE AUTHORS OR CONSTANTRIGHT HOLDERS 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 opt_constant_propagation.cpp
+ *
+ * Tracks assignments of constants to channels of variables, and
+ * usage of those constant channels with direct usage of the constants.
+ *
+ * This can lead to constant folding and algebraic optimizations in
+ * those later expressions, while causing no increase in instruction
+ * count (due to constants being generally free to load from a
+ * constant push buffer or as instruction immediate values) and
+ * possibly reducing register pressure.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_rvalue_visitor.h"
+#include "ir_basic_block.h"
+#include "ir_optimization.h"
+#include "glsl_types.h"
+
+class acp_entry : public exec_node
+{
+public:
+ acp_entry(ir_variable *var, unsigned write_mask, ir_constant *constant)
+ {
+ assert(var);
+ assert(constant);
+ this->var = var;
+ this->write_mask = write_mask;
+ this->constant = constant;
+ }
+
+ ir_variable *var;
+ ir_constant *constant;
+ unsigned write_mask;
+};
+
+
+class kill_entry : public exec_node
+{
+public:
+ kill_entry(ir_variable *var, unsigned write_mask)
+ {
+ assert(var);
+ this->var = var;
+ this->write_mask = write_mask;
+ }
+
+ ir_variable *var;
+ unsigned write_mask;
+};
+
+class ir_constant_propagation_visitor : public ir_rvalue_visitor {
+public:
+ ir_constant_propagation_visitor()
+ {
+ progress = false;
+ mem_ctx = ralloc_context(0);
+ this->acp = new(mem_ctx) exec_list;
+ this->kills = new(mem_ctx) exec_list;
+ }
+ ~ir_constant_propagation_visitor()
+ {
+ ralloc_free(mem_ctx);
+ }
+
+ virtual ir_visitor_status visit_enter(class ir_loop *);
+ virtual ir_visitor_status visit_enter(class ir_function_signature *);
+ virtual ir_visitor_status visit_enter(class ir_function *);
+ virtual ir_visitor_status visit_leave(class ir_assignment *);
+ virtual ir_visitor_status visit_enter(class ir_call *);
+ virtual ir_visitor_status visit_enter(class ir_if *);
+
+ void add_constant(ir_assignment *ir);
+ void kill(ir_variable *ir, unsigned write_mask);
+ void handle_if_block(exec_list *instructions);
+ void handle_rvalue(ir_rvalue **rvalue);
+
+ /** List of acp_entry: The available constants to propagate */
+ exec_list *acp;
+
+ /**
+ * List of kill_entry: The masks of variables whose values were
+ * killed in this block.
+ */
+ exec_list *kills;
+
+ bool progress;
+
+ bool killed_all;
+
+ void *mem_ctx;
+};
+
+
+void
+ir_constant_propagation_visitor::handle_rvalue(ir_rvalue **rvalue)
+{
+ if (this->in_assignee || !*rvalue)
+ return;
+
+ const glsl_type *type = (*rvalue)->type;
+ if (!type->is_scalar() && !type->is_vector())
+ return;
+
+ ir_swizzle *swiz = NULL;
+ ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
+ if (!deref) {
+ swiz = (*rvalue)->as_swizzle();
+ if (!swiz)
+ return;
+
+ deref = swiz->val->as_dereference_variable();
+ if (!deref)
+ return;
+ }
+
+ ir_constant_data data;
+ memset(&data, 0, sizeof(data));
+
+ for (unsigned int i = 0; i < type->components(); i++) {
+ int channel;
+ acp_entry *found = NULL;
+
+ if (swiz) {
+ switch (i) {
+ case 0: channel = swiz->mask.x; break;
+ case 1: channel = swiz->mask.y; break;
+ case 2: channel = swiz->mask.z; break;
+ case 3: channel = swiz->mask.w; break;
+ default: assert(!"shouldn't be reached"); channel = 0; break;
+ }
+ } else {
+ channel = i;
+ }
+
+ foreach_iter(exec_list_iterator, iter, *this->acp) {
+ acp_entry *entry = (acp_entry *)iter.get();
+ if (entry->var == deref->var && entry->write_mask & (1 << channel)) {
+ found = entry;
+ break;
+ }
+ }
+
+ if (!found)
+ return;
+
+ int rhs_channel = 0;
+ for (int j = 0; j < 4; j++) {
+ if (j == channel)
+ break;
+ if (found->write_mask & (1 << j))
+ rhs_channel++;
+ }
+
+ switch (type->base_type) {
+ case GLSL_TYPE_FLOAT:
+ data.f[i] = found->constant->value.f[rhs_channel];
+ break;
+ case GLSL_TYPE_INT:
+ data.i[i] = found->constant->value.i[rhs_channel];
+ break;
+ case GLSL_TYPE_UINT:
+ data.u[i] = found->constant->value.u[rhs_channel];
+ break;
+ case GLSL_TYPE_BOOL:
+ data.b[i] = found->constant->value.b[rhs_channel];
+ break;
+ default:
+ assert(!"not reached");
+ break;
+ }
+ }
+
+ *rvalue = new(ralloc_parent(deref)) ir_constant(type, &data);
+ this->progress = true;
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_enter(ir_function_signature *ir)
+{
+ /* Treat entry into a function signature as a completely separate
+ * block. Any instructions at global scope will be shuffled into
+ * main() at link time, so they're irrelevant to us.
+ */
+ exec_list *orig_acp = this->acp;
+ exec_list *orig_kills = this->kills;
+ bool orig_killed_all = this->killed_all;
+
+ this->acp = new(mem_ctx) exec_list;
+ this->kills = new(mem_ctx) exec_list;
+ this->killed_all = false;
+
+ visit_list_elements(this, &ir->body);
+
+ this->kills = orig_kills;
+ this->acp = orig_acp;
+ this->killed_all = orig_killed_all;
+
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_leave(ir_assignment *ir)
+{
+ if (this->in_assignee)
+ return visit_continue;
+
+ kill(ir->lhs->variable_referenced(), ir->write_mask);
+
+ add_constant(ir);
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_enter(ir_function *ir)
+{
+ (void) ir;
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_enter(ir_call *ir)
+{
+ /* Do constant propagation on call parameters, but skip any out params */
+ exec_list_iterator sig_param_iter = ir->get_callee()->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, ir->actual_parameters) {
+ ir_variable *sig_param = (ir_variable *)sig_param_iter.get();
+ ir_rvalue *param = (ir_rvalue *)iter.get();
+ if (sig_param->mode != ir_var_out && sig_param->mode != ir_var_inout) {
+ ir_rvalue *new_param = param;
+ handle_rvalue(&new_param);
+ if (new_param != param)
+ param->replace_with(new_param);
+ else
+ param->accept(this);
+ }
+ sig_param_iter.next();
+ }
+
+ /* Since we're unlinked, we don't (necssarily) know the side effects of
+ * this call. So kill all copies.
+ */
+ acp->make_empty();
+ this->killed_all = true;
+
+ return visit_continue_with_parent;
+}
+
+void
+ir_constant_propagation_visitor::handle_if_block(exec_list *instructions)
+{
+ exec_list *orig_acp = this->acp;
+ exec_list *orig_kills = this->kills;
+ bool orig_killed_all = this->killed_all;
+
+ this->acp = new(mem_ctx) exec_list;
+ this->kills = new(mem_ctx) exec_list;
+ this->killed_all = false;
+
+ /* Populate the initial acp with a constant of the original */
+ foreach_iter(exec_list_iterator, iter, *orig_acp) {
+ acp_entry *a = (acp_entry *)iter.get();
+ this->acp->push_tail(new(this->mem_ctx) acp_entry(a->var, a->write_mask,
+ a->constant));
+ }
+
+ visit_list_elements(this, instructions);
+
+ if (this->killed_all) {
+ orig_acp->make_empty();
+ }
+
+ exec_list *new_kills = this->kills;
+ this->kills = orig_kills;
+ this->acp = orig_acp;
+ this->killed_all = this->killed_all || orig_killed_all;
+
+ foreach_iter(exec_list_iterator, iter, *new_kills) {
+ kill_entry *k = (kill_entry *)iter.get();
+ kill(k->var, k->write_mask);
+ }
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_enter(ir_if *ir)
+{
+ ir->condition->accept(this);
+ handle_rvalue(&ir->condition);
+
+ handle_if_block(&ir->then_instructions);
+ handle_if_block(&ir->else_instructions);
+
+ /* handle_if_block() already descended into the children. */
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_constant_propagation_visitor::visit_enter(ir_loop *ir)
+{
+ exec_list *orig_acp = this->acp;
+ exec_list *orig_kills = this->kills;
+ bool orig_killed_all = this->killed_all;
+
+ /* FINISHME: For now, the initial acp for loops is totally empty.
+ * We could go through once, then go through again with the acp
+ * cloned minus the killed entries after the first run through.
+ */
+ this->acp = new(mem_ctx) exec_list;
+ this->kills = new(mem_ctx) exec_list;
+ this->killed_all = false;
+
+ visit_list_elements(this, &ir->body_instructions);
+
+ if (this->killed_all) {
+ orig_acp->make_empty();
+ }
+
+ exec_list *new_kills = this->kills;
+ this->kills = orig_kills;
+ this->acp = orig_acp;
+ this->killed_all = this->killed_all || orig_killed_all;
+
+ foreach_iter(exec_list_iterator, iter, *new_kills) {
+ kill_entry *k = (kill_entry *)iter.get();
+ kill(k->var, k->write_mask);
+ }
+
+ /* already descended into the children. */
+ return visit_continue_with_parent;
+}
+
+void
+ir_constant_propagation_visitor::kill(ir_variable *var, unsigned write_mask)
+{
+ assert(var != NULL);
+
+ /* We don't track non-vectors. */
+ if (!var->type->is_vector() && !var->type->is_scalar())
+ return;
+
+ /* Remove any entries currently in the ACP for this kill. */
+ foreach_iter(exec_list_iterator, iter, *this->acp) {
+ acp_entry *entry = (acp_entry *)iter.get();
+
+ if (entry->var == var) {
+ entry->write_mask &= ~write_mask;
+ if (entry->write_mask == 0)
+ entry->remove();
+ }
+ }
+
+ /* Add this writemask of the variable to the list of killed
+ * variables in this block.
+ */
+ foreach_iter(exec_list_iterator, iter, *this->kills) {
+ kill_entry *entry = (kill_entry *)iter.get();
+
+ if (entry->var == var) {
+ entry->write_mask |= write_mask;
+ return;
+ }
+ }
+ /* Not already in the list. Make new entry. */
+ this->kills->push_tail(new(this->mem_ctx) kill_entry(var, write_mask));
+}
+
+/**
+ * Adds an entry to the available constant list if it's a plain assignment
+ * of a variable to a variable.
+ */
+void
+ir_constant_propagation_visitor::add_constant(ir_assignment *ir)
+{
+ acp_entry *entry;
+
+ if (ir->condition)
+ return;
+
+ if (!ir->write_mask)
+ return;
+
+ ir_dereference_variable *deref = ir->lhs->as_dereference_variable();
+ ir_constant *constant = ir->rhs->as_constant();
+
+ if (!deref || !constant)
+ return;
+
+ /* Only do constant propagation on vectors. Constant matrices,
+ * arrays, or structures would require more work elsewhere.
+ */
+ if (!deref->var->type->is_vector() && !deref->var->type->is_scalar())
+ return;
+
+ entry = new(this->mem_ctx) acp_entry(deref->var, ir->write_mask, constant);
+ this->acp->push_tail(entry);
+}
+
+/**
+ * Does a constant propagation pass on the code present in the instruction stream.
+ */
+bool
+do_constant_propagation(exec_list *instructions)
+{
+ ir_constant_propagation_visitor v;
+
+ visit_list_elements(&v, instructions);
+
+ return v.progress;
+}
diff --git a/mesalib/src/glsl/opt_constant_variable.cpp b/mesalib/src/glsl/opt_constant_variable.cpp
index 3fa7c3bad..f1aeaa99a 100644
--- a/mesalib/src/glsl/opt_constant_variable.cpp
+++ b/mesalib/src/glsl/opt_constant_variable.cpp
@@ -1,195 +1,195 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_constant_variable.cpp
- *
- * Marks variables assigned a single constant value over the course
- * of the program as constant.
- *
- * The goal here is to trigger further constant folding and then dead
- * code elimination. This is common with vector/matrix constructors
- * and calls to builtin functions.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_optimization.h"
-#include "glsl_types.h"
-
-struct assignment_entry {
- exec_node link;
- int assignment_count;
- ir_variable *var;
- ir_constant *constval;
- bool our_scope;
-};
-
-class ir_constant_variable_visitor : public ir_hierarchical_visitor {
-public:
- virtual ir_visitor_status visit_enter(ir_dereference_variable *);
- virtual ir_visitor_status visit(ir_variable *);
- virtual ir_visitor_status visit_enter(ir_assignment *);
- virtual ir_visitor_status visit_enter(ir_call *);
-
- exec_list list;
-};
-
-static struct assignment_entry *
-get_assignment_entry(ir_variable *var, exec_list *list)
-{
- struct assignment_entry *entry;
-
- foreach_list_typed(struct assignment_entry, entry, link, list) {
- if (entry->var == var)
- return entry;
- }
-
- entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
- entry->var = var;
- list->push_head(&entry->link);
- return entry;
-}
-
-ir_visitor_status
-ir_constant_variable_visitor::visit(ir_variable *ir)
-{
- struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
- entry->our_scope = true;
- return visit_continue;
-}
-
-/* Skip derefs of variables so that we can detect declarations. */
-ir_visitor_status
-ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
-{
- (void)ir;
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
-{
- ir_constant *constval;
- struct assignment_entry *entry;
-
- entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
- assert(entry);
- entry->assignment_count++;
-
- /* If it's already constant, don't do the work. */
- if (entry->var->constant_value)
- return visit_continue;
-
- /* OK, now find if we actually have all the right conditions for
- * this to be a constant value assigned to the var.
- */
- if (ir->condition)
- return visit_continue;
-
- ir_variable *var = ir->whole_variable_written();
- if (!var)
- return visit_continue;
-
- constval = ir->rhs->constant_expression_value();
- if (!constval)
- return visit_continue;
-
- /* Mark this entry as having a constant assignment (if the
- * assignment count doesn't go >1). do_constant_variable will fix
- * up the variable with the constant value later.
- */
- entry->constval = constval;
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_constant_variable_visitor::visit_enter(ir_call *ir)
-{
- exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_rvalue *param_rval = (ir_rvalue *)iter.get();
- ir_variable *param = (ir_variable *)sig_iter.get();
-
- if (param->mode == ir_var_out ||
- param->mode == ir_var_inout) {
- ir_variable *var = param_rval->variable_referenced();
- struct assignment_entry *entry;
-
- assert(var);
- entry = get_assignment_entry(var, &this->list);
- entry->assignment_count++;
- }
- sig_iter.next();
- }
- return visit_continue;
-}
-
-/**
- * Does a copy propagation pass on the code present in the instruction stream.
- */
-bool
-do_constant_variable(exec_list *instructions)
-{
- bool progress = false;
- ir_constant_variable_visitor v;
-
- v.run(instructions);
-
- while (!v.list.is_empty()) {
-
- struct assignment_entry *entry;
- entry = exec_node_data(struct assignment_entry, v.list.head, link);
-
- if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
- entry->var->constant_value = entry->constval;
- progress = true;
- }
- entry->link.remove();
- free(entry);
- }
-
- return progress;
-}
-
-bool
-do_constant_variable_unlinked(exec_list *instructions)
-{
- bool progress = false;
-
- foreach_iter(exec_list_iterator, iter, *instructions) {
- ir_instruction *ir = (ir_instruction *)iter.get();
- ir_function *f = ir->as_function();
- if (f) {
- foreach_iter(exec_list_iterator, sigiter, *f) {
- ir_function_signature *sig =
- (ir_function_signature *) sigiter.get();
- if (do_constant_variable(&sig->body))
- progress = true;
- }
- }
- }
-
- return progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_constant_variable.cpp
+ *
+ * Marks variables assigned a single constant value over the course
+ * of the program as constant.
+ *
+ * The goal here is to trigger further constant folding and then dead
+ * code elimination. This is common with vector/matrix constructors
+ * and calls to builtin functions.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_optimization.h"
+#include "glsl_types.h"
+
+struct assignment_entry {
+ exec_node link;
+ int assignment_count;
+ ir_variable *var;
+ ir_constant *constval;
+ bool our_scope;
+};
+
+class ir_constant_variable_visitor : public ir_hierarchical_visitor {
+public:
+ virtual ir_visitor_status visit_enter(ir_dereference_variable *);
+ virtual ir_visitor_status visit(ir_variable *);
+ virtual ir_visitor_status visit_enter(ir_assignment *);
+ virtual ir_visitor_status visit_enter(ir_call *);
+
+ exec_list list;
+};
+
+static struct assignment_entry *
+get_assignment_entry(ir_variable *var, exec_list *list)
+{
+ struct assignment_entry *entry;
+
+ foreach_list_typed(struct assignment_entry, entry, link, list) {
+ if (entry->var == var)
+ return entry;
+ }
+
+ entry = (struct assignment_entry *)calloc(1, sizeof(*entry));
+ entry->var = var;
+ list->push_head(&entry->link);
+ return entry;
+}
+
+ir_visitor_status
+ir_constant_variable_visitor::visit(ir_variable *ir)
+{
+ struct assignment_entry *entry = get_assignment_entry(ir, &this->list);
+ entry->our_scope = true;
+ return visit_continue;
+}
+
+/* Skip derefs of variables so that we can detect declarations. */
+ir_visitor_status
+ir_constant_variable_visitor::visit_enter(ir_dereference_variable *ir)
+{
+ (void)ir;
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_constant_variable_visitor::visit_enter(ir_assignment *ir)
+{
+ ir_constant *constval;
+ struct assignment_entry *entry;
+
+ entry = get_assignment_entry(ir->lhs->variable_referenced(), &this->list);
+ assert(entry);
+ entry->assignment_count++;
+
+ /* If it's already constant, don't do the work. */
+ if (entry->var->constant_value)
+ return visit_continue;
+
+ /* OK, now find if we actually have all the right conditions for
+ * this to be a constant value assigned to the var.
+ */
+ if (ir->condition)
+ return visit_continue;
+
+ ir_variable *var = ir->whole_variable_written();
+ if (!var)
+ return visit_continue;
+
+ constval = ir->rhs->constant_expression_value();
+ if (!constval)
+ return visit_continue;
+
+ /* Mark this entry as having a constant assignment (if the
+ * assignment count doesn't go >1). do_constant_variable will fix
+ * up the variable with the constant value later.
+ */
+ entry->constval = constval;
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_constant_variable_visitor::visit_enter(ir_call *ir)
+{
+ exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_rvalue *param_rval = (ir_rvalue *)iter.get();
+ ir_variable *param = (ir_variable *)sig_iter.get();
+
+ if (param->mode == ir_var_out ||
+ param->mode == ir_var_inout) {
+ ir_variable *var = param_rval->variable_referenced();
+ struct assignment_entry *entry;
+
+ assert(var);
+ entry = get_assignment_entry(var, &this->list);
+ entry->assignment_count++;
+ }
+ sig_iter.next();
+ }
+ return visit_continue;
+}
+
+/**
+ * Does a copy propagation pass on the code present in the instruction stream.
+ */
+bool
+do_constant_variable(exec_list *instructions)
+{
+ bool progress = false;
+ ir_constant_variable_visitor v;
+
+ v.run(instructions);
+
+ while (!v.list.is_empty()) {
+
+ struct assignment_entry *entry;
+ entry = exec_node_data(struct assignment_entry, v.list.head, link);
+
+ if (entry->assignment_count == 1 && entry->constval && entry->our_scope) {
+ entry->var->constant_value = entry->constval;
+ progress = true;
+ }
+ entry->link.remove();
+ free(entry);
+ }
+
+ return progress;
+}
+
+bool
+do_constant_variable_unlinked(exec_list *instructions)
+{
+ bool progress = false;
+
+ foreach_iter(exec_list_iterator, iter, *instructions) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+ ir_function *f = ir->as_function();
+ if (f) {
+ foreach_iter(exec_list_iterator, sigiter, *f) {
+ ir_function_signature *sig =
+ (ir_function_signature *) sigiter.get();
+ if (do_constant_variable(&sig->body))
+ progress = true;
+ }
+ }
+ }
+
+ return progress;
+}
diff --git a/mesalib/src/glsl/opt_dead_code.cpp b/mesalib/src/glsl/opt_dead_code.cpp
index cb500d2d1..492ba73a1 100644
--- a/mesalib/src/glsl/opt_dead_code.cpp
+++ b/mesalib/src/glsl/opt_dead_code.cpp
@@ -1,142 +1,142 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_code.cpp
- *
- * Eliminates dead assignments and variable declarations from the code.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_variable_refcount.h"
-#include "glsl_types.h"
-
-static bool debug = false;
-
-/**
- * Do a dead code pass over instructions and everything that instructions
- * references.
- *
- * Note that this will remove assignments to globals, so it is not suitable
- * for usage on an unlinked instruction stream.
- */
-bool
-do_dead_code(exec_list *instructions)
-{
- ir_variable_refcount_visitor v;
- bool progress = false;
-
- v.run(instructions);
-
- foreach_iter(exec_list_iterator, iter, v.variable_list) {
- variable_entry *entry = (variable_entry *)iter.get();
-
- /* Since each assignment is a reference, the refereneced count must be
- * greater than or equal to the assignment count. If they are equal,
- * then all of the references are assignments, and the variable is
- * dead.
- *
- * Note that if the variable is neither assigned nor referenced, both
- * counts will be zero and will be caught by the equality test.
- */
- assert(entry->referenced_count >= entry->assigned_count);
-
- if (debug) {
- printf("%s@%p: %d refs, %d assigns, %sdeclared in our scope\n",
- entry->var->name, (void *) entry->var,
- entry->referenced_count, entry->assigned_count,
- entry->declaration ? "" : "not ");
- }
-
- if ((entry->referenced_count > entry->assigned_count)
- || !entry->declaration)
- continue;
-
- if (entry->assign) {
- /* Remove a single dead assignment to the variable we found.
- * Don't do so if it's a shader output, though.
- */
- if (entry->var->mode != ir_var_out &&
- entry->var->mode != ir_var_inout &&
- !ir_has_call(entry->assign)) {
- entry->assign->remove();
- progress = true;
-
- if (debug) {
- printf("Removed assignment to %s@%p\n",
- entry->var->name, (void *) entry->var);
- }
- }
- } else {
- /* If there are no assignments or references to the variable left,
- * then we can remove its declaration.
- */
-
- /* uniform initializers are precious, and could get used by another
- * stage.
- */
- if (entry->var->mode == ir_var_uniform &&
- entry->var->constant_value)
- continue;
-
- entry->var->remove();
- progress = true;
-
- if (debug) {
- printf("Removed declaration of %s@%p\n",
- entry->var->name, (void *) entry->var);
- }
- }
- }
-
- return progress;
-}
-
-/**
- * Does a dead code pass on the functions present in the instruction stream.
- *
- * This is suitable for use while the program is not linked, as it will
- * ignore variable declarations (and the assignments to them) for variables
- * with global scope.
- */
-bool
-do_dead_code_unlinked(exec_list *instructions)
-{
- bool progress = false;
-
- foreach_iter(exec_list_iterator, iter, *instructions) {
- ir_instruction *ir = (ir_instruction *)iter.get();
- ir_function *f = ir->as_function();
- if (f) {
- foreach_iter(exec_list_iterator, sigiter, *f) {
- ir_function_signature *sig =
- (ir_function_signature *) sigiter.get();
- if (do_dead_code(&sig->body))
- progress = true;
- }
- }
- }
-
- return progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_code.cpp
+ *
+ * Eliminates dead assignments and variable declarations from the code.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_variable_refcount.h"
+#include "glsl_types.h"
+
+static bool debug = false;
+
+/**
+ * Do a dead code pass over instructions and everything that instructions
+ * references.
+ *
+ * Note that this will remove assignments to globals, so it is not suitable
+ * for usage on an unlinked instruction stream.
+ */
+bool
+do_dead_code(exec_list *instructions)
+{
+ ir_variable_refcount_visitor v;
+ bool progress = false;
+
+ v.run(instructions);
+
+ foreach_iter(exec_list_iterator, iter, v.variable_list) {
+ variable_entry *entry = (variable_entry *)iter.get();
+
+ /* Since each assignment is a reference, the refereneced count must be
+ * greater than or equal to the assignment count. If they are equal,
+ * then all of the references are assignments, and the variable is
+ * dead.
+ *
+ * Note that if the variable is neither assigned nor referenced, both
+ * counts will be zero and will be caught by the equality test.
+ */
+ assert(entry->referenced_count >= entry->assigned_count);
+
+ if (debug) {
+ printf("%s@%p: %d refs, %d assigns, %sdeclared in our scope\n",
+ entry->var->name, (void *) entry->var,
+ entry->referenced_count, entry->assigned_count,
+ entry->declaration ? "" : "not ");
+ }
+
+ if ((entry->referenced_count > entry->assigned_count)
+ || !entry->declaration)
+ continue;
+
+ if (entry->assign) {
+ /* Remove a single dead assignment to the variable we found.
+ * Don't do so if it's a shader output, though.
+ */
+ if (entry->var->mode != ir_var_out &&
+ entry->var->mode != ir_var_inout &&
+ !ir_has_call(entry->assign)) {
+ entry->assign->remove();
+ progress = true;
+
+ if (debug) {
+ printf("Removed assignment to %s@%p\n",
+ entry->var->name, (void *) entry->var);
+ }
+ }
+ } else {
+ /* If there are no assignments or references to the variable left,
+ * then we can remove its declaration.
+ */
+
+ /* uniform initializers are precious, and could get used by another
+ * stage.
+ */
+ if (entry->var->mode == ir_var_uniform &&
+ entry->var->constant_value)
+ continue;
+
+ entry->var->remove();
+ progress = true;
+
+ if (debug) {
+ printf("Removed declaration of %s@%p\n",
+ entry->var->name, (void *) entry->var);
+ }
+ }
+ }
+
+ return progress;
+}
+
+/**
+ * Does a dead code pass on the functions present in the instruction stream.
+ *
+ * This is suitable for use while the program is not linked, as it will
+ * ignore variable declarations (and the assignments to them) for variables
+ * with global scope.
+ */
+bool
+do_dead_code_unlinked(exec_list *instructions)
+{
+ bool progress = false;
+
+ foreach_iter(exec_list_iterator, iter, *instructions) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+ ir_function *f = ir->as_function();
+ if (f) {
+ foreach_iter(exec_list_iterator, sigiter, *f) {
+ ir_function_signature *sig =
+ (ir_function_signature *) sigiter.get();
+ if (do_dead_code(&sig->body))
+ progress = true;
+ }
+ }
+ }
+
+ return progress;
+}
diff --git a/mesalib/src/glsl/opt_dead_code_local.cpp b/mesalib/src/glsl/opt_dead_code_local.cpp
index 39962bd60..42e5e94c8 100644
--- a/mesalib/src/glsl/opt_dead_code_local.cpp
+++ b/mesalib/src/glsl/opt_dead_code_local.cpp
@@ -1,222 +1,222 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_code_local.cpp
- *
- * Eliminates local dead assignments from the code.
- *
- * This operates on basic blocks, tracking assignments and finding if
- * they're used before the variable is completely reassigned.
- *
- * Compare this to ir_dead_code.cpp, which operates globally looking
- * for assignments to variables that are never read.
- */
-
-#include "ir.h"
-#include "ir_basic_block.h"
-#include "ir_optimization.h"
-#include "glsl_types.h"
-
-static bool debug = false;
-
-class assignment_entry : public exec_node
-{
-public:
- assignment_entry(ir_variable *lhs, ir_instruction *ir)
- {
- assert(lhs);
- assert(ir);
- this->lhs = lhs;
- this->ir = ir;
- }
-
- ir_variable *lhs;
- ir_instruction *ir;
-};
-
-class kill_for_derefs_visitor : public ir_hierarchical_visitor {
-public:
- kill_for_derefs_visitor(exec_list *assignments)
- {
- this->assignments = assignments;
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- ir_variable *const var = ir->variable_referenced();
-
- foreach_iter(exec_list_iterator, iter, *this->assignments) {
- assignment_entry *entry = (assignment_entry *)iter.get();
-
- if (entry->lhs == var) {
- if (debug)
- printf("kill %s\n", entry->lhs->name);
- entry->remove();
- }
- }
-
- return visit_continue;
- }
-
-private:
- exec_list *assignments;
-};
-
-class array_index_visit : public ir_hierarchical_visitor {
-public:
- array_index_visit(ir_hierarchical_visitor *v)
- {
- this->visitor = v;
- }
-
- virtual ir_visitor_status visit_enter(class ir_dereference_array *ir)
- {
- ir->array_index->accept(visitor);
- return visit_continue;
- }
-
- static void run(ir_instruction *ir, ir_hierarchical_visitor *v)
- {
- array_index_visit top_visit(v);
- ir->accept(& top_visit);
- }
-
- ir_hierarchical_visitor *visitor;
-};
-
-
-/**
- * Adds an entry to the available copy list if it's a plain assignment
- * of a variable to a variable.
- */
-static bool
-process_assignment(void *ctx, ir_assignment *ir, exec_list *assignments)
-{
- ir_variable *var = NULL;
- bool progress = false;
- kill_for_derefs_visitor v(assignments);
-
- /* Kill assignment entries for things used to produce this assignment. */
- ir->rhs->accept(&v);
- if (ir->condition) {
- ir->condition->accept(&v);
- }
-
- /* Kill assignment enties used as array indices.
- */
- array_index_visit::run(ir->lhs, &v);
- var = ir->lhs->variable_referenced();
- assert(var);
-
- /* Now, check if we did a whole-variable assignment. */
- if (!ir->condition && (ir->whole_variable_written() != NULL)) {
- /* We did a whole-variable assignment. So, any instruction in
- * the assignment list with the same LHS is dead.
- */
- if (debug)
- printf("looking for %s to remove\n", var->name);
- foreach_iter(exec_list_iterator, iter, *assignments) {
- assignment_entry *entry = (assignment_entry *)iter.get();
-
- if (entry->lhs == var) {
- if (debug)
- printf("removing %s\n", var->name);
- entry->ir->remove();
- entry->remove();
- progress = true;
- }
- }
- }
-
- /* Add this instruction to the assignment list available to be removed.
- * But not if the assignment has other side effects.
- */
- if (ir_has_call(ir))
- return progress;
-
- assignment_entry *entry = new(ctx) assignment_entry(var, ir);
- assignments->push_tail(entry);
-
- if (debug) {
- printf("add %s\n", var->name);
-
- printf("current entries\n");
- foreach_iter(exec_list_iterator, iter, *assignments) {
- assignment_entry *entry = (assignment_entry *)iter.get();
-
- printf(" %s\n", entry->lhs->name);
- }
- }
-
- return progress;
-}
-
-static void
-dead_code_local_basic_block(ir_instruction *first,
- ir_instruction *last,
- void *data)
-{
- ir_instruction *ir, *ir_next;
- /* List of avaialble_copy */
- exec_list assignments;
- bool *out_progress = (bool *)data;
- bool progress = false;
-
- void *ctx = ralloc_context(NULL);
- /* Safe looping, since process_assignment */
- for (ir = first, ir_next = (ir_instruction *)first->next;;
- ir = ir_next, ir_next = (ir_instruction *)ir->next) {
- ir_assignment *ir_assign = ir->as_assignment();
-
- if (debug) {
- ir->print();
- printf("\n");
- }
-
- if (ir_assign) {
- progress = process_assignment(ctx, ir_assign, &assignments) || progress;
- } else {
- kill_for_derefs_visitor kill(&assignments);
- ir->accept(&kill);
- }
-
- if (ir == last)
- break;
- }
- *out_progress = progress;
- ralloc_free(ctx);
-}
-
-/**
- * Does a copy propagation pass on the code present in the instruction stream.
- */
-bool
-do_dead_code_local(exec_list *instructions)
-{
- bool progress = false;
-
- call_for_basic_blocks(instructions, dead_code_local_basic_block, &progress);
-
- return progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_code_local.cpp
+ *
+ * Eliminates local dead assignments from the code.
+ *
+ * This operates on basic blocks, tracking assignments and finding if
+ * they're used before the variable is completely reassigned.
+ *
+ * Compare this to ir_dead_code.cpp, which operates globally looking
+ * for assignments to variables that are never read.
+ */
+
+#include "ir.h"
+#include "ir_basic_block.h"
+#include "ir_optimization.h"
+#include "glsl_types.h"
+
+static bool debug = false;
+
+class assignment_entry : public exec_node
+{
+public:
+ assignment_entry(ir_variable *lhs, ir_instruction *ir)
+ {
+ assert(lhs);
+ assert(ir);
+ this->lhs = lhs;
+ this->ir = ir;
+ }
+
+ ir_variable *lhs;
+ ir_instruction *ir;
+};
+
+class kill_for_derefs_visitor : public ir_hierarchical_visitor {
+public:
+ kill_for_derefs_visitor(exec_list *assignments)
+ {
+ this->assignments = assignments;
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ ir_variable *const var = ir->variable_referenced();
+
+ foreach_iter(exec_list_iterator, iter, *this->assignments) {
+ assignment_entry *entry = (assignment_entry *)iter.get();
+
+ if (entry->lhs == var) {
+ if (debug)
+ printf("kill %s\n", entry->lhs->name);
+ entry->remove();
+ }
+ }
+
+ return visit_continue;
+ }
+
+private:
+ exec_list *assignments;
+};
+
+class array_index_visit : public ir_hierarchical_visitor {
+public:
+ array_index_visit(ir_hierarchical_visitor *v)
+ {
+ this->visitor = v;
+ }
+
+ virtual ir_visitor_status visit_enter(class ir_dereference_array *ir)
+ {
+ ir->array_index->accept(visitor);
+ return visit_continue;
+ }
+
+ static void run(ir_instruction *ir, ir_hierarchical_visitor *v)
+ {
+ array_index_visit top_visit(v);
+ ir->accept(& top_visit);
+ }
+
+ ir_hierarchical_visitor *visitor;
+};
+
+
+/**
+ * Adds an entry to the available copy list if it's a plain assignment
+ * of a variable to a variable.
+ */
+static bool
+process_assignment(void *ctx, ir_assignment *ir, exec_list *assignments)
+{
+ ir_variable *var = NULL;
+ bool progress = false;
+ kill_for_derefs_visitor v(assignments);
+
+ /* Kill assignment entries for things used to produce this assignment. */
+ ir->rhs->accept(&v);
+ if (ir->condition) {
+ ir->condition->accept(&v);
+ }
+
+ /* Kill assignment enties used as array indices.
+ */
+ array_index_visit::run(ir->lhs, &v);
+ var = ir->lhs->variable_referenced();
+ assert(var);
+
+ /* Now, check if we did a whole-variable assignment. */
+ if (!ir->condition && (ir->whole_variable_written() != NULL)) {
+ /* We did a whole-variable assignment. So, any instruction in
+ * the assignment list with the same LHS is dead.
+ */
+ if (debug)
+ printf("looking for %s to remove\n", var->name);
+ foreach_iter(exec_list_iterator, iter, *assignments) {
+ assignment_entry *entry = (assignment_entry *)iter.get();
+
+ if (entry->lhs == var) {
+ if (debug)
+ printf("removing %s\n", var->name);
+ entry->ir->remove();
+ entry->remove();
+ progress = true;
+ }
+ }
+ }
+
+ /* Add this instruction to the assignment list available to be removed.
+ * But not if the assignment has other side effects.
+ */
+ if (ir_has_call(ir))
+ return progress;
+
+ assignment_entry *entry = new(ctx) assignment_entry(var, ir);
+ assignments->push_tail(entry);
+
+ if (debug) {
+ printf("add %s\n", var->name);
+
+ printf("current entries\n");
+ foreach_iter(exec_list_iterator, iter, *assignments) {
+ assignment_entry *entry = (assignment_entry *)iter.get();
+
+ printf(" %s\n", entry->lhs->name);
+ }
+ }
+
+ return progress;
+}
+
+static void
+dead_code_local_basic_block(ir_instruction *first,
+ ir_instruction *last,
+ void *data)
+{
+ ir_instruction *ir, *ir_next;
+ /* List of avaialble_copy */
+ exec_list assignments;
+ bool *out_progress = (bool *)data;
+ bool progress = false;
+
+ void *ctx = ralloc_context(NULL);
+ /* Safe looping, since process_assignment */
+ for (ir = first, ir_next = (ir_instruction *)first->next;;
+ ir = ir_next, ir_next = (ir_instruction *)ir->next) {
+ ir_assignment *ir_assign = ir->as_assignment();
+
+ if (debug) {
+ ir->print();
+ printf("\n");
+ }
+
+ if (ir_assign) {
+ progress = process_assignment(ctx, ir_assign, &assignments) || progress;
+ } else {
+ kill_for_derefs_visitor kill(&assignments);
+ ir->accept(&kill);
+ }
+
+ if (ir == last)
+ break;
+ }
+ *out_progress = progress;
+ ralloc_free(ctx);
+}
+
+/**
+ * Does a copy propagation pass on the code present in the instruction stream.
+ */
+bool
+do_dead_code_local(exec_list *instructions)
+{
+ bool progress = false;
+
+ call_for_basic_blocks(instructions, dead_code_local_basic_block, &progress);
+
+ return progress;
+}
diff --git a/mesalib/src/glsl/opt_dead_functions.cpp b/mesalib/src/glsl/opt_dead_functions.cpp
index ceb79080a..6d41af5c5 100644
--- a/mesalib/src/glsl/opt_dead_functions.cpp
+++ b/mesalib/src/glsl/opt_dead_functions.cpp
@@ -1,153 +1,153 @@
- /*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_functions.cpp
- *
- * Eliminates unused functions from the linked program.
- */
-
- #include "ir.h"
- #include "ir_visitor.h"
- #include "ir_expression_flattening.h"
- #include "glsl_types.h"
-
- class signature_entry : public exec_node
- {
- public:
- signature_entry(ir_function_signature *sig)
- {
- this->signature = sig;
- this->used = false;
- }
-
- ir_function_signature *signature;
- bool used;
- };
-
- class ir_dead_functions_visitor : public ir_hierarchical_visitor {
- public:
- ir_dead_functions_visitor()
- {
- this->mem_ctx = ralloc_context(NULL);
- }
-
- ~ir_dead_functions_visitor()
- {
- ralloc_free(this->mem_ctx);
- }
-
- virtual ir_visitor_status visit_enter(ir_function_signature *);
- virtual ir_visitor_status visit_enter(ir_call *);
-
- signature_entry *get_signature_entry(ir_function_signature *var);
-
- bool (*predicate)(ir_instruction *ir);
-
- /* List of signature_entry */
- exec_list signature_list;
- void *mem_ctx;
- };
-
-
- signature_entry *
- ir_dead_functions_visitor::get_signature_entry(ir_function_signature *sig)
- {
- foreach_iter(exec_list_iterator, iter, this->signature_list) {
- signature_entry *entry = (signature_entry *)iter.get();
- if (entry->signature == sig)
- return entry;
- }
-
- signature_entry *entry = new(mem_ctx) signature_entry(sig);
- this->signature_list.push_tail(entry);
- return entry;
- }
-
-
- ir_visitor_status
- ir_dead_functions_visitor::visit_enter(ir_function_signature *ir)
- {
- signature_entry *entry = this->get_signature_entry(ir);
-
- if (strcmp(ir->function_name(), "main") == 0) {
- entry->used = true;
- }
-
- return visit_continue;
- }
-
-
- ir_visitor_status
- ir_dead_functions_visitor::visit_enter(ir_call *ir)
- {
- signature_entry *entry = this->get_signature_entry(ir->get_callee());
-
- entry->used = true;
-
- return visit_continue;
-}
-
-bool
-do_dead_functions(exec_list *instructions)
-{
- ir_dead_functions_visitor v;
- bool progress = false;
-
- visit_list_elements(&v, instructions);
-
- /* Now that we've figured out which function signatures are used, remove
- * the unused ones, and remove function definitions that have no more
- * signatures.
- */
- foreach_iter(exec_list_iterator, iter, v.signature_list) {
- signature_entry *entry = (signature_entry *)iter.get();
-
- if (!entry->used) {
- entry->signature->remove();
- delete entry->signature;
- progress = true;
- }
- delete(entry);
- }
-
- /* We don't just do this above when we nuked a signature because of
- * const pointers.
- */
- foreach_iter(exec_list_iterator, iter, *instructions) {
- ir_instruction *ir = (ir_instruction *)iter.get();
- ir_function *func = ir->as_function();
-
- if (func && func->signatures.is_empty()) {
- /* At this point (post-linking), the symbol table is no
- * longer in use, so not removing the function from the
- * symbol table should be OK.
- */
- func->remove();
- delete func;
- progress = true;
- }
- }
-
- return progress;
-}
+ /*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_dead_functions.cpp
+ *
+ * Eliminates unused functions from the linked program.
+ */
+
+ #include "ir.h"
+ #include "ir_visitor.h"
+ #include "ir_expression_flattening.h"
+ #include "glsl_types.h"
+
+ class signature_entry : public exec_node
+ {
+ public:
+ signature_entry(ir_function_signature *sig)
+ {
+ this->signature = sig;
+ this->used = false;
+ }
+
+ ir_function_signature *signature;
+ bool used;
+ };
+
+ class ir_dead_functions_visitor : public ir_hierarchical_visitor {
+ public:
+ ir_dead_functions_visitor()
+ {
+ this->mem_ctx = ralloc_context(NULL);
+ }
+
+ ~ir_dead_functions_visitor()
+ {
+ ralloc_free(this->mem_ctx);
+ }
+
+ virtual ir_visitor_status visit_enter(ir_function_signature *);
+ virtual ir_visitor_status visit_enter(ir_call *);
+
+ signature_entry *get_signature_entry(ir_function_signature *var);
+
+ bool (*predicate)(ir_instruction *ir);
+
+ /* List of signature_entry */
+ exec_list signature_list;
+ void *mem_ctx;
+ };
+
+
+ signature_entry *
+ ir_dead_functions_visitor::get_signature_entry(ir_function_signature *sig)
+ {
+ foreach_iter(exec_list_iterator, iter, this->signature_list) {
+ signature_entry *entry = (signature_entry *)iter.get();
+ if (entry->signature == sig)
+ return entry;
+ }
+
+ signature_entry *entry = new(mem_ctx) signature_entry(sig);
+ this->signature_list.push_tail(entry);
+ return entry;
+ }
+
+
+ ir_visitor_status
+ ir_dead_functions_visitor::visit_enter(ir_function_signature *ir)
+ {
+ signature_entry *entry = this->get_signature_entry(ir);
+
+ if (strcmp(ir->function_name(), "main") == 0) {
+ entry->used = true;
+ }
+
+ return visit_continue;
+ }
+
+
+ ir_visitor_status
+ ir_dead_functions_visitor::visit_enter(ir_call *ir)
+ {
+ signature_entry *entry = this->get_signature_entry(ir->get_callee());
+
+ entry->used = true;
+
+ return visit_continue;
+}
+
+bool
+do_dead_functions(exec_list *instructions)
+{
+ ir_dead_functions_visitor v;
+ bool progress = false;
+
+ visit_list_elements(&v, instructions);
+
+ /* Now that we've figured out which function signatures are used, remove
+ * the unused ones, and remove function definitions that have no more
+ * signatures.
+ */
+ foreach_iter(exec_list_iterator, iter, v.signature_list) {
+ signature_entry *entry = (signature_entry *)iter.get();
+
+ if (!entry->used) {
+ entry->signature->remove();
+ delete entry->signature;
+ progress = true;
+ }
+ delete(entry);
+ }
+
+ /* We don't just do this above when we nuked a signature because of
+ * const pointers.
+ */
+ foreach_iter(exec_list_iterator, iter, *instructions) {
+ ir_instruction *ir = (ir_instruction *)iter.get();
+ ir_function *func = ir->as_function();
+
+ if (func && func->signatures.is_empty()) {
+ /* At this point (post-linking), the symbol table is no
+ * longer in use, so not removing the function from the
+ * symbol table should be OK.
+ */
+ func->remove();
+ delete func;
+ progress = true;
+ }
+ }
+
+ return progress;
+}
diff --git a/mesalib/src/glsl/opt_structure_splitting.cpp b/mesalib/src/glsl/opt_structure_splitting.cpp
index 014407c0b..ec2315499 100644
--- a/mesalib/src/glsl/opt_structure_splitting.cpp
+++ b/mesalib/src/glsl/opt_structure_splitting.cpp
@@ -1,361 +1,361 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_structure_splitting.cpp
- *
- * If a structure is only ever referenced by its components, then
- * split those components out to individual variables so they can be
- * handled normally by other optimization passes.
- *
- * This skips structures like uniforms, which need to be accessible as
- * structures for their access by the GL.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_print_visitor.h"
-#include "ir_rvalue_visitor.h"
-#include "glsl_types.h"
-
-static bool debug = false;
-
-// XXX using variable_entry2 here to avoid collision (MSVC multiply-defined
-// function) with the variable_entry class seen in ir_variable_refcount.h
-// Perhaps we can use the one in ir_variable_refcount.h and make this class
-// here go away?
-class variable_entry2 : public exec_node
-{
-public:
- variable_entry2(ir_variable *var)
- {
- this->var = var;
- this->whole_structure_access = 0;
- this->declaration = false;
- this->components = NULL;
- this->mem_ctx = NULL;
- }
-
- ir_variable *var; /* The key: the variable's pointer. */
-
- /** Number of times the variable is referenced, including assignments. */
- unsigned whole_structure_access;
-
- bool declaration; /* If the variable had a decl in the instruction stream */
-
- ir_variable **components;
-
- /** ralloc_parent(this->var) -- the shader's ralloc context. */
- void *mem_ctx;
-};
-
-
-class ir_structure_reference_visitor : public ir_hierarchical_visitor {
-public:
- ir_structure_reference_visitor(void)
- {
- this->mem_ctx = ralloc_context(NULL);
- this->variable_list.make_empty();
- }
-
- ~ir_structure_reference_visitor(void)
- {
- ralloc_free(mem_ctx);
- }
-
- virtual ir_visitor_status visit(ir_variable *);
- virtual ir_visitor_status visit(ir_dereference_variable *);
- virtual ir_visitor_status visit_enter(ir_dereference_record *);
- virtual ir_visitor_status visit_enter(ir_assignment *);
- virtual ir_visitor_status visit_enter(ir_function_signature *);
-
- variable_entry2 *get_variable_entry2(ir_variable *var);
-
- /* List of variable_entry */
- exec_list variable_list;
-
- void *mem_ctx;
-};
-
-variable_entry2 *
-ir_structure_reference_visitor::get_variable_entry2(ir_variable *var)
-{
- assert(var);
-
- if (!var->type->is_record() || var->mode == ir_var_uniform)
- return NULL;
-
- foreach_iter(exec_list_iterator, iter, this->variable_list) {
- variable_entry2 *entry = (variable_entry2 *)iter.get();
- if (entry->var == var)
- return entry;
- }
-
- variable_entry2 *entry = new(mem_ctx) variable_entry2(var);
- this->variable_list.push_tail(entry);
- return entry;
-}
-
-
-ir_visitor_status
-ir_structure_reference_visitor::visit(ir_variable *ir)
-{
- variable_entry2 *entry = this->get_variable_entry2(ir);
-
- if (entry)
- entry->declaration = true;
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
-{
- ir_variable *const var = ir->variable_referenced();
- variable_entry2 *entry = this->get_variable_entry2(var);
-
- if (entry)
- entry->whole_structure_access++;
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
-{
- (void) ir;
- /* Don't descend into the ir_dereference_variable below. */
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
-{
- if (ir->lhs->as_dereference_variable() &&
- ir->rhs->as_dereference_variable() &&
- !ir->condition) {
- /* We'll split copies of a structure to copies of components, so don't
- * descend to the ir_dereference_variables.
- */
- return visit_continue_with_parent;
- }
- return visit_continue;
-}
-
-ir_visitor_status
-ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
-{
- /* We don't want to descend into the function parameters and
- * dead-code eliminate them, so just accept the body here.
- */
- visit_list_elements(this, &ir->body);
- return visit_continue_with_parent;
-}
-
-class ir_structure_splitting_visitor : public ir_rvalue_visitor {
-public:
- ir_structure_splitting_visitor(exec_list *vars)
- {
- this->variable_list = vars;
- }
-
- virtual ~ir_structure_splitting_visitor()
- {
- }
-
- virtual ir_visitor_status visit_leave(ir_assignment *);
-
- void split_deref(ir_dereference **deref);
- void handle_rvalue(ir_rvalue **rvalue);
- variable_entry2 *get_splitting_entry(ir_variable *var);
-
- exec_list *variable_list;
- void *mem_ctx;
-};
-
-variable_entry2 *
-ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
-{
- assert(var);
-
- if (!var->type->is_record())
- return NULL;
-
- foreach_iter(exec_list_iterator, iter, *this->variable_list) {
- variable_entry2 *entry = (variable_entry2 *)iter.get();
- if (entry->var == var) {
- return entry;
- }
- }
-
- return NULL;
-}
-
-void
-ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
-{
- if ((*deref)->ir_type != ir_type_dereference_record)
- return;
-
- ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
- ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
- if (!deref_var)
- return;
-
- variable_entry2 *entry = get_splitting_entry(deref_var->var);
- if (!entry)
- return;
-
- unsigned int i;
- for (i = 0; i < entry->var->type->length; i++) {
- if (strcmp(deref_record->field,
- entry->var->type->fields.structure[i].name) == 0)
- break;
- }
- assert(i != entry->var->type->length);
-
- *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
-}
-
-void
-ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
-{
- if (!*rvalue)
- return;
-
- ir_dereference *deref = (*rvalue)->as_dereference();
-
- if (!deref)
- return;
-
- split_deref(&deref);
- *rvalue = deref;
-}
-
-ir_visitor_status
-ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
-{
- ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
- ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
- variable_entry2 *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
- variable_entry2 *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
- const glsl_type *type = ir->rhs->type;
-
- if ((lhs_entry || rhs_entry) && !ir->condition) {
- for (unsigned int i = 0; i < type->length; i++) {
- ir_dereference *new_lhs, *new_rhs;
- void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;
-
- if (lhs_entry) {
- new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
- } else {
- new_lhs = new(mem_ctx)
- ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
- type->fields.structure[i].name);
- }
-
- if (rhs_entry) {
- new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
- } else {
- new_rhs = new(mem_ctx)
- ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
- type->fields.structure[i].name);
- }
-
- ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
- new_rhs,
- NULL));
- }
- ir->remove();
- } else {
- handle_rvalue(&ir->rhs);
- split_deref(&ir->lhs);
- }
-
- handle_rvalue(&ir->condition);
-
- return visit_continue;
-}
-
-bool
-do_structure_splitting(exec_list *instructions)
-{
- ir_structure_reference_visitor refs;
-
- visit_list_elements(&refs, instructions);
-
- /* Trim out variables we can't split. */
- foreach_iter(exec_list_iterator, iter, refs.variable_list) {
- variable_entry2 *entry = (variable_entry2 *)iter.get();
-
- if (debug) {
- printf("structure %s@%p: decl %d, whole_access %d\n",
- entry->var->name, (void *) entry->var, entry->declaration,
- entry->whole_structure_access);
- }
-
- if (!entry->declaration || entry->whole_structure_access) {
- entry->remove();
- }
- }
-
- if (refs.variable_list.is_empty())
- return false;
-
- void *mem_ctx = ralloc_context(NULL);
-
- /* Replace the decls of the structures to be split with their split
- * components.
- */
- foreach_iter(exec_list_iterator, iter, refs.variable_list) {
- variable_entry2 *entry = (variable_entry2 *)iter.get();
- const struct glsl_type *type = entry->var->type;
-
- entry->mem_ctx = ralloc_parent(entry->var);
-
- entry->components = ralloc_array(mem_ctx,
- ir_variable *,
- type->length);
-
- for (unsigned int i = 0; i < entry->var->type->length; i++) {
- const char *name = ralloc_asprintf(mem_ctx, "%s_%s",
- entry->var->name,
- type->fields.structure[i].name);
-
- entry->components[i] =
- new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
- name,
- ir_var_temporary);
- entry->var->insert_before(entry->components[i]);
- }
-
- entry->var->remove();
- }
-
- ir_structure_splitting_visitor split(&refs.variable_list);
- visit_list_elements(&split, instructions);
-
- ralloc_free(mem_ctx);
-
- return true;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_structure_splitting.cpp
+ *
+ * If a structure is only ever referenced by its components, then
+ * split those components out to individual variables so they can be
+ * handled normally by other optimization passes.
+ *
+ * This skips structures like uniforms, which need to be accessible as
+ * structures for their access by the GL.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_print_visitor.h"
+#include "ir_rvalue_visitor.h"
+#include "glsl_types.h"
+
+static bool debug = false;
+
+// XXX using variable_entry2 here to avoid collision (MSVC multiply-defined
+// function) with the variable_entry class seen in ir_variable_refcount.h
+// Perhaps we can use the one in ir_variable_refcount.h and make this class
+// here go away?
+class variable_entry2 : public exec_node
+{
+public:
+ variable_entry2(ir_variable *var)
+ {
+ this->var = var;
+ this->whole_structure_access = 0;
+ this->declaration = false;
+ this->components = NULL;
+ this->mem_ctx = NULL;
+ }
+
+ ir_variable *var; /* The key: the variable's pointer. */
+
+ /** Number of times the variable is referenced, including assignments. */
+ unsigned whole_structure_access;
+
+ bool declaration; /* If the variable had a decl in the instruction stream */
+
+ ir_variable **components;
+
+ /** ralloc_parent(this->var) -- the shader's ralloc context. */
+ void *mem_ctx;
+};
+
+
+class ir_structure_reference_visitor : public ir_hierarchical_visitor {
+public:
+ ir_structure_reference_visitor(void)
+ {
+ this->mem_ctx = ralloc_context(NULL);
+ this->variable_list.make_empty();
+ }
+
+ ~ir_structure_reference_visitor(void)
+ {
+ ralloc_free(mem_ctx);
+ }
+
+ virtual ir_visitor_status visit(ir_variable *);
+ virtual ir_visitor_status visit(ir_dereference_variable *);
+ virtual ir_visitor_status visit_enter(ir_dereference_record *);
+ virtual ir_visitor_status visit_enter(ir_assignment *);
+ virtual ir_visitor_status visit_enter(ir_function_signature *);
+
+ variable_entry2 *get_variable_entry2(ir_variable *var);
+
+ /* List of variable_entry */
+ exec_list variable_list;
+
+ void *mem_ctx;
+};
+
+variable_entry2 *
+ir_structure_reference_visitor::get_variable_entry2(ir_variable *var)
+{
+ assert(var);
+
+ if (!var->type->is_record() || var->mode == ir_var_uniform)
+ return NULL;
+
+ foreach_iter(exec_list_iterator, iter, this->variable_list) {
+ variable_entry2 *entry = (variable_entry2 *)iter.get();
+ if (entry->var == var)
+ return entry;
+ }
+
+ variable_entry2 *entry = new(mem_ctx) variable_entry2(var);
+ this->variable_list.push_tail(entry);
+ return entry;
+}
+
+
+ir_visitor_status
+ir_structure_reference_visitor::visit(ir_variable *ir)
+{
+ variable_entry2 *entry = this->get_variable_entry2(ir);
+
+ if (entry)
+ entry->declaration = true;
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
+{
+ ir_variable *const var = ir->variable_referenced();
+ variable_entry2 *entry = this->get_variable_entry2(var);
+
+ if (entry)
+ entry->whole_structure_access++;
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
+{
+ (void) ir;
+ /* Don't descend into the ir_dereference_variable below. */
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
+{
+ if (ir->lhs->as_dereference_variable() &&
+ ir->rhs->as_dereference_variable() &&
+ !ir->condition) {
+ /* We'll split copies of a structure to copies of components, so don't
+ * descend to the ir_dereference_variables.
+ */
+ return visit_continue_with_parent;
+ }
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
+{
+ /* We don't want to descend into the function parameters and
+ * dead-code eliminate them, so just accept the body here.
+ */
+ visit_list_elements(this, &ir->body);
+ return visit_continue_with_parent;
+}
+
+class ir_structure_splitting_visitor : public ir_rvalue_visitor {
+public:
+ ir_structure_splitting_visitor(exec_list *vars)
+ {
+ this->variable_list = vars;
+ }
+
+ virtual ~ir_structure_splitting_visitor()
+ {
+ }
+
+ virtual ir_visitor_status visit_leave(ir_assignment *);
+
+ void split_deref(ir_dereference **deref);
+ void handle_rvalue(ir_rvalue **rvalue);
+ variable_entry2 *get_splitting_entry(ir_variable *var);
+
+ exec_list *variable_list;
+ void *mem_ctx;
+};
+
+variable_entry2 *
+ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
+{
+ assert(var);
+
+ if (!var->type->is_record())
+ return NULL;
+
+ foreach_iter(exec_list_iterator, iter, *this->variable_list) {
+ variable_entry2 *entry = (variable_entry2 *)iter.get();
+ if (entry->var == var) {
+ return entry;
+ }
+ }
+
+ return NULL;
+}
+
+void
+ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
+{
+ if ((*deref)->ir_type != ir_type_dereference_record)
+ return;
+
+ ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
+ ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
+ if (!deref_var)
+ return;
+
+ variable_entry2 *entry = get_splitting_entry(deref_var->var);
+ if (!entry)
+ return;
+
+ unsigned int i;
+ for (i = 0; i < entry->var->type->length; i++) {
+ if (strcmp(deref_record->field,
+ entry->var->type->fields.structure[i].name) == 0)
+ break;
+ }
+ assert(i != entry->var->type->length);
+
+ *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
+}
+
+void
+ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
+{
+ if (!*rvalue)
+ return;
+
+ ir_dereference *deref = (*rvalue)->as_dereference();
+
+ if (!deref)
+ return;
+
+ split_deref(&deref);
+ *rvalue = deref;
+}
+
+ir_visitor_status
+ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
+{
+ ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
+ ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
+ variable_entry2 *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
+ variable_entry2 *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
+ const glsl_type *type = ir->rhs->type;
+
+ if ((lhs_entry || rhs_entry) && !ir->condition) {
+ for (unsigned int i = 0; i < type->length; i++) {
+ ir_dereference *new_lhs, *new_rhs;
+ void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;
+
+ if (lhs_entry) {
+ new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
+ } else {
+ new_lhs = new(mem_ctx)
+ ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
+ type->fields.structure[i].name);
+ }
+
+ if (rhs_entry) {
+ new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
+ } else {
+ new_rhs = new(mem_ctx)
+ ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
+ type->fields.structure[i].name);
+ }
+
+ ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
+ new_rhs,
+ NULL));
+ }
+ ir->remove();
+ } else {
+ handle_rvalue(&ir->rhs);
+ split_deref(&ir->lhs);
+ }
+
+ handle_rvalue(&ir->condition);
+
+ return visit_continue;
+}
+
+bool
+do_structure_splitting(exec_list *instructions)
+{
+ ir_structure_reference_visitor refs;
+
+ visit_list_elements(&refs, instructions);
+
+ /* Trim out variables we can't split. */
+ foreach_iter(exec_list_iterator, iter, refs.variable_list) {
+ variable_entry2 *entry = (variable_entry2 *)iter.get();
+
+ if (debug) {
+ printf("structure %s@%p: decl %d, whole_access %d\n",
+ entry->var->name, (void *) entry->var, entry->declaration,
+ entry->whole_structure_access);
+ }
+
+ if (!entry->declaration || entry->whole_structure_access) {
+ entry->remove();
+ }
+ }
+
+ if (refs.variable_list.is_empty())
+ return false;
+
+ void *mem_ctx = ralloc_context(NULL);
+
+ /* Replace the decls of the structures to be split with their split
+ * components.
+ */
+ foreach_iter(exec_list_iterator, iter, refs.variable_list) {
+ variable_entry2 *entry = (variable_entry2 *)iter.get();
+ const struct glsl_type *type = entry->var->type;
+
+ entry->mem_ctx = ralloc_parent(entry->var);
+
+ entry->components = ralloc_array(mem_ctx,
+ ir_variable *,
+ type->length);
+
+ for (unsigned int i = 0; i < entry->var->type->length; i++) {
+ const char *name = ralloc_asprintf(mem_ctx, "%s_%s",
+ entry->var->name,
+ type->fields.structure[i].name);
+
+ entry->components[i] =
+ new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
+ name,
+ ir_var_temporary);
+ entry->var->insert_before(entry->components[i]);
+ }
+
+ entry->var->remove();
+ }
+
+ ir_structure_splitting_visitor split(&refs.variable_list);
+ visit_list_elements(&split, instructions);
+
+ ralloc_free(mem_ctx);
+
+ return true;
+}
diff --git a/mesalib/src/glsl/opt_swizzle_swizzle.cpp b/mesalib/src/glsl/opt_swizzle_swizzle.cpp
index bc442fa86..e23655240 100644
--- a/mesalib/src/glsl/opt_swizzle_swizzle.cpp
+++ b/mesalib/src/glsl/opt_swizzle_swizzle.cpp
@@ -1,93 +1,93 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_swizzle_swizzle.cpp
- *
- * Eliminates the second swizzle in a swizzle chain.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_optimization.h"
-#include "glsl_types.h"
-
-class ir_swizzle_swizzle_visitor : public ir_hierarchical_visitor {
-public:
- ir_swizzle_swizzle_visitor()
- {
- progress = false;
- }
-
- virtual ir_visitor_status visit_enter(ir_swizzle *);
-
- bool progress;
-};
-
-ir_visitor_status
-ir_swizzle_swizzle_visitor::visit_enter(ir_swizzle *ir)
-{
- int mask2[4];
-
- ir_swizzle *swiz2 = ir->val->as_swizzle();
- if (!swiz2)
- return visit_continue;
-
- memset(&mask2, 0, sizeof(mask2));
- if (swiz2->mask.num_components >= 1)
- mask2[0] = swiz2->mask.x;
- if (swiz2->mask.num_components >= 2)
- mask2[1] = swiz2->mask.y;
- if (swiz2->mask.num_components >= 3)
- mask2[2] = swiz2->mask.z;
- if (swiz2->mask.num_components >= 4)
- mask2[3] = swiz2->mask.w;
-
- if (ir->mask.num_components >= 1)
- ir->mask.x = mask2[ir->mask.x];
- if (ir->mask.num_components >= 2)
- ir->mask.y = mask2[ir->mask.y];
- if (ir->mask.num_components >= 3)
- ir->mask.z = mask2[ir->mask.z];
- if (ir->mask.num_components >= 4)
- ir->mask.w = mask2[ir->mask.w];
-
- ir->val = swiz2->val;
-
- this->progress = true;
-
- return visit_continue;
-}
-
-/**
- * Does a copy propagation pass on the code present in the instruction stream.
- */
-bool
-do_swizzle_swizzle(exec_list *instructions)
-{
- ir_swizzle_swizzle_visitor v;
-
- v.run(instructions);
-
- return v.progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_swizzle_swizzle.cpp
+ *
+ * Eliminates the second swizzle in a swizzle chain.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_optimization.h"
+#include "glsl_types.h"
+
+class ir_swizzle_swizzle_visitor : public ir_hierarchical_visitor {
+public:
+ ir_swizzle_swizzle_visitor()
+ {
+ progress = false;
+ }
+
+ virtual ir_visitor_status visit_enter(ir_swizzle *);
+
+ bool progress;
+};
+
+ir_visitor_status
+ir_swizzle_swizzle_visitor::visit_enter(ir_swizzle *ir)
+{
+ int mask2[4];
+
+ ir_swizzle *swiz2 = ir->val->as_swizzle();
+ if (!swiz2)
+ return visit_continue;
+
+ memset(&mask2, 0, sizeof(mask2));
+ if (swiz2->mask.num_components >= 1)
+ mask2[0] = swiz2->mask.x;
+ if (swiz2->mask.num_components >= 2)
+ mask2[1] = swiz2->mask.y;
+ if (swiz2->mask.num_components >= 3)
+ mask2[2] = swiz2->mask.z;
+ if (swiz2->mask.num_components >= 4)
+ mask2[3] = swiz2->mask.w;
+
+ if (ir->mask.num_components >= 1)
+ ir->mask.x = mask2[ir->mask.x];
+ if (ir->mask.num_components >= 2)
+ ir->mask.y = mask2[ir->mask.y];
+ if (ir->mask.num_components >= 3)
+ ir->mask.z = mask2[ir->mask.z];
+ if (ir->mask.num_components >= 4)
+ ir->mask.w = mask2[ir->mask.w];
+
+ ir->val = swiz2->val;
+
+ this->progress = true;
+
+ return visit_continue;
+}
+
+/**
+ * Does a copy propagation pass on the code present in the instruction stream.
+ */
+bool
+do_swizzle_swizzle(exec_list *instructions)
+{
+ ir_swizzle_swizzle_visitor v;
+
+ v.run(instructions);
+
+ return v.progress;
+}
diff --git a/mesalib/src/glsl/opt_tree_grafting.cpp b/mesalib/src/glsl/opt_tree_grafting.cpp
index 1ef940f9c..75bd11c09 100644
--- a/mesalib/src/glsl/opt_tree_grafting.cpp
+++ b/mesalib/src/glsl/opt_tree_grafting.cpp
@@ -1,368 +1,368 @@
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_tree_grafting.cpp
- *
- * Takes assignments to variables that are dereferenced only once and
- * pastes the RHS expression into where the variable is dereferenced.
- *
- * In the process of various operations like function inlining and
- * tertiary op handling, we'll end up with our expression trees having
- * been chopped up into a series of assignments of short expressions
- * to temps. Other passes like ir_algebraic.cpp would prefer to see
- * the deepest expression trees they can to try to optimize them.
- *
- * This is a lot like copy propagaton. In comparison, copy
- * propagation only acts on plain copies, not arbitrary expressions on
- * the RHS. Generally, we wouldn't want to go pasting some
- * complicated expression everywhere it got used, though, so we don't
- * handle expressions in that pass.
- *
- * The hard part is making sure we don't move an expression across
- * some other assignments that would change the value of the
- * expression. So we split this into two passes: First, find the
- * variables in our scope which are written to once and read once, and
- * then go through basic blocks seeing if we find an opportunity to
- * move those expressions safely.
- */
-
-#include "ir.h"
-#include "ir_visitor.h"
-#include "ir_variable_refcount.h"
-#include "ir_basic_block.h"
-#include "ir_optimization.h"
-#include "glsl_types.h"
-
-static bool debug = false;
-
-class ir_tree_grafting_visitor : public ir_hierarchical_visitor {
-public:
- ir_tree_grafting_visitor(ir_assignment *graft_assign,
- ir_variable *graft_var)
- {
- this->progress = false;
- this->graft_assign = graft_assign;
- this->graft_var = graft_var;
- }
-
- virtual ir_visitor_status visit_leave(class ir_assignment *);
- virtual ir_visitor_status visit_enter(class ir_call *);
- virtual ir_visitor_status visit_enter(class ir_expression *);
- virtual ir_visitor_status visit_enter(class ir_function *);
- virtual ir_visitor_status visit_enter(class ir_function_signature *);
- virtual ir_visitor_status visit_enter(class ir_if *);
- virtual ir_visitor_status visit_enter(class ir_loop *);
- virtual ir_visitor_status visit_enter(class ir_swizzle *);
- virtual ir_visitor_status visit_enter(class ir_texture *);
-
- bool do_graft(ir_rvalue **rvalue);
-
- bool progress;
- ir_variable *graft_var;
- ir_assignment *graft_assign;
-};
-
-struct find_deref_info {
- ir_variable *var;
- bool found;
-};
-
-void
-dereferences_variable_callback(ir_instruction *ir, void *data)
-{
- struct find_deref_info *info = (struct find_deref_info *)data;
- ir_dereference_variable *deref = ir->as_dereference_variable();
-
- if (deref && deref->var == info->var)
- info->found = true;
-}
-
-static bool
-dereferences_variable(ir_instruction *ir, ir_variable *var)
-{
- struct find_deref_info info;
-
- info.var = var;
- info.found = false;
-
- visit_tree(ir, dereferences_variable_callback, &info);
-
- return info.found;
-}
-
-bool
-ir_tree_grafting_visitor::do_graft(ir_rvalue **rvalue)
-{
- if (!*rvalue)
- return false;
-
- ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
-
- if (!deref || deref->var != this->graft_var)
- return false;
-
- if (debug) {
- printf("GRAFTING:\n");
- this->graft_assign->print();
- printf("\n");
- printf("TO:\n");
- (*rvalue)->print();
- printf("\n");
- }
-
- this->graft_assign->remove();
- *rvalue = this->graft_assign->rhs;
-
- this->progress = true;
- return true;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_loop *ir)
-{
- (void)ir;
- /* Do not traverse into the body of the loop since that is a
- * different basic block.
- */
- return visit_stop;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_leave(ir_assignment *ir)
-{
- if (do_graft(&ir->rhs) ||
- do_graft(&ir->condition))
- return visit_stop;
-
- /* If this assignment updates a variable used in the assignment
- * we're trying to graft, then we're done.
- */
- if (dereferences_variable(this->graft_assign->rhs,
- ir->lhs->variable_referenced())) {
- if (debug) {
- printf("graft killed by: ");
- ir->print();
- printf("\n");
- }
- return visit_stop;
- }
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_function *ir)
-{
- (void) ir;
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_function_signature *ir)
-{
- (void)ir;
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_call *ir)
-{
- exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
- /* Reminder: iterating ir_call iterates its parameters. */
- foreach_iter(exec_list_iterator, iter, *ir) {
- ir_variable *sig_param = (ir_variable *)sig_iter.get();
- ir_rvalue *ir = (ir_rvalue *)iter.get();
- ir_rvalue *new_ir = ir;
-
- if (sig_param->mode != ir_var_in && sig_param->mode != ir_var_const_in)
- continue;
-
- if (do_graft(&new_ir)) {
- ir->replace_with(new_ir);
- return visit_stop;
- }
- sig_iter.next();
- }
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_expression *ir)
-{
- for (unsigned int i = 0; i < ir->get_num_operands(); i++) {
- if (do_graft(&ir->operands[i]))
- return visit_stop;
- }
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_if *ir)
-{
- if (do_graft(&ir->condition))
- return visit_stop;
-
- /* Do not traverse into the body of the if-statement since that is a
- * different basic block.
- */
- return visit_continue_with_parent;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_swizzle *ir)
-{
- if (do_graft(&ir->val))
- return visit_stop;
-
- return visit_continue;
-}
-
-ir_visitor_status
-ir_tree_grafting_visitor::visit_enter(ir_texture *ir)
-{
- if (do_graft(&ir->coordinate) ||
- do_graft(&ir->projector) ||
- do_graft(&ir->offset) ||
- do_graft(&ir->shadow_comparitor))
- return visit_stop;
-
- switch (ir->op) {
- case ir_tex:
- break;
- case ir_txb:
- if (do_graft(&ir->lod_info.bias))
- return visit_stop;
- break;
- case ir_txf:
- case ir_txl:
- if (do_graft(&ir->lod_info.lod))
- return visit_stop;
- break;
- case ir_txd:
- if (do_graft(&ir->lod_info.grad.dPdx) ||
- do_graft(&ir->lod_info.grad.dPdy))
- return visit_stop;
- break;
- }
-
- return visit_continue;
-}
-
-struct tree_grafting_info {
- ir_variable_refcount_visitor *refs;
- bool progress;
-};
-
-static bool
-try_tree_grafting(ir_assignment *start,
- ir_variable *lhs_var,
- ir_instruction *bb_last)
-{
- ir_tree_grafting_visitor v(start, lhs_var);
-
- if (debug) {
- printf("trying to graft: ");
- lhs_var->print();
- printf("\n");
- }
-
- for (ir_instruction *ir = (ir_instruction *)start->next;
- ir != bb_last->next;
- ir = (ir_instruction *)ir->next) {
-
- if (debug) {
- printf("- ");
- ir->print();
- printf("\n");
- }
-
- ir_visitor_status s = ir->accept(&v);
- if (s == visit_stop)
- return v.progress;
- }
-
- return false;
-}
-
-static void
-tree_grafting_basic_block(ir_instruction *bb_first,
- ir_instruction *bb_last,
- void *data)
-{
- struct tree_grafting_info *info = (struct tree_grafting_info *)data;
- ir_instruction *ir, *next;
-
- for (ir = bb_first, next = (ir_instruction *)ir->next;
- ir != bb_last->next;
- ir = next, next = (ir_instruction *)ir->next) {
- ir_assignment *assign = ir->as_assignment();
-
- if (!assign)
- continue;
-
- ir_variable *lhs_var = assign->whole_variable_written();
- if (!lhs_var)
- continue;
-
- if (lhs_var->mode == ir_var_out ||
- lhs_var->mode == ir_var_inout)
- continue;
-
- variable_entry *entry = info->refs->get_variable_entry(lhs_var);
-
- if (!entry->declaration ||
- entry->assigned_count != 1 ||
- entry->referenced_count != 2)
- continue;
-
- assert(assign == entry->assign);
-
- /* Found a possibly graftable assignment. Now, walk through the
- * rest of the BB seeing if the deref is here, and if nothing interfered with
- * pasting its expression's values in between.
- */
- info->progress |= try_tree_grafting(assign, lhs_var, bb_last);
- }
-}
-
-/**
- * Does a copy propagation pass on the code present in the instruction stream.
- */
-bool
-do_tree_grafting(exec_list *instructions)
-{
- ir_variable_refcount_visitor refs;
- struct tree_grafting_info info;
-
- info.progress = false;
- info.refs = &refs;
-
- visit_list_elements(info.refs, instructions);
-
- call_for_basic_blocks(instructions, tree_grafting_basic_block, &info);
-
- return info.progress;
-}
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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 opt_tree_grafting.cpp
+ *
+ * Takes assignments to variables that are dereferenced only once and
+ * pastes the RHS expression into where the variable is dereferenced.
+ *
+ * In the process of various operations like function inlining and
+ * tertiary op handling, we'll end up with our expression trees having
+ * been chopped up into a series of assignments of short expressions
+ * to temps. Other passes like ir_algebraic.cpp would prefer to see
+ * the deepest expression trees they can to try to optimize them.
+ *
+ * This is a lot like copy propagaton. In comparison, copy
+ * propagation only acts on plain copies, not arbitrary expressions on
+ * the RHS. Generally, we wouldn't want to go pasting some
+ * complicated expression everywhere it got used, though, so we don't
+ * handle expressions in that pass.
+ *
+ * The hard part is making sure we don't move an expression across
+ * some other assignments that would change the value of the
+ * expression. So we split this into two passes: First, find the
+ * variables in our scope which are written to once and read once, and
+ * then go through basic blocks seeing if we find an opportunity to
+ * move those expressions safely.
+ */
+
+#include "ir.h"
+#include "ir_visitor.h"
+#include "ir_variable_refcount.h"
+#include "ir_basic_block.h"
+#include "ir_optimization.h"
+#include "glsl_types.h"
+
+static bool debug = false;
+
+class ir_tree_grafting_visitor : public ir_hierarchical_visitor {
+public:
+ ir_tree_grafting_visitor(ir_assignment *graft_assign,
+ ir_variable *graft_var)
+ {
+ this->progress = false;
+ this->graft_assign = graft_assign;
+ this->graft_var = graft_var;
+ }
+
+ virtual ir_visitor_status visit_leave(class ir_assignment *);
+ virtual ir_visitor_status visit_enter(class ir_call *);
+ virtual ir_visitor_status visit_enter(class ir_expression *);
+ virtual ir_visitor_status visit_enter(class ir_function *);
+ virtual ir_visitor_status visit_enter(class ir_function_signature *);
+ virtual ir_visitor_status visit_enter(class ir_if *);
+ virtual ir_visitor_status visit_enter(class ir_loop *);
+ virtual ir_visitor_status visit_enter(class ir_swizzle *);
+ virtual ir_visitor_status visit_enter(class ir_texture *);
+
+ bool do_graft(ir_rvalue **rvalue);
+
+ bool progress;
+ ir_variable *graft_var;
+ ir_assignment *graft_assign;
+};
+
+struct find_deref_info {
+ ir_variable *var;
+ bool found;
+};
+
+void
+dereferences_variable_callback(ir_instruction *ir, void *data)
+{
+ struct find_deref_info *info = (struct find_deref_info *)data;
+ ir_dereference_variable *deref = ir->as_dereference_variable();
+
+ if (deref && deref->var == info->var)
+ info->found = true;
+}
+
+static bool
+dereferences_variable(ir_instruction *ir, ir_variable *var)
+{
+ struct find_deref_info info;
+
+ info.var = var;
+ info.found = false;
+
+ visit_tree(ir, dereferences_variable_callback, &info);
+
+ return info.found;
+}
+
+bool
+ir_tree_grafting_visitor::do_graft(ir_rvalue **rvalue)
+{
+ if (!*rvalue)
+ return false;
+
+ ir_dereference_variable *deref = (*rvalue)->as_dereference_variable();
+
+ if (!deref || deref->var != this->graft_var)
+ return false;
+
+ if (debug) {
+ printf("GRAFTING:\n");
+ this->graft_assign->print();
+ printf("\n");
+ printf("TO:\n");
+ (*rvalue)->print();
+ printf("\n");
+ }
+
+ this->graft_assign->remove();
+ *rvalue = this->graft_assign->rhs;
+
+ this->progress = true;
+ return true;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_loop *ir)
+{
+ (void)ir;
+ /* Do not traverse into the body of the loop since that is a
+ * different basic block.
+ */
+ return visit_stop;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_leave(ir_assignment *ir)
+{
+ if (do_graft(&ir->rhs) ||
+ do_graft(&ir->condition))
+ return visit_stop;
+
+ /* If this assignment updates a variable used in the assignment
+ * we're trying to graft, then we're done.
+ */
+ if (dereferences_variable(this->graft_assign->rhs,
+ ir->lhs->variable_referenced())) {
+ if (debug) {
+ printf("graft killed by: ");
+ ir->print();
+ printf("\n");
+ }
+ return visit_stop;
+ }
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_function *ir)
+{
+ (void) ir;
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_function_signature *ir)
+{
+ (void)ir;
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_call *ir)
+{
+ exec_list_iterator sig_iter = ir->get_callee()->parameters.iterator();
+ /* Reminder: iterating ir_call iterates its parameters. */
+ foreach_iter(exec_list_iterator, iter, *ir) {
+ ir_variable *sig_param = (ir_variable *)sig_iter.get();
+ ir_rvalue *ir = (ir_rvalue *)iter.get();
+ ir_rvalue *new_ir = ir;
+
+ if (sig_param->mode != ir_var_in && sig_param->mode != ir_var_const_in)
+ continue;
+
+ if (do_graft(&new_ir)) {
+ ir->replace_with(new_ir);
+ return visit_stop;
+ }
+ sig_iter.next();
+ }
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_expression *ir)
+{
+ for (unsigned int i = 0; i < ir->get_num_operands(); i++) {
+ if (do_graft(&ir->operands[i]))
+ return visit_stop;
+ }
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_if *ir)
+{
+ if (do_graft(&ir->condition))
+ return visit_stop;
+
+ /* Do not traverse into the body of the if-statement since that is a
+ * different basic block.
+ */
+ return visit_continue_with_parent;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_swizzle *ir)
+{
+ if (do_graft(&ir->val))
+ return visit_stop;
+
+ return visit_continue;
+}
+
+ir_visitor_status
+ir_tree_grafting_visitor::visit_enter(ir_texture *ir)
+{
+ if (do_graft(&ir->coordinate) ||
+ do_graft(&ir->projector) ||
+ do_graft(&ir->offset) ||
+ do_graft(&ir->shadow_comparitor))
+ return visit_stop;
+
+ switch (ir->op) {
+ case ir_tex:
+ break;
+ case ir_txb:
+ if (do_graft(&ir->lod_info.bias))
+ return visit_stop;
+ break;
+ case ir_txf:
+ case ir_txl:
+ if (do_graft(&ir->lod_info.lod))
+ return visit_stop;
+ break;
+ case ir_txd:
+ if (do_graft(&ir->lod_info.grad.dPdx) ||
+ do_graft(&ir->lod_info.grad.dPdy))
+ return visit_stop;
+ break;
+ }
+
+ return visit_continue;
+}
+
+struct tree_grafting_info {
+ ir_variable_refcount_visitor *refs;
+ bool progress;
+};
+
+static bool
+try_tree_grafting(ir_assignment *start,
+ ir_variable *lhs_var,
+ ir_instruction *bb_last)
+{
+ ir_tree_grafting_visitor v(start, lhs_var);
+
+ if (debug) {
+ printf("trying to graft: ");
+ lhs_var->print();
+ printf("\n");
+ }
+
+ for (ir_instruction *ir = (ir_instruction *)start->next;
+ ir != bb_last->next;
+ ir = (ir_instruction *)ir->next) {
+
+ if (debug) {
+ printf("- ");
+ ir->print();
+ printf("\n");
+ }
+
+ ir_visitor_status s = ir->accept(&v);
+ if (s == visit_stop)
+ return v.progress;
+ }
+
+ return false;
+}
+
+static void
+tree_grafting_basic_block(ir_instruction *bb_first,
+ ir_instruction *bb_last,
+ void *data)
+{
+ struct tree_grafting_info *info = (struct tree_grafting_info *)data;
+ ir_instruction *ir, *next;
+
+ for (ir = bb_first, next = (ir_instruction *)ir->next;
+ ir != bb_last->next;
+ ir = next, next = (ir_instruction *)ir->next) {
+ ir_assignment *assign = ir->as_assignment();
+
+ if (!assign)
+ continue;
+
+ ir_variable *lhs_var = assign->whole_variable_written();
+ if (!lhs_var)
+ continue;
+
+ if (lhs_var->mode == ir_var_out ||
+ lhs_var->mode == ir_var_inout)
+ continue;
+
+ variable_entry *entry = info->refs->get_variable_entry(lhs_var);
+
+ if (!entry->declaration ||
+ entry->assigned_count != 1 ||
+ entry->referenced_count != 2)
+ continue;
+
+ assert(assign == entry->assign);
+
+ /* Found a possibly graftable assignment. Now, walk through the
+ * rest of the BB seeing if the deref is here, and if nothing interfered with
+ * pasting its expression's values in between.
+ */
+ info->progress |= try_tree_grafting(assign, lhs_var, bb_last);
+ }
+}
+
+/**
+ * Does a copy propagation pass on the code present in the instruction stream.
+ */
+bool
+do_tree_grafting(exec_list *instructions)
+{
+ ir_variable_refcount_visitor refs;
+ struct tree_grafting_info info;
+
+ info.progress = false;
+ info.refs = &refs;
+
+ visit_list_elements(info.refs, instructions);
+
+ call_for_basic_blocks(instructions, tree_grafting_basic_block, &info);
+
+ return info.progress;
+}
diff --git a/mesalib/src/glsl/s_expression.cpp b/mesalib/src/glsl/s_expression.cpp
index a922a50d3..b47b014c6 100644
--- a/mesalib/src/glsl/s_expression.cpp
+++ b/mesalib/src/glsl/s_expression.cpp
@@ -1,183 +1,183 @@
-/* -*- c++ -*- */
-/*
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include <assert.h>
-#include "s_expression.h"
-
-s_symbol::s_symbol(const char *tmp, size_t n)
-{
- this->str = ralloc_strndup (this, tmp, n);
- assert(this->str != NULL);
-}
-
-s_list::s_list()
-{
-}
-
-static void
-skip_whitespace(const char *& src)
-{
- src += strspn(src, " \v\t\r\n");
- /* Also skip Scheme-style comments: semi-colon 'til end of line */
- if (src[0] == ';') {
- src += strcspn(src, "\n");
- skip_whitespace(src);
- }
-}
-
-static s_expression *
-read_atom(void *ctx, const char *& src)
-{
- s_expression *expr = NULL;
-
- skip_whitespace(src);
-
- size_t n = strcspn(src, "( \v\t\r\n);");
- if (n == 0)
- return NULL; // no atom
-
- // Check if the atom is a number.
- char *float_end = NULL;
- double f = glsl_strtod(src, &float_end);
- if (float_end != src) {
- char *int_end = NULL;
- int i = strtol(src, &int_end, 10);
- // If strtod matched more characters, it must have a decimal part
- if (float_end > int_end)
- expr = new(ctx) s_float(f);
- else
- expr = new(ctx) s_int(i);
- } else {
- // Not a number; return a symbol.
- expr = new(ctx) s_symbol(src, n);
- }
-
- src += n;
-
- return expr;
-}
-
-s_expression *
-s_expression::read_expression(void *ctx, const char *&src)
-{
- assert(src != NULL);
-
- s_expression *atom = read_atom(ctx, src);
- if (atom != NULL)
- return atom;
-
- skip_whitespace(src);
- if (src[0] == '(') {
- ++src;
-
- s_list *list = new(ctx) s_list;
- s_expression *expr;
-
- while ((expr = read_expression(ctx, src)) != NULL) {
- list->subexpressions.push_tail(expr);
- }
- skip_whitespace(src);
- if (src[0] != ')') {
- printf("Unclosed expression (check your parenthesis).\n");
- return NULL;
- }
- ++src;
- return list;
- }
- return NULL;
-}
-
-void s_int::print()
-{
- printf("%d", this->val);
-}
-
-void s_float::print()
-{
- printf("%f", this->val);
-}
-
-void s_symbol::print()
-{
- printf("%s", this->str);
-}
-
-void s_list::print()
-{
- printf("(");
- foreach_iter(exec_list_iterator, it, this->subexpressions) {
- s_expression *expr = (s_expression*) it.get();
- expr->print();
- if (!expr->next->is_tail_sentinel())
- printf(" ");
- }
- printf(")");
-}
-
-// --------------------------------------------------
-
-bool
-s_pattern::match(s_expression *expr)
-{
- switch (type)
- {
- case EXPR: *p_expr = expr; break;
- case LIST: if (expr->is_list()) *p_list = (s_list *) expr; break;
- case SYMBOL: if (expr->is_symbol()) *p_symbol = (s_symbol *) expr; break;
- case NUMBER: if (expr->is_number()) *p_number = (s_number *) expr; break;
- case INT: if (expr->is_int()) *p_int = (s_int *) expr; break;
- case STRING:
- s_symbol *sym = SX_AS_SYMBOL(expr);
- if (sym != NULL && strcmp(sym->value(), literal) == 0)
- return true;
- return false;
- };
-
- return *p_expr == expr;
-}
-
-bool
-s_match(s_expression *top, unsigned n, s_pattern *pattern, bool partial)
-{
- s_list *list = SX_AS_LIST(top);
- if (list == NULL)
- return false;
-
- unsigned i = 0;
- foreach_iter(exec_list_iterator, it, list->subexpressions) {
- if (i >= n)
- return partial; /* More actual items than the pattern expected */
-
- s_expression *expr = (s_expression *) it.get();
- if (expr == NULL || !pattern[i].match(expr))
- return false;
-
- i++;
- }
-
- if (i < n)
- return false; /* Less actual items than the pattern expected */
-
- return true;
-}
+/* -*- c++ -*- */
+/*
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include <assert.h>
+#include "s_expression.h"
+
+s_symbol::s_symbol(const char *tmp, size_t n)
+{
+ this->str = ralloc_strndup (this, tmp, n);
+ assert(this->str != NULL);
+}
+
+s_list::s_list()
+{
+}
+
+static void
+skip_whitespace(const char *& src)
+{
+ src += strspn(src, " \v\t\r\n");
+ /* Also skip Scheme-style comments: semi-colon 'til end of line */
+ if (src[0] == ';') {
+ src += strcspn(src, "\n");
+ skip_whitespace(src);
+ }
+}
+
+static s_expression *
+read_atom(void *ctx, const char *& src)
+{
+ s_expression *expr = NULL;
+
+ skip_whitespace(src);
+
+ size_t n = strcspn(src, "( \v\t\r\n);");
+ if (n == 0)
+ return NULL; // no atom
+
+ // Check if the atom is a number.
+ char *float_end = NULL;
+ double f = glsl_strtod(src, &float_end);
+ if (float_end != src) {
+ char *int_end = NULL;
+ int i = strtol(src, &int_end, 10);
+ // If strtod matched more characters, it must have a decimal part
+ if (float_end > int_end)
+ expr = new(ctx) s_float(f);
+ else
+ expr = new(ctx) s_int(i);
+ } else {
+ // Not a number; return a symbol.
+ expr = new(ctx) s_symbol(src, n);
+ }
+
+ src += n;
+
+ return expr;
+}
+
+s_expression *
+s_expression::read_expression(void *ctx, const char *&src)
+{
+ assert(src != NULL);
+
+ s_expression *atom = read_atom(ctx, src);
+ if (atom != NULL)
+ return atom;
+
+ skip_whitespace(src);
+ if (src[0] == '(') {
+ ++src;
+
+ s_list *list = new(ctx) s_list;
+ s_expression *expr;
+
+ while ((expr = read_expression(ctx, src)) != NULL) {
+ list->subexpressions.push_tail(expr);
+ }
+ skip_whitespace(src);
+ if (src[0] != ')') {
+ printf("Unclosed expression (check your parenthesis).\n");
+ return NULL;
+ }
+ ++src;
+ return list;
+ }
+ return NULL;
+}
+
+void s_int::print()
+{
+ printf("%d", this->val);
+}
+
+void s_float::print()
+{
+ printf("%f", this->val);
+}
+
+void s_symbol::print()
+{
+ printf("%s", this->str);
+}
+
+void s_list::print()
+{
+ printf("(");
+ foreach_iter(exec_list_iterator, it, this->subexpressions) {
+ s_expression *expr = (s_expression*) it.get();
+ expr->print();
+ if (!expr->next->is_tail_sentinel())
+ printf(" ");
+ }
+ printf(")");
+}
+
+// --------------------------------------------------
+
+bool
+s_pattern::match(s_expression *expr)
+{
+ switch (type)
+ {
+ case EXPR: *p_expr = expr; break;
+ case LIST: if (expr->is_list()) *p_list = (s_list *) expr; break;
+ case SYMBOL: if (expr->is_symbol()) *p_symbol = (s_symbol *) expr; break;
+ case NUMBER: if (expr->is_number()) *p_number = (s_number *) expr; break;
+ case INT: if (expr->is_int()) *p_int = (s_int *) expr; break;
+ case STRING:
+ s_symbol *sym = SX_AS_SYMBOL(expr);
+ if (sym != NULL && strcmp(sym->value(), literal) == 0)
+ return true;
+ return false;
+ };
+
+ return *p_expr == expr;
+}
+
+bool
+s_match(s_expression *top, unsigned n, s_pattern *pattern, bool partial)
+{
+ s_list *list = SX_AS_LIST(top);
+ if (list == NULL)
+ return false;
+
+ unsigned i = 0;
+ foreach_iter(exec_list_iterator, it, list->subexpressions) {
+ if (i >= n)
+ return partial; /* More actual items than the pattern expected */
+
+ s_expression *expr = (s_expression *) it.get();
+ if (expr == NULL || !pattern[i].match(expr))
+ return false;
+
+ i++;
+ }
+
+ if (i < n)
+ return false; /* Less actual items than the pattern expected */
+
+ return true;
+}
diff --git a/mesalib/src/mapi/glapi/gen/gen.bat b/mesalib/src/mapi/glapi/gen/gen.bat
new file mode 100644
index 000000000..2b1826a81
--- /dev/null
+++ b/mesalib/src/mapi/glapi/gen/gen.bat
@@ -0,0 +1,20 @@
+echo on
+glx_server_table.py -f gl_and_glX_API.xml > indirect_table.c
+glx_proto_size.py -m size_h --only-set -h _INDIRECT_SIZE_H_ > indirect_size.h
+glx_proto_size.py -m size_c --only-set > indirect_size.c
+glx_proto_size.py -m size_h --only-get -h _INDIRECT_SIZE_GET_H_ > indirect_size_get.h
+glx_proto_size.py -m size_c --only-get > indirect_size_get.c
+glx_proto_size.py -m reqsize_c > indirect_reqsize.c
+glx_proto_size.py -m reqsize_h --only-get -h _INDIRECT_SIZE_GET_H_ > indirect_reqsize.h
+glx_proto_recv.py -m dispatch_c > indirect_dispatch.c
+glx_proto_recv.py -m dispatch_c -s > indirect_dispatch_swap.c
+glx_proto_recv.py -m dispatch_h -f gl_and_glX_API.xml -s > indirect_dispatch.h
+gl_table.py > glapitable.h
+gl_table.py -m remap_table > dispatch.h
+rem gl_offsets.py > glapioffsets.h
+gl_apitemp.py > glapitemp.h
+gl_procs.py > glprocs.h
+
+glX_proto_send.py -m proto > indirect.c
+glX_proto_send.py -m init_h > indirect.h
+glX_proto_send.py -m init_c > indirect_init.c
diff --git a/mesalib/src/mapi/glapi/gen/gl_API.xml b/mesalib/src/mapi/glapi/gen/gl_API.xml
index 1f12c4234..b792c7815 100644
--- a/mesalib/src/mapi/glapi/gen/gl_API.xml
+++ b/mesalib/src/mapi/glapi/gen/gl_API.xml
@@ -183,18 +183,18 @@
<size name="Get" mode="get"/>
</enum>
<enum name="LIGHT_MODEL_LOCAL_VIEWER" count="1" value="0x0B51">
- <size name="LightModelfv"/>
- <size name="LightModeliv"/>
+ <size name="LightModelfv" mode="get"/>
+ <size name="LightModeliv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="LIGHT_MODEL_TWO_SIDE" count="1" value="0x0B52">
- <size name="LightModelfv"/>
- <size name="LightModeliv"/>
+ <size name="LightModelfv" mode="get"/>
+ <size name="LightModeliv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="LIGHT_MODEL_AMBIENT" count="4" value="0x0B53">
- <size name="LightModelfv"/>
- <size name="LightModeliv"/>
+ <size name="LightModelfv" mode="get"/>
+ <size name="LightModeliv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="SHADE_MODEL" count="1" value="0x0B54">
@@ -213,33 +213,33 @@
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_INDEX" count="1" value="0x0B61">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_DENSITY" count="1" value="0x0B62">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_START" count="1" value="0x0B63">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_END" count="1" value="0x0B64">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_MODE" count="1" value="0x0B65">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="FOG_COLOR" count="4" value="0x0B66">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="DEPTH_RANGE" count="2" value="0x0B70">
@@ -531,8 +531,8 @@
<size name="Get" mode="get"/>
</enum>
<enum name="ALPHA_SCALE" count="1" value="0x0D1C">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
<size name="Get" mode="get"/>
@@ -625,93 +625,93 @@
<size name="Get" mode="get"/>
</enum>
<enum name="MAP1_COLOR_4" count="4" value="0x0D90">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_INDEX" count="1" value="0x0D91">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_NORMAL" count="3" value="0x0D92">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_TEXTURE_COORD_1" count="1" value="0x0D93">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_TEXTURE_COORD_2" count="2" value="0x0D94">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_TEXTURE_COORD_3" count="3" value="0x0D95">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_TEXTURE_COORD_4" count="4" value="0x0D96">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_VERTEX_3" count="3" value="0x0D97">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_VERTEX_4" count="4" value="0x0D98">
- <size name="Map1d"/>
- <size name="Map1f"/>
+ <size name="Map1d" mode="get"/>
+ <size name="Map1f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_COLOR_4" count="4" value="0x0DB0">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_INDEX" count="1" value="0x0DB1">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_NORMAL" count="3" value="0x0DB2">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_TEXTURE_COORD_1" count="1" value="0x0DB3">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_TEXTURE_COORD_2" count="2" value="0x0DB4">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_TEXTURE_COORD_3" count="3" value="0x0DB5">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_TEXTURE_COORD_4" count="4" value="0x0DB6">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_VERTEX_3" count="3" value="0x0DB7">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP2_VERTEX_4" count="4" value="0x0DB8">
- <size name="Map2d"/>
- <size name="Map2f"/>
+ <size name="Map2d" mode="get"/>
+ <size name="Map2f" mode="get"/>
<size name="Get" count="1" mode="get"/>
</enum>
<enum name="MAP1_GRID_DOMAIN" count="2" value="0x0DD0">
@@ -754,8 +754,8 @@
<size name="GetTexLevelParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_BORDER_COLOR" count="4" value="0x1004">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -763,111 +763,111 @@
<enum name="FASTEST" value="0x1101"/>
<enum name="NICEST" value="0x1102"/>
<enum name="AMBIENT" count="4" value="0x1200">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="DIFFUSE" count="4" value="0x1201">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="SPECULAR" count="4" value="0x1202">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="POSITION" count="4" value="0x1203">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="SPOT_DIRECTION" count="3" value="0x1204">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="SPOT_EXPONENT" count="1" value="0x1205">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="SPOT_CUTOFF" count="1" value="0x1206">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="CONSTANT_ATTENUATION" count="1" value="0x1207">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="LINEAR_ATTENUATION" count="1" value="0x1208">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="QUADRATIC_ATTENUATION" count="1" value="0x1209">
- <size name="Lightfv"/>
- <size name="Lightiv"/>
+ <size name="Lightfv" mode="get"/>
+ <size name="Lightiv" mode="get"/>
<size name="GetLightfv" mode="get"/>
<size name="GetLightiv" mode="get"/>
</enum>
<enum name="COMPILE" value="0x1300"/>
<enum name="COMPILE_AND_EXECUTE" value="0x1301"/>
<enum name="BYTE" count="1" value="0x1400">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="UNSIGNED_BYTE" count="1" value="0x1401">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="SHORT" count="2" value="0x1402">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="UNSIGNED_SHORT" count="2" value="0x1403">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="INT" count="4" value="0x1404">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="UNSIGNED_INT" count="4" value="0x1405">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="FLOAT" count="4" value="0x1406">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="2_BYTES" count="2" value="0x1407">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="3_BYTES" count="3" value="0x1408">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="4_BYTES" count="4" value="0x1409">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="HALF_FLOAT" count="2" value="0x140B">
- <size name="CallLists"/>
+ <size name="CallLists" mode="get"/>
</enum>
<enum name="CLEAR" value="0x1500"/>
<enum name="AND" value="0x1501"/>
@@ -886,26 +886,26 @@
<enum name="NAND" value="0x150E"/>
<enum name="SET" value="0x150F"/>
<enum name="EMISSION" count="4" value="0x1600">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
</enum>
<enum name="SHININESS" count="1" value="0x1601">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
</enum>
<enum name="AMBIENT_AND_DIFFUSE" count="4" value="0x1602">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
</enum>
<enum name="COLOR_INDEXES" count="3" value="0x1603">
- <size name="Materialfv"/>
- <size name="Materialiv"/>
+ <size name="Materialfv" mode="get"/>
+ <size name="Materialiv" mode="get"/>
<size name="GetMaterialfv" mode="get"/>
<size name="GetMaterialiv" mode="get"/>
</enum>
@@ -950,14 +950,14 @@
<enum name="MODULATE" value="0x2100"/>
<enum name="DECAL" value="0x2101"/>
<enum name="TEXTURE_ENV_MODE" count="1" value="0x2200">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="TEXTURE_ENV_COLOR" count="4" value="0x2201">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
@@ -966,25 +966,25 @@
<enum name="OBJECT_LINEAR" value="0x2401"/>
<enum name="SPHERE_MAP" value="0x2402"/>
<enum name="TEXTURE_GEN_MODE" count="1" value="0x2500">
- <size name="TexGendv"/>
- <size name="TexGenfv"/>
- <size name="TexGeniv"/>
+ <size name="TexGendv" mode="get"/>
+ <size name="TexGenfv" mode="get"/>
+ <size name="TexGeniv" mode="get"/>
<size name="GetTexGendv" mode="get"/>
<size name="GetTexGenfv" mode="get"/>
<size name="GetTexGeniv" mode="get"/>
</enum>
<enum name="OBJECT_PLANE" count="4" value="0x2501">
- <size name="TexGendv"/>
- <size name="TexGenfv"/>
- <size name="TexGeniv"/>
+ <size name="TexGendv" mode="get"/>
+ <size name="TexGenfv" mode="get"/>
+ <size name="TexGeniv" mode="get"/>
<size name="GetTexGendv" mode="get"/>
<size name="GetTexGenfv" mode="get"/>
<size name="GetTexGeniv" mode="get"/>
</enum>
<enum name="EYE_PLANE" count="4" value="0x2502">
- <size name="TexGendv"/>
- <size name="TexGenfv"/>
- <size name="TexGeniv"/>
+ <size name="TexGendv" mode="get"/>
+ <size name="TexGenfv" mode="get"/>
+ <size name="TexGeniv" mode="get"/>
<size name="GetTexGendv" mode="get"/>
<size name="GetTexGenfv" mode="get"/>
<size name="GetTexGeniv" mode="get"/>
@@ -996,26 +996,26 @@
<enum name="NEAREST_MIPMAP_LINEAR" value="0x2702"/>
<enum name="LINEAR_MIPMAP_LINEAR" value="0x2703"/>
<enum name="TEXTURE_MAG_FILTER" count="1" value="0x2800">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_MIN_FILTER" count="1" value="0x2801">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_WRAP_S" count="1" value="0x2802">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_WRAP_T" count="1" value="0x2803">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -3039,8 +3039,8 @@
<enum name="PROXY_TEXTURE_1D" value="0x8063"/>
<enum name="PROXY_TEXTURE_2D" value="0x8064"/>
<enum name="TEXTURE_PRIORITY" count="1" value="0x8066">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -3380,8 +3380,8 @@
<size name="GetTexLevelParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_WRAP_R" count="1" value="0x8072">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -3405,32 +3405,32 @@
</enum>
<enum name="CLAMP_TO_EDGE" value="0x812F"/>
<enum name="TEXTURE_MIN_LOD" count="1" value="0x813A">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_MAX_LOD" count="1" value="0x813B">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_BASE_LEVEL" count="1" value="0x813C">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_MAX_LEVEL" count="1" value="0x813D">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="LIGHT_MODEL_COLOR_CONTROL" count="1" value="0x81F8">
- <size name="LightModelfv"/>
- <size name="LightModeliv"/>
+ <size name="LightModelfv" mode="get"/>
+ <size name="LightModeliv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="SINGLE_COLOR" value="0x81F9"/>
@@ -3482,26 +3482,26 @@
</enum>
<enum name="CONVOLUTION_BORDER_MODE" count="1" value="0x8013">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
<enum name="CONVOLUTION_BORDER_COLOR" count="4" value="0x8154">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
<enum name="CONVOLUTION_FILTER_SCALE" count="4" value="0x8014">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
<enum name="CONVOLUTION_FILTER_BIAS" count="4" value="0x8015">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
@@ -3649,14 +3649,14 @@
<enum name="PROXY_POST_COLOR_MATRIX_COLOR_TABLE" value="0x80D5"/>
<enum name="COLOR_TABLE_SCALE" count="4" value="0x80D6">
- <size name="ColorTableParameterfv"/>
- <size name="ColorTableParameteriv"/>
+ <size name="ColorTableParameterfv" mode="get"/>
+ <size name="ColorTableParameteriv" mode="get"/>
<size name="GetColorTableParameterfv" mode="get"/>
<size name="GetColorTableParameteriv" mode="get"/>
</enum>
<enum name="COLOR_TABLE_BIAS" count="4" value="0x80D7">
- <size name="ColorTableParameterfv"/>
- <size name="ColorTableParameteriv"/>
+ <size name="ColorTableParameterfv" mode="get"/>
+ <size name="ColorTableParameteriv" mode="get"/>
<size name="GetColorTableParameterfv" mode="get"/>
<size name="GetColorTableParameteriv" mode="get"/>
</enum>
@@ -4133,92 +4133,92 @@
<enum name="CLAMP_TO_BORDER" value="0x812D"/>
<enum name="COMBINE" value="0x8570"/>
<enum name="COMBINE_RGB" count="1" value="0x8571">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="COMBINE_ALPHA" count="1" value="0x8572">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE0_RGB" count="1" value="0x8580">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE1_RGB" count="1" value="0x8581">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE2_RGB" count="1" value="0x8582">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE0_ALPHA" count="1" value="0x8588">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE1_ALPHA" count="1" value="0x8589">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE2_ALPHA" count="1" value="0x858A">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND0_RGB" count="1" value="0x8590">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND1_RGB" count="1" value="0x8591">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND2_RGB" count="1" value="0x8592">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND0_ALPHA" count="1" value="0x8598">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND1_ALPHA" count="1" value="0x8599">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND2_ALPHA" count="1" value="0x859A">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="RGB_SCALE" count="1" value="0x8573">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
@@ -4534,24 +4534,24 @@
<size name="Get" mode="get"/>
</enum>
<enum name="POINT_SIZE_MIN" count="1" value="0x8126">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="POINT_SIZE_MAX" count="1" value="0x8127">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="POINT_FADE_THRESHOLD_SIZE" count="1" value="0x8128">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="POINT_DISTANCE_ATTENUATION" count="3" value="0x8129">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="GENERATE_MIPMAP" count="1" value="0x8191">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -4600,10 +4600,10 @@
</enum>
<enum name="TEXTURE_FILTER_CONTROL" value="0x8500"/>
<enum name="TEXTURE_LOD_BIAS" count="1" value="0x8501">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
@@ -4616,20 +4616,20 @@
<size name="GetTexLevelParameteriv" mode="get"/>
</enum>
<enum name="DEPTH_TEXTURE_MODE" count="1" value="0x884B">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_COMPARE_MODE" count="1" value="0x884C">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_COMPARE_FUNC" count="1" value="0x884D">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -5121,8 +5121,8 @@
<enum name="SHADING_LANGUAGE_VERSION" value="0x8B8C"/>
<enum name="CURRENT_PROGRAM" value="0x8B8D"/>
<enum name="POINT_SPRITE_COORD_ORIGIN" count="1" value="0x8CA0">
- <size name="PointParameterfvEXT"/>
- <size name="PointParameterivNV"/>
+ <size name="PointParameterfvEXT" mode="get"/>
+ <size name="PointParameterivNV" mode="get"/>
</enum>
<enum name="LOWER_LEFT" value="0x8CA1"/>
<enum name="UPPER_LEFT" value="0x8CA2"/>
@@ -6226,16 +6226,16 @@
<category name="GL_ARB_point_parameters" number="14">
<enum name="POINT_SIZE_MIN_ARB" count="1" value="0x8126">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_SIZE_MAX_ARB" count="1" value="0x8127">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_FADE_THRESHOLD_SIZE_ARB" count="1" value="0x8128">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_DISTANCE_ATTENUATION_ARB" count="3" value="0x8129">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<function name="PointParameterfARB" alias="PointParameterfEXT">
@@ -6541,8 +6541,8 @@
<size name="GetTexLevelParameteriv" mode="get"/>
</enum>
<enum name="DEPTH_TEXTURE_MODE_ARB" count="1" value="0x884B">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -6550,14 +6550,14 @@
<category name="GL_ARB_shadow" number="23">
<enum name="TEXTURE_COMPARE_MODE_ARB" count="1" value="0x884C">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_COMPARE_FUNC_ARB" count="1" value="0x884D">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -6566,8 +6566,8 @@
<category name="GL_ARB_shadow_ambient" number="24">
<enum name="TEXTURE_COMPARE_FAIL_VALUE_ARB" count="1" value="0x80BF">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -7865,8 +7865,8 @@
<size name="Get" mode="get"/>
</enum>
<enum name="COORD_REPLACE_ARB" count="1" value="0x8862">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
@@ -8317,20 +8317,20 @@
<category name="GL_EXT_convolution" number="12">
<enum name="CONVOLUTION_BORDER_MODE_EXT" count="1" value="0x8013">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
<enum name="CONVOLUTION_FILTER_SCALE_EXT" count="4" value="0x8014">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
<enum name="CONVOLUTION_FILTER_BIAS_EXT" count="4" value="0x8015">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
@@ -8840,8 +8840,8 @@
<category name="GL_SGIS_generate_mipmap" number="32">
<enum name="GENERATE_MIPMAP_SGIS" count="1" value="0x8191">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -8851,26 +8851,26 @@
<category name="GL_SGIX_clipmap" number="33">
<enum name="LINEAR_CLIPMAP_LINEAR_SGIX" value="0x8170"/>
<enum name="TEXTURE_CLIPMAP_CENTER_SGIX" count="2" value="0x8171">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_CLIPMAP_FRAME_SGIX" count="1" value="0x8172">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_CLIPMAP_OFFSET_SGIX" count="2" value="0x8173">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX" count="3" value="0x8174">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -8885,14 +8885,14 @@
<category name="GL_SGIX_shadow" number="34">
<enum name="TEXTURE_COMPARE_SGIX" count="1" value="0x819A">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_COMPARE_OPERATOR_SGIX" count="1" value="0x819B">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -8969,16 +8969,16 @@
<category name="GL_EXT_point_parameters" number="54">
<enum name="POINT_SIZE_MIN_EXT" count="1" value="0x8126">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_SIZE_MAX_EXT" count="1" value="0x8127">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_FADE_THRESHOLD_SIZE_EXT" count="1" value="0x8128">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_DISTANCE_ATTENUATION_EXT" count="3" value="0x8129">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<function name="PointParameterfEXT" offset="assign">
@@ -9029,14 +9029,14 @@
<category name="GL_SGIX_texture_scale_bias" number="56">
<enum name="POST_TEXTURE_FILTER_BIAS_SGIX" count="4" value="0x8179">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="POST_TEXTURE_FILTER_SCALE_SGIX" count="4" value="0x817A">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -9096,8 +9096,8 @@
<category name="GL_SGIX_fog_offset" number="65">
<enum name="FOG_OFFSET_SGIX" value="0x8198"/>
<enum name="FOG_OFFSET_VALUE_SGIX" count="1" value="0x8199">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
</enum>
</category>
@@ -9144,8 +9144,8 @@
<enum name="CONSTANT_BORDER_HP" value="0x8151"/>
<enum name="REPLICATE_BORDER_HP" value="0x8153"/>
<enum name="CONVOLUTION_BORDER_COLOR_HP" count="4" value="0x8154">
- <size name="ConvolutionParameterfv"/>
- <size name="ConvolutionParameteriv"/>
+ <size name="ConvolutionParameterfv" mode="get"/>
+ <size name="ConvolutionParameteriv" mode="get"/>
<size name="GetConvolutionParameterfv" mode="get"/>
<size name="GetConvolutionParameteriv" mode="get"/>
</enum>
@@ -9311,20 +9311,20 @@
<category name="GL_SGIX_texture_lod_bias" number="84">
<enum name="TEXTURE_LOD_BIAS_S_SGIX" count="1" value="0x818E">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_LOD_BIAS_T_SGIX" count="1" value="0x818F">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_LOD_BIAS_R_SGIX" count="1" value="0x8190">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -9339,8 +9339,8 @@
<category name="GL_SGIX_shadow_ambient" number="90">
<enum name="SHADOW_AMBIENT_SGIX" count="1" value="0x80BF">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -9684,8 +9684,8 @@
<category name="GL_EXT_separate_specular_color" number="144">
<enum name="LIGHT_MODEL_COLOR_CONTROL_EXT" count="1" value="0x81F8">
- <size name="LightModelfv"/>
- <size name="LightModeliv"/>
+ <size name="LightModelfv" mode="get"/>
+ <size name="LightModeliv" mode="get"/>
</enum>
<enum name="SINGLE_COLOR_EXT" value="0x81F9"/>
<enum name="SEPARATE_SPECULAR_COLOR_EXT" value="0x81FA"/>
@@ -10458,8 +10458,8 @@
<category name="GL_EXT_texture_lod_bias" number="186">
<enum name="TEXTURE_LOD_BIAS_EXT" count="1" value="0x8501">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -10467,8 +10467,8 @@
<category name="GL_EXT_texture_filter_anisotropic" number="187">
<enum name="TEXTURE_MAX_ANISOTROPY_EXT" count="1" value="0x84FE">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -10626,8 +10626,8 @@
<category name="GL_NV_fog_distance" number="192">
<enum name="FOG_DISTANCE_MODE_NV" count="1" value="0x855A">
- <size name="Fogfv"/>
- <size name="Fogiv"/>
+ <size name="Fogfv" mode="get"/>
+ <size name="Fogiv" mode="get"/>
<size name="Get" mode="get"/>
</enum>
<enum name="EYE_RADIAL_NV" value="0x855B"/>
@@ -10641,26 +10641,26 @@
<category name="GL_NV_texture_env_combine4" number="195">
<enum name="COMBINE4" value="0x8503"/>
<enum name="SOURCE3_RGB_NV" count="1" value="0x8583">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="SOURCE3_ALPHA_NV" count="1" value="0x858B">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND3_RGB_NV" count="1" value="0x8593">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="OPERAND3_ALPHA_NV" count="1" value="0x859B">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
@@ -11681,20 +11681,20 @@
<category name="GL_SGIX_texture_coordinate_clamp" number="235">
<enum name="TEXTURE_MAX_CLAMP_S_SGIX" count="1" value="0x8369">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_MAX_CLAMP_T_SGIX" count="1" value="0x836A">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
<enum name="TEXTURE_MAX_CLAMP_R_SGIX" count="1" value="0x836B">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -11733,8 +11733,8 @@
<enum name="DU8DV8_ATI" value="0x877A"/>
<enum name="BUMP_ENVMAP_ATI" value="0x877B"/>
<enum name="BUMP_TARGET_ATI" count="1" value="0x877C">
- <size name="TexEnviv"/>
- <size name="TexEnvfv"/>
+ <size name="TexEnviv" mode="get"/>
+ <size name="TexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
</enum>
@@ -11927,30 +11927,30 @@
added for this extension. -->
<enum name="POINT_SIZE_MIN_EXT" count="1" value="0x8126">
- <size name="PointParameterivNV"/>
+ <size name="PointParameterivNV" mode="get"/>
</enum>
<enum name="POINT_SIZE_MAX_EXT" count="1" value="0x8127">
- <size name="PointParameterivNV"/>
+ <size name="PointParameterivNV" mode="get"/>
</enum>
<enum name="POINT_FADE_THRESHOLD_SIZE_EXT" count="1" value="0x8128">
- <size name="PointParameterivNV"/>
+ <size name="PointParameterivNV" mode="get"/>
</enum>
<enum name="POINT_DISTANCE_ATTENUATION_EXT" count="3" value="0x8129">
- <size name="PointParameterivNV"/>
+ <size name="PointParameterivNV" mode="get"/>
</enum>
<enum name="POINT_SPRITE_NV" count="1" value="0x8861">
<size name="Get" mode="get"/>
</enum>
<enum name="COORD_REPLACE_NV" count="1" value="0x8862">
- <size name="TexEnvfv"/>
- <size name="TexEnviv"/>
+ <size name="TexEnvfv" mode="get"/>
+ <size name="TexEnviv" mode="get"/>
<size name="GetTexEnvfv" mode="get"/>
<size name="GetTexEnviv" mode="get"/>
</enum>
<enum name="POINT_SPRITE_R_MODE_NV" count="1" value="0x8863">
- <size name="PointParameterfvEXT"/>
- <size name="PointParameterivNV"/>
+ <size name="PointParameterfvEXT" mode="get"/>
+ <size name="PointParameterivNV" mode="get"/>
<size name="Get" mode="get"/>
</enum>
@@ -12129,8 +12129,8 @@
<category name="GL_NV_texture_expand_normal" number="286">
<enum name="TEXTURE_UNSIGNED_REMAP_MODE_NV" count="1" value="0x888F">
- <size name="TexParameterfv"/>
- <size name="TexParameteriv"/>
+ <size name="TexParameterfv" mode="get"/>
+ <size name="TexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
</enum>
@@ -12284,22 +12284,22 @@
<category name="GL_APPLE_texture_range" number="367">
<enum name="TEXTURE_STORAGE_HINT_APPLE" count="1" value="0x85BC">
- <size name="TexParameteriv"/>
- <size name="TexParameterfv"/>
+ <size name="TexParameteriv" mode="get"/>
+ <size name="TexParameterfv" mode="get"/>
<size name="GetTexParameteriv" mode="get"/>
<size name="GetTexParameterfv" mode="get"/>
</enum>
<enum name="STORAGE_PRIVATE_APPLE" count="1" value="0x85BD">
- <size name="TexParameteriv"/>
- <size name="TexParameterfv"/>
+ <size name="TexParameteriv" mode="get"/>
+ <size name="TexParameterfv" mode="get"/>
</enum>
<enum name="STORAGE_CACHED_APPLE" count="1" value="0x85BE">
- <size name="TexParameteriv"/>
- <size name="TexParameterfv"/>
+ <size name="TexParameteriv" mode="get"/>
+ <size name="TexParameterfv" mode="get"/>
</enum>
<enum name="STORAGE_SHARED_APPLE" count="1" value="0x85BF">
- <size name="TexParameteriv"/>
- <size name="TexParameterfv"/>
+ <size name="TexParameteriv" mode="get"/>
+ <size name="TexParameterfv" mode="get"/>
</enum>
<enum name="TEXTURE_RANGE_LENGTH_APPLE" count="1" value="0x85B7">
<size name="GetTexParameteriv" mode="get"/>
@@ -12442,16 +12442,16 @@
<category name="GL_SGIS_point_parameters">
<enum name="POINT_SIZE_MIN_SGIS" count="1" value="0x8126">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_SIZE_MAX_SGIS" count="1" value="0x8127">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_FADE_THRESHOLD_SIZE_SGIS" count="1" value="0x8128">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<enum name="POINT_DISTANCE_ATTENUATION_SGIS" count="3" value="0x8129">
- <size name="PointParameterfvEXT"/>
+ <size name="PointParameterfvEXT" mode="get"/>
</enum>
<function name="PointParameterfSGIS" alias="PointParameterfEXT" static_dispatch="false">
diff --git a/mesalib/src/mapi/glapi/glapi.h b/mesalib/src/mapi/glapi/glapi.h
index 1d4ac4674..a99317ad0 100644
--- a/mesalib/src/mapi/glapi/glapi.h
+++ b/mesalib/src/mapi/glapi/glapi.h
@@ -39,12 +39,9 @@
* This module is intended to be non-Mesa-specific so it can be used
* with the X/DRI libGL also.
*/
-
-
#ifndef _GLAPI_H
#define _GLAPI_H
-
#ifdef _GLAPI_NO_EXPORTS
# define _GLAPI_EXPORT
#else /* _GLAPI_NO_EXPORTS */
@@ -72,7 +69,7 @@
#define _glapi_Context _mglapi_Context
#endif
-#include "glapi/glthread.h"
+#include "glthread.h"
typedef void (*_glapi_proc)(void);
struct _glapi_table;
@@ -94,8 +91,14 @@ _GLAPI_EXPORT extern const void *_glapi_Context;
#else
-_GLAPI_EXPORT extern struct _glapi_table *_glapi_Dispatch;
-_GLAPI_EXPORT extern void *_glapi_Context;
+#ifdef INSERVER
+#define SERVEXTERN _declspec(dllimport)
+#else
+#define SERVEXTERN _declspec(dllexport)
+#endif
+
+SERVEXTERN struct _glapi_table *_glapi_Dispatch;
+SERVEXTERN void *_glapi_Context;
# ifdef THREADS
@@ -119,31 +122,31 @@ void
_glapi_destroy_multithread(void);
-_GLAPI_EXPORT void
+SERVEXTERN void
_glapi_check_multithread(void);
-_GLAPI_EXPORT void
+SERVEXTERN void
_glapi_set_context(void *context);
-_GLAPI_EXPORT void *
+SERVEXTERN void *
_glapi_get_context(void);
-_GLAPI_EXPORT void
+SERVEXTERN void
_glapi_set_dispatch(struct _glapi_table *dispatch);
-_GLAPI_EXPORT struct _glapi_table *
+SERVEXTERN struct _glapi_table *
_glapi_get_dispatch(void);
-_GLAPI_EXPORT unsigned int
+SERVEXTERN unsigned int
_glapi_get_dispatch_table_size(void);
-_GLAPI_EXPORT int
+SERVEXTERN int
_glapi_add_dispatch( const char * const * function_names,
const char * parameter_signature );
@@ -166,7 +169,7 @@ _glthread_GetID(void);
/*
* These stubs are kept so that the old DRI drivers still load.
*/
-_GLAPI_EXPORT void
+SERVEXTERN void
_glapi_noop_enable_warnings(unsigned char enable);
diff --git a/mesalib/src/mapi/glapi/glapi_getproc.c b/mesalib/src/mapi/glapi/glapi_getproc.c
index 21380ea41..d5c72f29b 100644
--- a/mesalib/src/mapi/glapi/glapi_getproc.c
+++ b/mesalib/src/mapi/glapi/glapi_getproc.c
@@ -369,6 +369,7 @@ set_entry_info( struct _glapi_function * entry, const char * signature, unsigned
* the parameter signature of a static function.
*/
+#ifndef INSERVER
int
_glapi_add_dispatch( const char * const * function_names,
const char * parameter_signature )
@@ -478,12 +479,12 @@ _glapi_add_dispatch( const char * const * function_names,
return offset;
}
-
+#endif
/**
* Return offset of entrypoint for named function within dispatch table.
*/
-GLint
+GLint _GLAPI_EXPORT
_glapi_get_proc_offset(const char *funcName)
{
GLint offset;
@@ -504,7 +505,7 @@ _glapi_get_proc_offset(const char *funcName)
* in the name of static functions, try generating a new API entrypoint on
* the fly with assembly language.
*/
-_glapi_proc
+_glapi_proc _GLAPI_EXPORT
_glapi_get_proc_address(const char *funcName)
{
_glapi_proc func;
@@ -545,7 +546,7 @@ _glapi_get_proc_address(const char *funcName)
* Return the name of the function at the given dispatch offset.
* This is only intended for debugging.
*/
-const char *
+const char * _GLAPI_EXPORT
_glapi_get_proc_name(GLuint offset)
{
const char * n;
@@ -571,7 +572,7 @@ _glapi_get_proc_name(GLuint offset)
* Return size of dispatch table struct as number of functions (or
* slots).
*/
-GLuint
+GLuint _GLAPI_EXPORT
_glapi_get_dispatch_table_size(void)
{
/*
diff --git a/mesalib/src/mapi/glapi/glapi_nop.c b/mesalib/src/mapi/glapi/glapi_nop.c
index 9b0929715..365a6e1c8 100644
--- a/mesalib/src/mapi/glapi/glapi_nop.c
+++ b/mesalib/src/mapi/glapi/glapi_nop.c
@@ -41,12 +41,12 @@
#include "glapi/glapi_priv.h"
-void
+void _GLAPI_EXPORT
_glapi_noop_enable_warnings(unsigned char enable)
{
}
-void
+void _GLAPI_EXPORT
_glapi_set_warning_func(_glapi_proc func)
{
}
diff --git a/mesalib/src/mapi/glapi/glthread.c b/mesalib/src/mapi/glapi/glthread.c
index 00915380f..239090ecf 100644
--- a/mesalib/src/mapi/glapi/glthread.c
+++ b/mesalib/src/mapi/glapi/glthread.c
@@ -1,6 +1,6 @@
#include "glapi/glapi.h"
-unsigned long
+unsigned long _GLAPI_EXPORT
_glthread_GetID(void)
{
return u_thread_self();
diff --git a/mesalib/src/mesa/drivers/dri/Makefile.template b/mesalib/src/mesa/drivers/dri/Makefile.template
index d1a119379..195d60a9c 100644
--- a/mesalib/src/mesa/drivers/dri/Makefile.template
+++ b/mesalib/src/mesa/drivers/dri/Makefile.template
@@ -1,111 +1,111 @@
-# -*-makefile-*-
-
-COMMON_GALLIUM_SOURCES = \
- ../common/utils.c \
- ../common/vblank.c \
- ../common/dri_util.c \
- ../common/xmlconfig.c
-
-COMMON_SOURCES = $(COMMON_GALLIUM_SOURCES) \
- ../../common/driverfuncs.c \
- ../common/texmem.c \
- ../common/drirenderbuffer.c
-
-INCLUDES = $(SHARED_INCLUDES) $(EXPAT_INCLUDES)
-
-OBJECTS = $(C_SOURCES:.c=.o) \
- $(CXX_SOURCES:.cpp=.o) \
- $(ASM_SOURCES:.S=.o)
-
-
-### Include directories
-SHARED_INCLUDES = \
- -I. \
- -I$(TOP)/src/mesa/drivers/dri/common \
- -Iserver \
- -I$(TOP)/include \
- -I$(TOP)/src/mapi \
- -I$(TOP)/src/mesa \
- -I$(TOP)/src/egl/main \
- -I$(TOP)/src/egl/drivers/dri \
- $(LIBDRM_CFLAGS)
-
-CFLAGS += $(API_DEFINES)
-CXXFLAGS += $(API_DEFINES)
-
-##### RULES #####
-
-.c.o:
- $(CC) -c $(INCLUDES) $(DRI_CFLAGS) $(DRIVER_DEFINES) $< -o $@
-
-.cpp.o:
- $(CC) -c $(INCLUDES) $(DRI_CXXFLAGS) $(DRIVER_DEFINES) $< -o $@
-
-.S.o:
- $(CC) -c $(INCLUDES) $(DRI_CFLAGS) $(DRIVER_DEFINES) $< -o $@
-
-
-##### TARGETS #####
-
-default: subdirs lib
-
-
-.PHONY: lib
-lib: symlinks subdirs depend
- @$(MAKE) $(LIBNAME) $(TOP)/$(LIB_DIR)/$(LIBNAME)
-
-$(LIBNAME): $(OBJECTS) $(EXTRA_MODULES) $(MESA_MODULES) Makefile \
- $(TOP)/src/mesa/drivers/dri/Makefile.template $(TOP)/src/mesa/drivers/dri/common/dri_test.o
- $(MKLIB) -o $@.tmp -noprefix -linker '$(CXX)' -ldflags '$(LDFLAGS)' \
- $(OBJECTS) $(EXTRA_MODULES) $(DRI_LIB_DEPS)
- $(CXX) $(CFLAGS) -o $@.test $(TOP)/src/mesa/drivers/dri/common/dri_test.o $@.tmp $(DRI_LIB_DEPS)
- @rm -f $@.test
- mv -f $@.tmp $@
-
-
-$(TOP)/$(LIB_DIR)/$(LIBNAME): $(LIBNAME)
- $(INSTALL) $(LIBNAME) $(TOP)/$(LIB_DIR)
-
-
-# If the Makefile defined SUBDIRS, run make in each
-.PHONY: subdirs
-subdirs:
- @if test -n "$(SUBDIRS)" ; then \
- for dir in $(SUBDIRS) ; do \
- if [ -d $$dir ] ; then \
- (cd $$dir && $(MAKE)) || exit 1; \
- fi \
- done \
- fi
-
-
-.PHONY: symlinks
-symlinks:
-
-
-depend: $(C_SOURCES) $(CXX_SOURCES) $(ASM_SOURCES) $(SYMLINKS)
- @ echo "running $(MKDEP)"
- @ rm -f depend
- @ touch depend
- @ $(MKDEP) $(MKDEP_OPTIONS) $(DRIVER_DEFINES) $(INCLUDES) \
- $(C_SOURCES) $(CXX_SOURCES) \
- $(ASM_SOURCES) > /dev/null 2>/dev/null
-
-
-# Emacs tags
-tags:
- etags `find . -name \*.[ch]` `find ../include`
-
-
-# Remove .o and backup files
-clean:
- -rm -f *.o */*.o *~ *.so *~ server/*.o $(SYMLINKS)
- -rm -f depend depend.bak
-
-
-install: $(LIBNAME)
- $(INSTALL) -d $(DESTDIR)$(DRI_DRIVER_INSTALL_DIR)
- $(MINSTALL) -m 755 $(LIBNAME) $(DESTDIR)$(DRI_DRIVER_INSTALL_DIR)
-
-
--include depend
+# -*-makefile-*-
+
+COMMON_GALLIUM_SOURCES = \
+ ../common/utils.c \
+ ../common/vblank.c \
+ ../common/dri_util.c \
+ ../common/xmlconfig.c
+
+COMMON_SOURCES = $(COMMON_GALLIUM_SOURCES) \
+ ../../common/driverfuncs.c \
+ ../common/texmem.c \
+ ../common/drirenderbuffer.c
+
+INCLUDES = $(SHARED_INCLUDES) $(EXPAT_INCLUDES)
+
+OBJECTS = $(C_SOURCES:.c=.o) \
+ $(CXX_SOURCES:.cpp=.o) \
+ $(ASM_SOURCES:.S=.o)
+
+
+### Include directories
+SHARED_INCLUDES = \
+ -I. \
+ -I$(TOP)/src/mesa/drivers/dri/common \
+ -Iserver \
+ -I$(TOP)/include \
+ -I$(TOP)/src/mapi \
+ -I$(TOP)/src/mesa \
+ -I$(TOP)/src/egl/main \
+ -I$(TOP)/src/egl/drivers/dri \
+ $(LIBDRM_CFLAGS)
+
+CFLAGS += $(API_DEFINES)
+CXXFLAGS += $(API_DEFINES)
+
+##### RULES #####
+
+.c.o:
+ $(CC) -c $(INCLUDES) $(DRI_CFLAGS) $(DRIVER_DEFINES) $< -o $@
+
+.cpp.o:
+ $(CC) -c $(INCLUDES) $(DRI_CXXFLAGS) $(DRIVER_DEFINES) $< -o $@
+
+.S.o:
+ $(CC) -c $(INCLUDES) $(DRI_CFLAGS) $(DRIVER_DEFINES) $< -o $@
+
+
+##### TARGETS #####
+
+default: subdirs lib
+
+
+.PHONY: lib
+lib: symlinks subdirs depend
+ @$(MAKE) $(LIBNAME) $(TOP)/$(LIB_DIR)/$(LIBNAME)
+
+$(LIBNAME): $(OBJECTS) $(EXTRA_MODULES) $(MESA_MODULES) Makefile \
+ $(TOP)/src/mesa/drivers/dri/Makefile.template $(TOP)/src/mesa/drivers/dri/common/dri_test.o
+ $(MKLIB) -o $@.tmp -noprefix -linker '$(CXX)' -ldflags '$(LDFLAGS)' \
+ $(OBJECTS) $(EXTRA_MODULES) $(DRI_LIB_DEPS)
+ $(CXX) $(CFLAGS) -o $@.test $(TOP)/src/mesa/drivers/dri/common/dri_test.o $@.tmp $(DRI_LIB_DEPS)
+ @rm -f $@.test
+ mv -f $@.tmp $@
+
+
+$(TOP)/$(LIB_DIR)/$(LIBNAME): $(LIBNAME)
+ $(INSTALL) $(LIBNAME) $(TOP)/$(LIB_DIR)
+
+
+# If the Makefile defined SUBDIRS, run make in each
+.PHONY: subdirs
+subdirs:
+ @if test -n "$(SUBDIRS)" ; then \
+ for dir in $(SUBDIRS) ; do \
+ if [ -d $$dir ] ; then \
+ (cd $$dir && $(MAKE)) || exit 1; \
+ fi \
+ done \
+ fi
+
+
+.PHONY: symlinks
+symlinks:
+
+
+depend: $(C_SOURCES) $(CXX_SOURCES) $(ASM_SOURCES) $(SYMLINKS)
+ @ echo "running $(MKDEP)"
+ @ rm -f depend
+ @ touch depend
+ @ $(MKDEP) $(MKDEP_OPTIONS) $(DRIVER_DEFINES) $(INCLUDES) \
+ $(C_SOURCES) $(CXX_SOURCES) \
+ $(ASM_SOURCES) > /dev/null 2>/dev/null
+
+
+# Emacs tags
+tags:
+ etags `find . -name \*.[ch]` `find ../include`
+
+
+# Remove .o and backup files
+clean:
+ -rm -f *.o */*.o *~ *.so *~ server/*.o $(SYMLINKS)
+ -rm -f depend depend.bak
+
+
+install: $(LIBNAME)
+ $(INSTALL) -d $(DESTDIR)$(DRI_DRIVER_INSTALL_DIR)
+ $(MINSTALL) -m 755 $(LIBNAME) $(DESTDIR)$(DRI_DRIVER_INSTALL_DIR)
+
+
+-include depend
diff --git a/mesalib/src/mesa/drivers/dri/common/dri_util.c b/mesalib/src/mesa/drivers/dri/common/dri_util.c
index 82638fa72..6d3dd0a2c 100644
--- a/mesalib/src/mesa/drivers/dri/common/dri_util.c
+++ b/mesalib/src/mesa/drivers/dri/common/dri_util.c
@@ -1,1030 +1,1030 @@
-/**
- * \file dri_util.c
- * DRI utility functions.
- *
- * This module acts as glue between GLX and the actual hardware driver. A DRI
- * driver doesn't really \e have to use any of this - it's optional. But, some
- * useful stuff is done here that otherwise would have to be duplicated in most
- * drivers.
- *
- * Basically, these utility functions take care of some of the dirty details of
- * screen initialization, context creation, context binding, DRM setup, etc.
- *
- * These functions are compiled into each DRI driver so libGL.so knows nothing
- * about them.
- */
-
-
-#include <assert.h>
-#include <stdarg.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <stdio.h>
-
-#ifndef MAP_FAILED
-#define MAP_FAILED ((void *)-1)
-#endif
-
-#include "main/imports.h"
-#define None 0
-
-#include "dri_util.h"
-#include "drm_sarea.h"
-#include "utils.h"
-#include "xmlpool.h"
-#include "../glsl/glsl_parser_extras.h"
-
-PUBLIC const char __dri2ConfigOptions[] =
- DRI_CONF_BEGIN
- DRI_CONF_SECTION_PERFORMANCE
- DRI_CONF_VBLANK_MODE(DRI_CONF_VBLANK_DEF_INTERVAL_1)
- DRI_CONF_SECTION_END
- DRI_CONF_END;
-
-static const uint __dri2NConfigOptions = 1;
-
-#ifndef GLX_OML_sync_control
-typedef GLboolean ( * PFNGLXGETMSCRATEOMLPROC) (__DRIdrawable *drawable, int32_t *numerator, int32_t *denominator);
-#endif
-
-static void dri_get_drawable(__DRIdrawable *pdp);
-static void dri_put_drawable(__DRIdrawable *pdp);
-
-/**
- * This is just a token extension used to signal that the driver
- * supports setting a read drawable.
- */
-const __DRIextension driReadDrawableExtension = {
- __DRI_READ_DRAWABLE, __DRI_READ_DRAWABLE_VERSION
-};
-
-GLint
-driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 )
-{
- if (rect2.x1 > rect1.x1) rect1.x1 = rect2.x1;
- if (rect2.x2 < rect1.x2) rect1.x2 = rect2.x2;
- if (rect2.y1 > rect1.y1) rect1.y1 = rect2.y1;
- if (rect2.y2 < rect1.y2) rect1.y2 = rect2.y2;
-
- if (rect1.x1 > rect1.x2 || rect1.y1 > rect1.y2) return 0;
-
- return (rect1.x2 - rect1.x1) * (rect1.y2 - rect1.y1);
-}
-
-/*****************************************************************/
-/** \name Context (un)binding functions */
-/*****************************************************************/
-/*@{*/
-
-/**
- * Unbind context.
- *
- * \param scrn the screen.
- * \param gc context.
- *
- * \return \c GL_TRUE on success, or \c GL_FALSE on failure.
- *
- * \internal
- * This function calls __DriverAPIRec::UnbindContext, and then decrements
- * __DRIdrawableRec::refcount which must be non-zero for a successful
- * return.
- *
- * While casting the opaque private pointers associated with the parameters
- * into their respective real types it also assures they are not \c NULL.
- */
-static int driUnbindContext(__DRIcontext *pcp)
-{
- __DRIscreen *psp;
- __DRIdrawable *pdp;
- __DRIdrawable *prp;
-
- /*
- ** Assume error checking is done properly in glXMakeCurrent before
- ** calling driUnbindContext.
- */
-
- if (pcp == NULL)
- return GL_FALSE;
-
- psp = pcp->driScreenPriv;
- pdp = pcp->driDrawablePriv;
- prp = pcp->driReadablePriv;
-
- /* already unbound */
- if (!pdp && !prp)
- return GL_TRUE;
- /* Let driver unbind drawable from context */
- (*psp->DriverAPI.UnbindContext)(pcp);
-
- assert(pdp);
- if (pdp->refcount == 0) {
- /* ERROR!!! */
- return GL_FALSE;
- }
-
- dri_put_drawable(pdp);
-
- if (prp != pdp) {
- if (prp->refcount == 0) {
- /* ERROR!!! */
- return GL_FALSE;
- }
-
- dri_put_drawable(prp);
- }
-
-
- /* XXX this is disabled so that if we call SwapBuffers on an unbound
- * window we can determine the last context bound to the window and
- * use that context's lock. (BrianP, 2-Dec-2000)
- */
- pcp->driDrawablePriv = pcp->driReadablePriv = NULL;
-
- return GL_TRUE;
-}
-
-/**
- * This function takes both a read buffer and a draw buffer. This is needed
- * for \c glXMakeCurrentReadSGI or GLX 1.3's \c glXMakeContextCurrent
- * function.
- */
-static int driBindContext(__DRIcontext *pcp,
- __DRIdrawable *pdp,
- __DRIdrawable *prp)
-{
- __DRIscreen *psp = NULL;
-
- /*
- ** Assume error checking is done properly in glXMakeCurrent before
- ** calling driUnbindContext.
- */
-
- if (!pcp)
- return GL_FALSE;
-
- /* Bind the drawable to the context */
- psp = pcp->driScreenPriv;
- pcp->driDrawablePriv = pdp;
- pcp->driReadablePriv = prp;
- if (pdp) {
- pdp->driContextPriv = pcp;
- dri_get_drawable(pdp);
- }
- if (prp && pdp != prp) {
- dri_get_drawable(prp);
- }
-
- /*
- ** Now that we have a context associated with this drawable, we can
- ** initialize the drawable information if has not been done before.
- */
-
- if (!psp->dri2.enabled) {
- if (pdp && !pdp->pStamp) {
- DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
- __driUtilUpdateDrawableInfo(pdp);
- DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
- }
- if (prp && pdp != prp && !prp->pStamp) {
- DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
- __driUtilUpdateDrawableInfo(prp);
- DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
- }
- }
-
- /* Call device-specific MakeCurrent */
- return (*psp->DriverAPI.MakeCurrent)(pcp, pdp, prp);
-}
-
-/*@}*/
-
-
-/*****************************************************************/
-/** \name Drawable handling functions */
-/*****************************************************************/
-/*@{*/
-
-/**
- * Update private drawable information.
- *
- * \param pdp pointer to the private drawable information to update.
- *
- * This function basically updates the __DRIdrawable struct's
- * cliprect information by calling \c __DRIinterfaceMethods::getDrawableInfo.
- * This is usually called by the DRI_VALIDATE_DRAWABLE_INFO macro which
- * compares the __DRIdrwablePrivate pStamp and lastStamp values. If
- * the values are different that means we have to update the clipping
- * info.
- */
-void
-__driUtilUpdateDrawableInfo(__DRIdrawable *pdp)
-{
- __DRIscreen *psp = pdp->driScreenPriv;
- __DRIcontext *pcp = pdp->driContextPriv;
-
- if (!pcp
- || ((pdp != pcp->driDrawablePriv) && (pdp != pcp->driReadablePriv))) {
- /* ERROR!!!
- * ...but we must ignore it. There can be many contexts bound to a
- * drawable.
- */
- }
-
- if (pdp->pClipRects) {
- free(pdp->pClipRects);
- pdp->pClipRects = NULL;
- }
-
- if (pdp->pBackClipRects) {
- free(pdp->pBackClipRects);
- pdp->pBackClipRects = NULL;
- }
-
- DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
-
- if (! (*psp->getDrawableInfo->getDrawableInfo)(pdp,
- &pdp->index, &pdp->lastStamp,
- &pdp->x, &pdp->y, &pdp->w, &pdp->h,
- &pdp->numClipRects, &pdp->pClipRects,
- &pdp->backX,
- &pdp->backY,
- &pdp->numBackClipRects,
- &pdp->pBackClipRects,
- pdp->loaderPrivate)) {
- /* Error -- eg the window may have been destroyed. Keep going
- * with no cliprects.
- */
- pdp->pStamp = &pdp->lastStamp; /* prevent endless loop */
- pdp->numClipRects = 0;
- pdp->pClipRects = NULL;
- pdp->numBackClipRects = 0;
- pdp->pBackClipRects = NULL;
- }
- else
- pdp->pStamp = &(psp->pSAREA->drawableTable[pdp->index].stamp);
-
- DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
-}
-
-/*@}*/
-
-/*****************************************************************/
-/** \name GLX callbacks */
-/*****************************************************************/
-/*@{*/
-
-static void driReportDamage(__DRIdrawable *pdp,
- struct drm_clip_rect *pClipRects, int numClipRects)
-{
- __DRIscreen *psp = pdp->driScreenPriv;
-
- /* Check that we actually have the new damage report method */
- if (psp->damage) {
- /* Report the damage. Currently, all our drivers draw
- * directly to the front buffer, so we report the damage there
- * rather than to the backing storein (if any).
- */
- (*psp->damage->reportDamage)(pdp,
- pdp->x, pdp->y,
- pClipRects, numClipRects,
- GL_TRUE, pdp->loaderPrivate);
- }
-}
-
-
-/**
- * Swap buffers.
- *
- * \param drawablePrivate opaque pointer to the per-drawable private info.
- *
- * \internal
- * This function calls __DRIdrawable::swapBuffers.
- *
- * Is called directly from glXSwapBuffers().
- */
-static void driSwapBuffers(__DRIdrawable *dPriv)
-{
- __DRIscreen *psp = dPriv->driScreenPriv;
- drm_clip_rect_t *rects;
- int i;
-
- psp->DriverAPI.SwapBuffers(dPriv);
-
- if (!dPriv->numClipRects)
- return;
-
- rects = malloc(sizeof(*rects) * dPriv->numClipRects);
-
- if (!rects)
- return;
-
- for (i = 0; i < dPriv->numClipRects; i++) {
- rects[i].x1 = dPriv->pClipRects[i].x1 - dPriv->x;
- rects[i].y1 = dPriv->pClipRects[i].y1 - dPriv->y;
- rects[i].x2 = dPriv->pClipRects[i].x2 - dPriv->x;
- rects[i].y2 = dPriv->pClipRects[i].y2 - dPriv->y;
- }
-
- driReportDamage(dPriv, rects, dPriv->numClipRects);
- free(rects);
-}
-
-static int driDrawableGetMSC( __DRIscreen *sPriv, __DRIdrawable *dPriv,
- int64_t *msc )
-{
- return sPriv->DriverAPI.GetDrawableMSC(sPriv, dPriv, msc);
-}
-
-
-static int driWaitForMSC(__DRIdrawable *dPriv, int64_t target_msc,
- int64_t divisor, int64_t remainder,
- int64_t * msc, int64_t * sbc)
-{
- __DRIswapInfo sInfo;
- int status;
-
- status = dPriv->driScreenPriv->DriverAPI.WaitForMSC( dPriv, target_msc,
- divisor, remainder,
- msc );
-
- /* GetSwapInfo() may not be provided by the driver if GLX_SGI_video_sync
- * is supported but GLX_OML_sync_control is not. Therefore, don't return
- * an error value if GetSwapInfo() is not implemented.
- */
- if ( status == 0
- && dPriv->driScreenPriv->DriverAPI.GetSwapInfo ) {
- status = dPriv->driScreenPriv->DriverAPI.GetSwapInfo( dPriv, & sInfo );
- *sbc = sInfo.swap_count;
- }
-
- return status;
-}
-
-
-const __DRImediaStreamCounterExtension driMediaStreamCounterExtension = {
- { __DRI_MEDIA_STREAM_COUNTER, __DRI_MEDIA_STREAM_COUNTER_VERSION },
- driWaitForMSC,
- driDrawableGetMSC,
-};
-
-
-static void driCopySubBuffer(__DRIdrawable *dPriv,
- int x, int y, int w, int h)
-{
- drm_clip_rect_t rect;
-
- rect.x1 = x;
- rect.y1 = dPriv->h - y - h;
- rect.x2 = x + w;
- rect.y2 = rect.y1 + h;
- driReportDamage(dPriv, &rect, 1);
-
- dPriv->driScreenPriv->DriverAPI.CopySubBuffer(dPriv, x, y, w, h);
-}
-
-const __DRIcopySubBufferExtension driCopySubBufferExtension = {
- { __DRI_COPY_SUB_BUFFER, __DRI_COPY_SUB_BUFFER_VERSION },
- driCopySubBuffer
-};
-
-static void driSetSwapInterval(__DRIdrawable *dPriv, unsigned int interval)
-{
- dPriv->swap_interval = interval;
-}
-
-static unsigned int driGetSwapInterval(__DRIdrawable *dPriv)
-{
- return dPriv->swap_interval;
-}
-
-const __DRIswapControlExtension driSwapControlExtension = {
- { __DRI_SWAP_CONTROL, __DRI_SWAP_CONTROL_VERSION },
- driSetSwapInterval,
- driGetSwapInterval
-};
-
-
-/**
- * This is called via __DRIscreenRec's createNewDrawable pointer.
- */
-static __DRIdrawable *
-driCreateNewDrawable(__DRIscreen *psp, const __DRIconfig *config,
- drm_drawable_t hwDrawable, int renderType,
- const int *attrs, void *data)
-{
- __DRIdrawable *pdp;
-
- /* Since pbuffers are not yet supported, no drawable attributes are
- * supported either.
- */
- (void) attrs;
-
- pdp = malloc(sizeof *pdp);
- if (!pdp) {
- return NULL;
- }
-
- pdp->driContextPriv = NULL;
- pdp->loaderPrivate = data;
- pdp->hHWDrawable = hwDrawable;
- pdp->refcount = 1;
- pdp->pStamp = NULL;
- pdp->lastStamp = 0;
- pdp->index = 0;
- pdp->x = 0;
- pdp->y = 0;
- pdp->w = 0;
- pdp->h = 0;
- pdp->numClipRects = 0;
- pdp->numBackClipRects = 0;
- pdp->pClipRects = NULL;
- pdp->pBackClipRects = NULL;
- pdp->vblSeq = 0;
- pdp->vblFlags = 0;
-
- pdp->driScreenPriv = psp;
-
- if (!(*psp->DriverAPI.CreateBuffer)(psp, pdp, &config->modes, 0)) {
- free(pdp);
- return NULL;
- }
-
- pdp->msc_base = 0;
-
- /* This special default value is replaced with the configured
- * default value when the drawable is first bound to a direct
- * rendering context.
- */
- pdp->swap_interval = (unsigned)-1;
-
- return pdp;
-}
-
-
-static __DRIdrawable *
-dri2CreateNewDrawable(__DRIscreen *screen,
- const __DRIconfig *config,
- void *loaderPrivate)
-{
- __DRIdrawable *pdraw;
-
- pdraw = driCreateNewDrawable(screen, config, 0, 0, NULL, loaderPrivate);
- if (!pdraw)
- return NULL;
-
- pdraw->pClipRects = &pdraw->dri2.clipRect;
- pdraw->pBackClipRects = &pdraw->dri2.clipRect;
-
- pdraw->pStamp = &pdraw->dri2.stamp;
- *pdraw->pStamp = pdraw->lastStamp + 1;
-
- return pdraw;
-}
-
-static __DRIbuffer *
-dri2AllocateBuffer(__DRIscreen *screen,
- unsigned int attachment, unsigned int format,
- int width, int height)
-{
- return (*screen->DriverAPI.AllocateBuffer)(screen, attachment, format,
- width, height);
-}
-
-static void
-dri2ReleaseBuffer(__DRIscreen *screen, __DRIbuffer *buffer)
-{
- (*screen->DriverAPI.ReleaseBuffer)(screen, buffer);
-}
-
-
-static int
-dri2ConfigQueryb(__DRIscreen *screen, const char *var, GLboolean *val)
-{
- if (!driCheckOption(&screen->optionCache, var, DRI_BOOL))
- return -1;
-
- *val = driQueryOptionb(&screen->optionCache, var);
-
- return 0;
-}
-
-static int
-dri2ConfigQueryi(__DRIscreen *screen, const char *var, GLint *val)
-{
- if (!driCheckOption(&screen->optionCache, var, DRI_INT) &&
- !driCheckOption(&screen->optionCache, var, DRI_ENUM))
- return -1;
-
- *val = driQueryOptioni(&screen->optionCache, var);
-
- return 0;
-}
-
-static int
-dri2ConfigQueryf(__DRIscreen *screen, const char *var, GLfloat *val)
-{
- if (!driCheckOption(&screen->optionCache, var, DRI_FLOAT))
- return -1;
-
- *val = driQueryOptionf(&screen->optionCache, var);
-
- return 0;
-}
-
-
-static void dri_get_drawable(__DRIdrawable *pdp)
-{
- pdp->refcount++;
-}
-
-static void dri_put_drawable(__DRIdrawable *pdp)
-{
- __DRIscreen *psp;
-
- if (pdp) {
- pdp->refcount--;
- if (pdp->refcount)
- return;
-
- psp = pdp->driScreenPriv;
- (*psp->DriverAPI.DestroyBuffer)(pdp);
- if (pdp->pClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
- free(pdp->pClipRects);
- pdp->pClipRects = NULL;
- }
- if (pdp->pBackClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
- free(pdp->pBackClipRects);
- pdp->pBackClipRects = NULL;
- }
- free(pdp);
- }
-}
-
-static void
-driDestroyDrawable(__DRIdrawable *pdp)
-{
- dri_put_drawable(pdp);
-}
-
-/*@}*/
-
-
-/*****************************************************************/
-/** \name Context handling functions */
-/*****************************************************************/
-/*@{*/
-
-/**
- * Destroy the per-context private information.
- *
- * \internal
- * This function calls __DriverAPIRec::DestroyContext on \p contextPrivate, calls
- * drmDestroyContext(), and finally frees \p contextPrivate.
- */
-static void
-driDestroyContext(__DRIcontext *pcp)
-{
- if (pcp) {
- (*pcp->driScreenPriv->DriverAPI.DestroyContext)(pcp);
- free(pcp);
- }
-}
-
-
-/**
- * Create the per-drawable private driver information.
- *
- * \param render_type Type of rendering target. \c GLX_RGBA is the only
- * type likely to ever be supported for direct-rendering.
- * \param shared Context with which to share textures, etc. or NULL
- *
- * \returns An opaque pointer to the per-context private information on
- * success, or \c NULL on failure.
- *
- * \internal
- * This function allocates and fills a __DRIcontextRec structure. It
- * performs some device independent initialization and passes all the
- * relevent information to __DriverAPIRec::CreateContext to create the
- * context.
- *
- */
-static __DRIcontext *
-driCreateNewContext(__DRIscreen *psp, const __DRIconfig *config,
- int render_type, __DRIcontext *shared,
- drm_context_t hwContext, void *data)
-{
- __DRIcontext *pcp;
- void * const shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
-
- pcp = malloc(sizeof *pcp);
- if (!pcp)
- return NULL;
-
- pcp->driScreenPriv = psp;
- pcp->driDrawablePriv = NULL;
- pcp->loaderPrivate = data;
-
- pcp->dri2.draw_stamp = 0;
- pcp->dri2.read_stamp = 0;
-
- pcp->hHWContext = hwContext;
-
- if ( !(*psp->DriverAPI.CreateContext)(API_OPENGL,
- &config->modes, pcp, shareCtx) ) {
- free(pcp);
- return NULL;
- }
-
- return pcp;
-}
-
-static unsigned int
-dri2GetAPIMask(__DRIscreen *screen)
-{
- return screen->api_mask;
-}
-
-static __DRIcontext *
-dri2CreateNewContextForAPI(__DRIscreen *screen, int api,
- const __DRIconfig *config,
- __DRIcontext *shared, void *data)
-{
- __DRIcontext *context;
- const struct gl_config *modes = (config != NULL) ? &config->modes : NULL;
- void *shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
- gl_api mesa_api;
-
- if (!(screen->api_mask & (1 << api)))
- return NULL;
-
- switch (api) {
- case __DRI_API_OPENGL:
- mesa_api = API_OPENGL;
- break;
- case __DRI_API_GLES:
- mesa_api = API_OPENGLES;
- break;
- case __DRI_API_GLES2:
- mesa_api = API_OPENGLES2;
- break;
- default:
- return NULL;
- }
-
- context = malloc(sizeof *context);
- if (!context)
- return NULL;
-
- context->driScreenPriv = screen;
- context->driDrawablePriv = NULL;
- context->loaderPrivate = data;
-
- if (!(*screen->DriverAPI.CreateContext)(mesa_api, modes,
- context, shareCtx) ) {
- free(context);
- return NULL;
- }
-
- return context;
-}
-
-
-static __DRIcontext *
-dri2CreateNewContext(__DRIscreen *screen, const __DRIconfig *config,
- __DRIcontext *shared, void *data)
-{
- return dri2CreateNewContextForAPI(screen, __DRI_API_OPENGL,
- config, shared, data);
-}
-
-static int
-driCopyContext(__DRIcontext *dest, __DRIcontext *src, unsigned long mask)
-{
- return GL_FALSE;
-}
-
-/*@}*/
-
-
-/*****************************************************************/
-/** \name Screen handling functions */
-/*****************************************************************/
-/*@{*/
-
-/**
- * Destroy the per-screen private information.
- *
- * \internal
- * This function calls __DriverAPIRec::DestroyScreen on \p screenPrivate, calls
- * drmClose(), and finally frees \p screenPrivate.
- */
-static void driDestroyScreen(__DRIscreen *psp)
-{
- if (psp) {
- /* No interaction with the X-server is possible at this point. This
- * routine is called after XCloseDisplay, so there is no protocol
- * stream open to the X-server anymore.
- */
-
- _mesa_destroy_shader_compiler();
-
- if (psp->DriverAPI.DestroyScreen)
- (*psp->DriverAPI.DestroyScreen)(psp);
-
- if (!psp->dri2.enabled) {
- (void)drmUnmap((drmAddress)psp->pSAREA, SAREA_MAX);
- (void)drmUnmap((drmAddress)psp->pFB, psp->fbSize);
- (void)drmCloseOnce(psp->fd);
- } else {
- driDestroyOptionCache(&psp->optionCache);
- driDestroyOptionInfo(&psp->optionInfo);
- }
-
- free(psp);
- }
-}
-
-static void
-setupLoaderExtensions(__DRIscreen *psp,
- const __DRIextension **extensions)
-{
- int i;
-
- for (i = 0; extensions[i]; i++) {
- if (strcmp(extensions[i]->name, __DRI_GET_DRAWABLE_INFO) == 0)
- psp->getDrawableInfo = (__DRIgetDrawableInfoExtension *) extensions[i];
- if (strcmp(extensions[i]->name, __DRI_DAMAGE) == 0)
- psp->damage = (__DRIdamageExtension *) extensions[i];
- if (strcmp(extensions[i]->name, __DRI_SYSTEM_TIME) == 0)
- psp->systemTime = (__DRIsystemTimeExtension *) extensions[i];
- if (strcmp(extensions[i]->name, __DRI_DRI2_LOADER) == 0)
- psp->dri2.loader = (__DRIdri2LoaderExtension *) extensions[i];
- if (strcmp(extensions[i]->name, __DRI_IMAGE_LOOKUP) == 0)
- psp->dri2.image = (__DRIimageLookupExtension *) extensions[i];
- if (strcmp(extensions[i]->name, __DRI_USE_INVALIDATE) == 0)
- psp->dri2.useInvalidate = (__DRIuseInvalidateExtension *) extensions[i];
- }
-}
-
-/**
- * This is the bootstrap function for the driver. libGL supplies all of the
- * requisite information about the system, and the driver initializes itself.
- * This routine also fills in the linked list pointed to by \c driver_modes
- * with the \c struct gl_config that the driver can support for windows or
- * pbuffers.
- *
- * For legacy DRI.
- *
- * \param scrn Index of the screen
- * \param ddx_version Version of the 2D DDX. This may not be meaningful for
- * all drivers.
- * \param dri_version Version of the "server-side" DRI.
- * \param drm_version Version of the kernel DRM.
- * \param frame_buffer Data describing the location and layout of the
- * framebuffer.
- * \param pSAREA Pointer to the SAREA.
- * \param fd Device handle for the DRM.
- * \param extensions ??
- * \param driver_modes Returns modes suppoted by the driver
- * \param loaderPrivate ??
- *
- * \note There is no need to check the minimum API version in this
- * function. Since the name of this function is versioned, it is
- * impossible for a loader that is too old to even load this driver.
- */
-static __DRIscreen *
-driCreateNewScreen(int scrn,
- const __DRIversion *ddx_version,
- const __DRIversion *dri_version,
- const __DRIversion *drm_version,
- const __DRIframebuffer *frame_buffer,
- drmAddress pSAREA, int fd,
- const __DRIextension **extensions,
- const __DRIconfig ***driver_modes,
- void *loaderPrivate)
-{
- static const __DRIextension *emptyExtensionList[] = { NULL };
- __DRIscreen *psp;
-
- if (driDriverAPI.InitScreen == NULL)
- return NULL;
-
- psp = calloc(1, sizeof *psp);
- if (!psp)
- return NULL;
-
- setupLoaderExtensions(psp, extensions);
-
- /*
- ** NOT_DONE: This is used by the X server to detect when the client
- ** has died while holding the drawable lock. The client sets the
- ** drawable lock to this value.
- */
- psp->drawLockID = 1;
-
- psp->drm_version = *drm_version;
- psp->ddx_version = *ddx_version;
- psp->dri_version = *dri_version;
-
- psp->pSAREA = pSAREA;
- psp->lock = (drmLock *) &psp->pSAREA->lock;
-
- psp->pFB = frame_buffer->base;
- psp->fbSize = frame_buffer->size;
- psp->fbStride = frame_buffer->stride;
- psp->fbWidth = frame_buffer->width;
- psp->fbHeight = frame_buffer->height;
- psp->devPrivSize = frame_buffer->dev_priv_size;
- psp->pDevPriv = frame_buffer->dev_priv;
- psp->fbBPP = psp->fbStride * 8 / frame_buffer->width;
-
- psp->extensions = emptyExtensionList;
- psp->fd = fd;
- psp->myNum = scrn;
- psp->dri2.enabled = GL_FALSE;
-
- psp->DriverAPI = driDriverAPI;
- psp->api_mask = (1 << __DRI_API_OPENGL);
-
- *driver_modes = driDriverAPI.InitScreen(psp);
- if (*driver_modes == NULL) {
- free(psp);
- return NULL;
- }
-
- return psp;
-}
-
-/**
- * DRI2
- */
-static __DRIscreen *
-dri2CreateNewScreen(int scrn, int fd,
- const __DRIextension **extensions,
- const __DRIconfig ***driver_configs, void *data)
-{
- static const __DRIextension *emptyExtensionList[] = { NULL };
- __DRIscreen *psp;
- drmVersionPtr version;
-
- if (driDriverAPI.InitScreen2 == NULL)
- return NULL;
-
- psp = calloc(1, sizeof(*psp));
- if (!psp)
- return NULL;
-
- setupLoaderExtensions(psp, extensions);
-
- version = drmGetVersion(fd);
- if (version) {
- psp->drm_version.major = version->version_major;
- psp->drm_version.minor = version->version_minor;
- psp->drm_version.patch = version->version_patchlevel;
- drmFreeVersion(version);
- }
-
- psp->extensions = emptyExtensionList;
- psp->fd = fd;
- psp->myNum = scrn;
- psp->dri2.enabled = GL_TRUE;
-
- psp->DriverAPI = driDriverAPI;
- psp->api_mask = (1 << __DRI_API_OPENGL);
- *driver_configs = driDriverAPI.InitScreen2(psp);
- if (*driver_configs == NULL) {
- free(psp);
- return NULL;
- }
-
- psp->DriverAPI = driDriverAPI;
- psp->loaderPrivate = data;
-
- driParseOptionInfo(&psp->optionInfo, __dri2ConfigOptions,
- __dri2NConfigOptions);
- driParseConfigFiles(&psp->optionCache, &psp->optionInfo, psp->myNum,
- "dri2");
-
- return psp;
-}
-
-static const __DRIextension **driGetExtensions(__DRIscreen *psp)
-{
- return psp->extensions;
-}
-
-/** Core interface */
-const __DRIcoreExtension driCoreExtension = {
- { __DRI_CORE, __DRI_CORE_VERSION },
- NULL,
- driDestroyScreen,
- driGetExtensions,
- driGetConfigAttrib,
- driIndexConfigAttrib,
- NULL,
- driDestroyDrawable,
- driSwapBuffers,
- NULL,
- driCopyContext,
- driDestroyContext,
- driBindContext,
- driUnbindContext
-};
-
-/** Legacy DRI interface */
-const __DRIlegacyExtension driLegacyExtension = {
- { __DRI_LEGACY, __DRI_LEGACY_VERSION },
- driCreateNewScreen,
- driCreateNewDrawable,
- driCreateNewContext,
-};
-
-/** DRI2 interface */
-const __DRIdri2Extension driDRI2Extension = {
- { __DRI_DRI2, __DRI_DRI2_VERSION },
- dri2CreateNewScreen,
- dri2CreateNewDrawable,
- dri2CreateNewContext,
- dri2GetAPIMask,
- dri2CreateNewContextForAPI,
- dri2AllocateBuffer,
- dri2ReleaseBuffer
-};
-
-const __DRI2configQueryExtension dri2ConfigQueryExtension = {
- { __DRI2_CONFIG_QUERY, __DRI2_CONFIG_QUERY_VERSION },
- dri2ConfigQueryb,
- dri2ConfigQueryi,
- dri2ConfigQueryf,
-};
-
-/**
- * Calculate amount of swap interval used between GLX buffer swaps.
- *
- * The usage value, on the range [0,max], is the fraction of total swap
- * interval time used between GLX buffer swaps is calculated.
- *
- * \f$p = t_d / (i * t_r)\f$
- *
- * Where \f$t_d\f$ is the time since the last GLX buffer swap, \f$i\f$ is the
- * swap interval (as set by \c glXSwapIntervalSGI), and \f$t_r\f$ time
- * required for a single vertical refresh period (as returned by \c
- * glXGetMscRateOML).
- *
- * See the documentation for the GLX_MESA_swap_frame_usage extension for more
- * details.
- *
- * \param dPriv Pointer to the private drawable structure.
- * \return If less than a single swap interval time period was required
- * between GLX buffer swaps, a number greater than 0 and less than
- * 1.0 is returned. If exactly one swap interval time period is
- * required, 1.0 is returned, and if more than one is required then
- * a number greater than 1.0 will be returned.
- *
- * \sa glXSwapIntervalSGI glXGetMscRateOML
- *
- * \todo Instead of caching the \c glXGetMscRateOML function pointer, would it
- * be possible to cache the sync rate?
- */
-float
-driCalculateSwapUsage( __DRIdrawable *dPriv, int64_t last_swap_ust,
- int64_t current_ust )
-{
- int32_t n;
- int32_t d;
- int interval;
- float usage = 1.0;
- __DRIscreen *psp = dPriv->driScreenPriv;
-
- if ( (*psp->systemTime->getMSCRate)(dPriv, &n, &d, dPriv->loaderPrivate) ) {
- interval = (dPriv->swap_interval != 0) ? dPriv->swap_interval : 1;
-
-
- /* We want to calculate
- * (current_UST - last_swap_UST) / (interval * us_per_refresh). We get
- * current_UST by calling __glXGetUST. last_swap_UST is stored in
- * dPriv->swap_ust. interval has already been calculated.
- *
- * The only tricky part is us_per_refresh. us_per_refresh is
- * 1000000 / MSC_rate. We know the MSC_rate is n / d. We can flip it
- * around and say us_per_refresh = 1000000 * d / n. Since this goes in
- * the denominator of the final calculation, we calculate
- * (interval * 1000000 * d) and move n into the numerator.
- */
-
- usage = (current_ust - last_swap_ust);
- usage *= n;
- usage /= (interval * d);
- usage /= 1000000.0;
- }
-
- return usage;
-}
-
-void
-dri2InvalidateDrawable(__DRIdrawable *drawable)
-{
- drawable->dri2.stamp++;
-}
-
-/*@}*/
+/**
+ * \file dri_util.c
+ * DRI utility functions.
+ *
+ * This module acts as glue between GLX and the actual hardware driver. A DRI
+ * driver doesn't really \e have to use any of this - it's optional. But, some
+ * useful stuff is done here that otherwise would have to be duplicated in most
+ * drivers.
+ *
+ * Basically, these utility functions take care of some of the dirty details of
+ * screen initialization, context creation, context binding, DRM setup, etc.
+ *
+ * These functions are compiled into each DRI driver so libGL.so knows nothing
+ * about them.
+ */
+
+
+#include <assert.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <sys/mman.h>
+#include <stdio.h>
+
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void *)-1)
+#endif
+
+#include "main/imports.h"
+#define None 0
+
+#include "dri_util.h"
+#include "drm_sarea.h"
+#include "utils.h"
+#include "xmlpool.h"
+#include "../glsl/glsl_parser_extras.h"
+
+PUBLIC const char __dri2ConfigOptions[] =
+ DRI_CONF_BEGIN
+ DRI_CONF_SECTION_PERFORMANCE
+ DRI_CONF_VBLANK_MODE(DRI_CONF_VBLANK_DEF_INTERVAL_1)
+ DRI_CONF_SECTION_END
+ DRI_CONF_END;
+
+static const uint __dri2NConfigOptions = 1;
+
+#ifndef GLX_OML_sync_control
+typedef GLboolean ( * PFNGLXGETMSCRATEOMLPROC) (__DRIdrawable *drawable, int32_t *numerator, int32_t *denominator);
+#endif
+
+static void dri_get_drawable(__DRIdrawable *pdp);
+static void dri_put_drawable(__DRIdrawable *pdp);
+
+/**
+ * This is just a token extension used to signal that the driver
+ * supports setting a read drawable.
+ */
+const __DRIextension driReadDrawableExtension = {
+ __DRI_READ_DRAWABLE, __DRI_READ_DRAWABLE_VERSION
+};
+
+GLint
+driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 )
+{
+ if (rect2.x1 > rect1.x1) rect1.x1 = rect2.x1;
+ if (rect2.x2 < rect1.x2) rect1.x2 = rect2.x2;
+ if (rect2.y1 > rect1.y1) rect1.y1 = rect2.y1;
+ if (rect2.y2 < rect1.y2) rect1.y2 = rect2.y2;
+
+ if (rect1.x1 > rect1.x2 || rect1.y1 > rect1.y2) return 0;
+
+ return (rect1.x2 - rect1.x1) * (rect1.y2 - rect1.y1);
+}
+
+/*****************************************************************/
+/** \name Context (un)binding functions */
+/*****************************************************************/
+/*@{*/
+
+/**
+ * Unbind context.
+ *
+ * \param scrn the screen.
+ * \param gc context.
+ *
+ * \return \c GL_TRUE on success, or \c GL_FALSE on failure.
+ *
+ * \internal
+ * This function calls __DriverAPIRec::UnbindContext, and then decrements
+ * __DRIdrawableRec::refcount which must be non-zero for a successful
+ * return.
+ *
+ * While casting the opaque private pointers associated with the parameters
+ * into their respective real types it also assures they are not \c NULL.
+ */
+static int driUnbindContext(__DRIcontext *pcp)
+{
+ __DRIscreen *psp;
+ __DRIdrawable *pdp;
+ __DRIdrawable *prp;
+
+ /*
+ ** Assume error checking is done properly in glXMakeCurrent before
+ ** calling driUnbindContext.
+ */
+
+ if (pcp == NULL)
+ return GL_FALSE;
+
+ psp = pcp->driScreenPriv;
+ pdp = pcp->driDrawablePriv;
+ prp = pcp->driReadablePriv;
+
+ /* already unbound */
+ if (!pdp && !prp)
+ return GL_TRUE;
+ /* Let driver unbind drawable from context */
+ (*psp->DriverAPI.UnbindContext)(pcp);
+
+ assert(pdp);
+ if (pdp->refcount == 0) {
+ /* ERROR!!! */
+ return GL_FALSE;
+ }
+
+ dri_put_drawable(pdp);
+
+ if (prp != pdp) {
+ if (prp->refcount == 0) {
+ /* ERROR!!! */
+ return GL_FALSE;
+ }
+
+ dri_put_drawable(prp);
+ }
+
+
+ /* XXX this is disabled so that if we call SwapBuffers on an unbound
+ * window we can determine the last context bound to the window and
+ * use that context's lock. (BrianP, 2-Dec-2000)
+ */
+ pcp->driDrawablePriv = pcp->driReadablePriv = NULL;
+
+ return GL_TRUE;
+}
+
+/**
+ * This function takes both a read buffer and a draw buffer. This is needed
+ * for \c glXMakeCurrentReadSGI or GLX 1.3's \c glXMakeContextCurrent
+ * function.
+ */
+static int driBindContext(__DRIcontext *pcp,
+ __DRIdrawable *pdp,
+ __DRIdrawable *prp)
+{
+ __DRIscreen *psp = NULL;
+
+ /*
+ ** Assume error checking is done properly in glXMakeCurrent before
+ ** calling driUnbindContext.
+ */
+
+ if (!pcp)
+ return GL_FALSE;
+
+ /* Bind the drawable to the context */
+ psp = pcp->driScreenPriv;
+ pcp->driDrawablePriv = pdp;
+ pcp->driReadablePriv = prp;
+ if (pdp) {
+ pdp->driContextPriv = pcp;
+ dri_get_drawable(pdp);
+ }
+ if (prp && pdp != prp) {
+ dri_get_drawable(prp);
+ }
+
+ /*
+ ** Now that we have a context associated with this drawable, we can
+ ** initialize the drawable information if has not been done before.
+ */
+
+ if (!psp->dri2.enabled) {
+ if (pdp && !pdp->pStamp) {
+ DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+ __driUtilUpdateDrawableInfo(pdp);
+ DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+ }
+ if (prp && pdp != prp && !prp->pStamp) {
+ DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+ __driUtilUpdateDrawableInfo(prp);
+ DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+ }
+ }
+
+ /* Call device-specific MakeCurrent */
+ return (*psp->DriverAPI.MakeCurrent)(pcp, pdp, prp);
+}
+
+/*@}*/
+
+
+/*****************************************************************/
+/** \name Drawable handling functions */
+/*****************************************************************/
+/*@{*/
+
+/**
+ * Update private drawable information.
+ *
+ * \param pdp pointer to the private drawable information to update.
+ *
+ * This function basically updates the __DRIdrawable struct's
+ * cliprect information by calling \c __DRIinterfaceMethods::getDrawableInfo.
+ * This is usually called by the DRI_VALIDATE_DRAWABLE_INFO macro which
+ * compares the __DRIdrwablePrivate pStamp and lastStamp values. If
+ * the values are different that means we have to update the clipping
+ * info.
+ */
+void
+__driUtilUpdateDrawableInfo(__DRIdrawable *pdp)
+{
+ __DRIscreen *psp = pdp->driScreenPriv;
+ __DRIcontext *pcp = pdp->driContextPriv;
+
+ if (!pcp
+ || ((pdp != pcp->driDrawablePriv) && (pdp != pcp->driReadablePriv))) {
+ /* ERROR!!!
+ * ...but we must ignore it. There can be many contexts bound to a
+ * drawable.
+ */
+ }
+
+ if (pdp->pClipRects) {
+ free(pdp->pClipRects);
+ pdp->pClipRects = NULL;
+ }
+
+ if (pdp->pBackClipRects) {
+ free(pdp->pBackClipRects);
+ pdp->pBackClipRects = NULL;
+ }
+
+ DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+
+ if (! (*psp->getDrawableInfo->getDrawableInfo)(pdp,
+ &pdp->index, &pdp->lastStamp,
+ &pdp->x, &pdp->y, &pdp->w, &pdp->h,
+ &pdp->numClipRects, &pdp->pClipRects,
+ &pdp->backX,
+ &pdp->backY,
+ &pdp->numBackClipRects,
+ &pdp->pBackClipRects,
+ pdp->loaderPrivate)) {
+ /* Error -- eg the window may have been destroyed. Keep going
+ * with no cliprects.
+ */
+ pdp->pStamp = &pdp->lastStamp; /* prevent endless loop */
+ pdp->numClipRects = 0;
+ pdp->pClipRects = NULL;
+ pdp->numBackClipRects = 0;
+ pdp->pBackClipRects = NULL;
+ }
+ else
+ pdp->pStamp = &(psp->pSAREA->drawableTable[pdp->index].stamp);
+
+ DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID);
+}
+
+/*@}*/
+
+/*****************************************************************/
+/** \name GLX callbacks */
+/*****************************************************************/
+/*@{*/
+
+static void driReportDamage(__DRIdrawable *pdp,
+ struct drm_clip_rect *pClipRects, int numClipRects)
+{
+ __DRIscreen *psp = pdp->driScreenPriv;
+
+ /* Check that we actually have the new damage report method */
+ if (psp->damage) {
+ /* Report the damage. Currently, all our drivers draw
+ * directly to the front buffer, so we report the damage there
+ * rather than to the backing storein (if any).
+ */
+ (*psp->damage->reportDamage)(pdp,
+ pdp->x, pdp->y,
+ pClipRects, numClipRects,
+ GL_TRUE, pdp->loaderPrivate);
+ }
+}
+
+
+/**
+ * Swap buffers.
+ *
+ * \param drawablePrivate opaque pointer to the per-drawable private info.
+ *
+ * \internal
+ * This function calls __DRIdrawable::swapBuffers.
+ *
+ * Is called directly from glXSwapBuffers().
+ */
+static void driSwapBuffers(__DRIdrawable *dPriv)
+{
+ __DRIscreen *psp = dPriv->driScreenPriv;
+ drm_clip_rect_t *rects;
+ int i;
+
+ psp->DriverAPI.SwapBuffers(dPriv);
+
+ if (!dPriv->numClipRects)
+ return;
+
+ rects = malloc(sizeof(*rects) * dPriv->numClipRects);
+
+ if (!rects)
+ return;
+
+ for (i = 0; i < dPriv->numClipRects; i++) {
+ rects[i].x1 = dPriv->pClipRects[i].x1 - dPriv->x;
+ rects[i].y1 = dPriv->pClipRects[i].y1 - dPriv->y;
+ rects[i].x2 = dPriv->pClipRects[i].x2 - dPriv->x;
+ rects[i].y2 = dPriv->pClipRects[i].y2 - dPriv->y;
+ }
+
+ driReportDamage(dPriv, rects, dPriv->numClipRects);
+ free(rects);
+}
+
+static int driDrawableGetMSC( __DRIscreen *sPriv, __DRIdrawable *dPriv,
+ int64_t *msc )
+{
+ return sPriv->DriverAPI.GetDrawableMSC(sPriv, dPriv, msc);
+}
+
+
+static int driWaitForMSC(__DRIdrawable *dPriv, int64_t target_msc,
+ int64_t divisor, int64_t remainder,
+ int64_t * msc, int64_t * sbc)
+{
+ __DRIswapInfo sInfo;
+ int status;
+
+ status = dPriv->driScreenPriv->DriverAPI.WaitForMSC( dPriv, target_msc,
+ divisor, remainder,
+ msc );
+
+ /* GetSwapInfo() may not be provided by the driver if GLX_SGI_video_sync
+ * is supported but GLX_OML_sync_control is not. Therefore, don't return
+ * an error value if GetSwapInfo() is not implemented.
+ */
+ if ( status == 0
+ && dPriv->driScreenPriv->DriverAPI.GetSwapInfo ) {
+ status = dPriv->driScreenPriv->DriverAPI.GetSwapInfo( dPriv, & sInfo );
+ *sbc = sInfo.swap_count;
+ }
+
+ return status;
+}
+
+
+const __DRImediaStreamCounterExtension driMediaStreamCounterExtension = {
+ { __DRI_MEDIA_STREAM_COUNTER, __DRI_MEDIA_STREAM_COUNTER_VERSION },
+ driWaitForMSC,
+ driDrawableGetMSC,
+};
+
+
+static void driCopySubBuffer(__DRIdrawable *dPriv,
+ int x, int y, int w, int h)
+{
+ drm_clip_rect_t rect;
+
+ rect.x1 = x;
+ rect.y1 = dPriv->h - y - h;
+ rect.x2 = x + w;
+ rect.y2 = rect.y1 + h;
+ driReportDamage(dPriv, &rect, 1);
+
+ dPriv->driScreenPriv->DriverAPI.CopySubBuffer(dPriv, x, y, w, h);
+}
+
+const __DRIcopySubBufferExtension driCopySubBufferExtension = {
+ { __DRI_COPY_SUB_BUFFER, __DRI_COPY_SUB_BUFFER_VERSION },
+ driCopySubBuffer
+};
+
+static void driSetSwapInterval(__DRIdrawable *dPriv, unsigned int interval)
+{
+ dPriv->swap_interval = interval;
+}
+
+static unsigned int driGetSwapInterval(__DRIdrawable *dPriv)
+{
+ return dPriv->swap_interval;
+}
+
+const __DRIswapControlExtension driSwapControlExtension = {
+ { __DRI_SWAP_CONTROL, __DRI_SWAP_CONTROL_VERSION },
+ driSetSwapInterval,
+ driGetSwapInterval
+};
+
+
+/**
+ * This is called via __DRIscreenRec's createNewDrawable pointer.
+ */
+static __DRIdrawable *
+driCreateNewDrawable(__DRIscreen *psp, const __DRIconfig *config,
+ drm_drawable_t hwDrawable, int renderType,
+ const int *attrs, void *data)
+{
+ __DRIdrawable *pdp;
+
+ /* Since pbuffers are not yet supported, no drawable attributes are
+ * supported either.
+ */
+ (void) attrs;
+
+ pdp = malloc(sizeof *pdp);
+ if (!pdp) {
+ return NULL;
+ }
+
+ pdp->driContextPriv = NULL;
+ pdp->loaderPrivate = data;
+ pdp->hHWDrawable = hwDrawable;
+ pdp->refcount = 1;
+ pdp->pStamp = NULL;
+ pdp->lastStamp = 0;
+ pdp->index = 0;
+ pdp->x = 0;
+ pdp->y = 0;
+ pdp->w = 0;
+ pdp->h = 0;
+ pdp->numClipRects = 0;
+ pdp->numBackClipRects = 0;
+ pdp->pClipRects = NULL;
+ pdp->pBackClipRects = NULL;
+ pdp->vblSeq = 0;
+ pdp->vblFlags = 0;
+
+ pdp->driScreenPriv = psp;
+
+ if (!(*psp->DriverAPI.CreateBuffer)(psp, pdp, &config->modes, 0)) {
+ free(pdp);
+ return NULL;
+ }
+
+ pdp->msc_base = 0;
+
+ /* This special default value is replaced with the configured
+ * default value when the drawable is first bound to a direct
+ * rendering context.
+ */
+ pdp->swap_interval = (unsigned)-1;
+
+ return pdp;
+}
+
+
+static __DRIdrawable *
+dri2CreateNewDrawable(__DRIscreen *screen,
+ const __DRIconfig *config,
+ void *loaderPrivate)
+{
+ __DRIdrawable *pdraw;
+
+ pdraw = driCreateNewDrawable(screen, config, 0, 0, NULL, loaderPrivate);
+ if (!pdraw)
+ return NULL;
+
+ pdraw->pClipRects = &pdraw->dri2.clipRect;
+ pdraw->pBackClipRects = &pdraw->dri2.clipRect;
+
+ pdraw->pStamp = &pdraw->dri2.stamp;
+ *pdraw->pStamp = pdraw->lastStamp + 1;
+
+ return pdraw;
+}
+
+static __DRIbuffer *
+dri2AllocateBuffer(__DRIscreen *screen,
+ unsigned int attachment, unsigned int format,
+ int width, int height)
+{
+ return (*screen->DriverAPI.AllocateBuffer)(screen, attachment, format,
+ width, height);
+}
+
+static void
+dri2ReleaseBuffer(__DRIscreen *screen, __DRIbuffer *buffer)
+{
+ (*screen->DriverAPI.ReleaseBuffer)(screen, buffer);
+}
+
+
+static int
+dri2ConfigQueryb(__DRIscreen *screen, const char *var, GLboolean *val)
+{
+ if (!driCheckOption(&screen->optionCache, var, DRI_BOOL))
+ return -1;
+
+ *val = driQueryOptionb(&screen->optionCache, var);
+
+ return 0;
+}
+
+static int
+dri2ConfigQueryi(__DRIscreen *screen, const char *var, GLint *val)
+{
+ if (!driCheckOption(&screen->optionCache, var, DRI_INT) &&
+ !driCheckOption(&screen->optionCache, var, DRI_ENUM))
+ return -1;
+
+ *val = driQueryOptioni(&screen->optionCache, var);
+
+ return 0;
+}
+
+static int
+dri2ConfigQueryf(__DRIscreen *screen, const char *var, GLfloat *val)
+{
+ if (!driCheckOption(&screen->optionCache, var, DRI_FLOAT))
+ return -1;
+
+ *val = driQueryOptionf(&screen->optionCache, var);
+
+ return 0;
+}
+
+
+static void dri_get_drawable(__DRIdrawable *pdp)
+{
+ pdp->refcount++;
+}
+
+static void dri_put_drawable(__DRIdrawable *pdp)
+{
+ __DRIscreen *psp;
+
+ if (pdp) {
+ pdp->refcount--;
+ if (pdp->refcount)
+ return;
+
+ psp = pdp->driScreenPriv;
+ (*psp->DriverAPI.DestroyBuffer)(pdp);
+ if (pdp->pClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
+ free(pdp->pClipRects);
+ pdp->pClipRects = NULL;
+ }
+ if (pdp->pBackClipRects && pdp->pClipRects != &pdp->dri2.clipRect) {
+ free(pdp->pBackClipRects);
+ pdp->pBackClipRects = NULL;
+ }
+ free(pdp);
+ }
+}
+
+static void
+driDestroyDrawable(__DRIdrawable *pdp)
+{
+ dri_put_drawable(pdp);
+}
+
+/*@}*/
+
+
+/*****************************************************************/
+/** \name Context handling functions */
+/*****************************************************************/
+/*@{*/
+
+/**
+ * Destroy the per-context private information.
+ *
+ * \internal
+ * This function calls __DriverAPIRec::DestroyContext on \p contextPrivate, calls
+ * drmDestroyContext(), and finally frees \p contextPrivate.
+ */
+static void
+driDestroyContext(__DRIcontext *pcp)
+{
+ if (pcp) {
+ (*pcp->driScreenPriv->DriverAPI.DestroyContext)(pcp);
+ free(pcp);
+ }
+}
+
+
+/**
+ * Create the per-drawable private driver information.
+ *
+ * \param render_type Type of rendering target. \c GLX_RGBA is the only
+ * type likely to ever be supported for direct-rendering.
+ * \param shared Context with which to share textures, etc. or NULL
+ *
+ * \returns An opaque pointer to the per-context private information on
+ * success, or \c NULL on failure.
+ *
+ * \internal
+ * This function allocates and fills a __DRIcontextRec structure. It
+ * performs some device independent initialization and passes all the
+ * relevent information to __DriverAPIRec::CreateContext to create the
+ * context.
+ *
+ */
+static __DRIcontext *
+driCreateNewContext(__DRIscreen *psp, const __DRIconfig *config,
+ int render_type, __DRIcontext *shared,
+ drm_context_t hwContext, void *data)
+{
+ __DRIcontext *pcp;
+ void * const shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
+
+ pcp = malloc(sizeof *pcp);
+ if (!pcp)
+ return NULL;
+
+ pcp->driScreenPriv = psp;
+ pcp->driDrawablePriv = NULL;
+ pcp->loaderPrivate = data;
+
+ pcp->dri2.draw_stamp = 0;
+ pcp->dri2.read_stamp = 0;
+
+ pcp->hHWContext = hwContext;
+
+ if ( !(*psp->DriverAPI.CreateContext)(API_OPENGL,
+ &config->modes, pcp, shareCtx) ) {
+ free(pcp);
+ return NULL;
+ }
+
+ return pcp;
+}
+
+static unsigned int
+dri2GetAPIMask(__DRIscreen *screen)
+{
+ return screen->api_mask;
+}
+
+static __DRIcontext *
+dri2CreateNewContextForAPI(__DRIscreen *screen, int api,
+ const __DRIconfig *config,
+ __DRIcontext *shared, void *data)
+{
+ __DRIcontext *context;
+ const struct gl_config *modes = (config != NULL) ? &config->modes : NULL;
+ void *shareCtx = (shared != NULL) ? shared->driverPrivate : NULL;
+ gl_api mesa_api;
+
+ if (!(screen->api_mask & (1 << api)))
+ return NULL;
+
+ switch (api) {
+ case __DRI_API_OPENGL:
+ mesa_api = API_OPENGL;
+ break;
+ case __DRI_API_GLES:
+ mesa_api = API_OPENGLES;
+ break;
+ case __DRI_API_GLES2:
+ mesa_api = API_OPENGLES2;
+ break;
+ default:
+ return NULL;
+ }
+
+ context = malloc(sizeof *context);
+ if (!context)
+ return NULL;
+
+ context->driScreenPriv = screen;
+ context->driDrawablePriv = NULL;
+ context->loaderPrivate = data;
+
+ if (!(*screen->DriverAPI.CreateContext)(mesa_api, modes,
+ context, shareCtx) ) {
+ free(context);
+ return NULL;
+ }
+
+ return context;
+}
+
+
+static __DRIcontext *
+dri2CreateNewContext(__DRIscreen *screen, const __DRIconfig *config,
+ __DRIcontext *shared, void *data)
+{
+ return dri2CreateNewContextForAPI(screen, __DRI_API_OPENGL,
+ config, shared, data);
+}
+
+static int
+driCopyContext(__DRIcontext *dest, __DRIcontext *src, unsigned long mask)
+{
+ return GL_FALSE;
+}
+
+/*@}*/
+
+
+/*****************************************************************/
+/** \name Screen handling functions */
+/*****************************************************************/
+/*@{*/
+
+/**
+ * Destroy the per-screen private information.
+ *
+ * \internal
+ * This function calls __DriverAPIRec::DestroyScreen on \p screenPrivate, calls
+ * drmClose(), and finally frees \p screenPrivate.
+ */
+static void driDestroyScreen(__DRIscreen *psp)
+{
+ if (psp) {
+ /* No interaction with the X-server is possible at this point. This
+ * routine is called after XCloseDisplay, so there is no protocol
+ * stream open to the X-server anymore.
+ */
+
+ _mesa_destroy_shader_compiler();
+
+ if (psp->DriverAPI.DestroyScreen)
+ (*psp->DriverAPI.DestroyScreen)(psp);
+
+ if (!psp->dri2.enabled) {
+ (void)drmUnmap((drmAddress)psp->pSAREA, SAREA_MAX);
+ (void)drmUnmap((drmAddress)psp->pFB, psp->fbSize);
+ (void)drmCloseOnce(psp->fd);
+ } else {
+ driDestroyOptionCache(&psp->optionCache);
+ driDestroyOptionInfo(&psp->optionInfo);
+ }
+
+ free(psp);
+ }
+}
+
+static void
+setupLoaderExtensions(__DRIscreen *psp,
+ const __DRIextension **extensions)
+{
+ int i;
+
+ for (i = 0; extensions[i]; i++) {
+ if (strcmp(extensions[i]->name, __DRI_GET_DRAWABLE_INFO) == 0)
+ psp->getDrawableInfo = (__DRIgetDrawableInfoExtension *) extensions[i];
+ if (strcmp(extensions[i]->name, __DRI_DAMAGE) == 0)
+ psp->damage = (__DRIdamageExtension *) extensions[i];
+ if (strcmp(extensions[i]->name, __DRI_SYSTEM_TIME) == 0)
+ psp->systemTime = (__DRIsystemTimeExtension *) extensions[i];
+ if (strcmp(extensions[i]->name, __DRI_DRI2_LOADER) == 0)
+ psp->dri2.loader = (__DRIdri2LoaderExtension *) extensions[i];
+ if (strcmp(extensions[i]->name, __DRI_IMAGE_LOOKUP) == 0)
+ psp->dri2.image = (__DRIimageLookupExtension *) extensions[i];
+ if (strcmp(extensions[i]->name, __DRI_USE_INVALIDATE) == 0)
+ psp->dri2.useInvalidate = (__DRIuseInvalidateExtension *) extensions[i];
+ }
+}
+
+/**
+ * This is the bootstrap function for the driver. libGL supplies all of the
+ * requisite information about the system, and the driver initializes itself.
+ * This routine also fills in the linked list pointed to by \c driver_modes
+ * with the \c struct gl_config that the driver can support for windows or
+ * pbuffers.
+ *
+ * For legacy DRI.
+ *
+ * \param scrn Index of the screen
+ * \param ddx_version Version of the 2D DDX. This may not be meaningful for
+ * all drivers.
+ * \param dri_version Version of the "server-side" DRI.
+ * \param drm_version Version of the kernel DRM.
+ * \param frame_buffer Data describing the location and layout of the
+ * framebuffer.
+ * \param pSAREA Pointer to the SAREA.
+ * \param fd Device handle for the DRM.
+ * \param extensions ??
+ * \param driver_modes Returns modes suppoted by the driver
+ * \param loaderPrivate ??
+ *
+ * \note There is no need to check the minimum API version in this
+ * function. Since the name of this function is versioned, it is
+ * impossible for a loader that is too old to even load this driver.
+ */
+static __DRIscreen *
+driCreateNewScreen(int scrn,
+ const __DRIversion *ddx_version,
+ const __DRIversion *dri_version,
+ const __DRIversion *drm_version,
+ const __DRIframebuffer *frame_buffer,
+ drmAddress pSAREA, int fd,
+ const __DRIextension **extensions,
+ const __DRIconfig ***driver_modes,
+ void *loaderPrivate)
+{
+ static const __DRIextension *emptyExtensionList[] = { NULL };
+ __DRIscreen *psp;
+
+ if (driDriverAPI.InitScreen == NULL)
+ return NULL;
+
+ psp = calloc(1, sizeof *psp);
+ if (!psp)
+ return NULL;
+
+ setupLoaderExtensions(psp, extensions);
+
+ /*
+ ** NOT_DONE: This is used by the X server to detect when the client
+ ** has died while holding the drawable lock. The client sets the
+ ** drawable lock to this value.
+ */
+ psp->drawLockID = 1;
+
+ psp->drm_version = *drm_version;
+ psp->ddx_version = *ddx_version;
+ psp->dri_version = *dri_version;
+
+ psp->pSAREA = pSAREA;
+ psp->lock = (drmLock *) &psp->pSAREA->lock;
+
+ psp->pFB = frame_buffer->base;
+ psp->fbSize = frame_buffer->size;
+ psp->fbStride = frame_buffer->stride;
+ psp->fbWidth = frame_buffer->width;
+ psp->fbHeight = frame_buffer->height;
+ psp->devPrivSize = frame_buffer->dev_priv_size;
+ psp->pDevPriv = frame_buffer->dev_priv;
+ psp->fbBPP = psp->fbStride * 8 / frame_buffer->width;
+
+ psp->extensions = emptyExtensionList;
+ psp->fd = fd;
+ psp->myNum = scrn;
+ psp->dri2.enabled = GL_FALSE;
+
+ psp->DriverAPI = driDriverAPI;
+ psp->api_mask = (1 << __DRI_API_OPENGL);
+
+ *driver_modes = driDriverAPI.InitScreen(psp);
+ if (*driver_modes == NULL) {
+ free(psp);
+ return NULL;
+ }
+
+ return psp;
+}
+
+/**
+ * DRI2
+ */
+static __DRIscreen *
+dri2CreateNewScreen(int scrn, int fd,
+ const __DRIextension **extensions,
+ const __DRIconfig ***driver_configs, void *data)
+{
+ static const __DRIextension *emptyExtensionList[] = { NULL };
+ __DRIscreen *psp;
+ drmVersionPtr version;
+
+ if (driDriverAPI.InitScreen2 == NULL)
+ return NULL;
+
+ psp = calloc(1, sizeof(*psp));
+ if (!psp)
+ return NULL;
+
+ setupLoaderExtensions(psp, extensions);
+
+ version = drmGetVersion(fd);
+ if (version) {
+ psp->drm_version.major = version->version_major;
+ psp->drm_version.minor = version->version_minor;
+ psp->drm_version.patch = version->version_patchlevel;
+ drmFreeVersion(version);
+ }
+
+ psp->extensions = emptyExtensionList;
+ psp->fd = fd;
+ psp->myNum = scrn;
+ psp->dri2.enabled = GL_TRUE;
+
+ psp->DriverAPI = driDriverAPI;
+ psp->api_mask = (1 << __DRI_API_OPENGL);
+ *driver_configs = driDriverAPI.InitScreen2(psp);
+ if (*driver_configs == NULL) {
+ free(psp);
+ return NULL;
+ }
+
+ psp->DriverAPI = driDriverAPI;
+ psp->loaderPrivate = data;
+
+ driParseOptionInfo(&psp->optionInfo, __dri2ConfigOptions,
+ __dri2NConfigOptions);
+ driParseConfigFiles(&psp->optionCache, &psp->optionInfo, psp->myNum,
+ "dri2");
+
+ return psp;
+}
+
+static const __DRIextension **driGetExtensions(__DRIscreen *psp)
+{
+ return psp->extensions;
+}
+
+/** Core interface */
+const __DRIcoreExtension driCoreExtension = {
+ { __DRI_CORE, __DRI_CORE_VERSION },
+ NULL,
+ driDestroyScreen,
+ driGetExtensions,
+ driGetConfigAttrib,
+ driIndexConfigAttrib,
+ NULL,
+ driDestroyDrawable,
+ driSwapBuffers,
+ NULL,
+ driCopyContext,
+ driDestroyContext,
+ driBindContext,
+ driUnbindContext
+};
+
+/** Legacy DRI interface */
+const __DRIlegacyExtension driLegacyExtension = {
+ { __DRI_LEGACY, __DRI_LEGACY_VERSION },
+ driCreateNewScreen,
+ driCreateNewDrawable,
+ driCreateNewContext,
+};
+
+/** DRI2 interface */
+const __DRIdri2Extension driDRI2Extension = {
+ { __DRI_DRI2, __DRI_DRI2_VERSION },
+ dri2CreateNewScreen,
+ dri2CreateNewDrawable,
+ dri2CreateNewContext,
+ dri2GetAPIMask,
+ dri2CreateNewContextForAPI,
+ dri2AllocateBuffer,
+ dri2ReleaseBuffer
+};
+
+const __DRI2configQueryExtension dri2ConfigQueryExtension = {
+ { __DRI2_CONFIG_QUERY, __DRI2_CONFIG_QUERY_VERSION },
+ dri2ConfigQueryb,
+ dri2ConfigQueryi,
+ dri2ConfigQueryf,
+};
+
+/**
+ * Calculate amount of swap interval used between GLX buffer swaps.
+ *
+ * The usage value, on the range [0,max], is the fraction of total swap
+ * interval time used between GLX buffer swaps is calculated.
+ *
+ * \f$p = t_d / (i * t_r)\f$
+ *
+ * Where \f$t_d\f$ is the time since the last GLX buffer swap, \f$i\f$ is the
+ * swap interval (as set by \c glXSwapIntervalSGI), and \f$t_r\f$ time
+ * required for a single vertical refresh period (as returned by \c
+ * glXGetMscRateOML).
+ *
+ * See the documentation for the GLX_MESA_swap_frame_usage extension for more
+ * details.
+ *
+ * \param dPriv Pointer to the private drawable structure.
+ * \return If less than a single swap interval time period was required
+ * between GLX buffer swaps, a number greater than 0 and less than
+ * 1.0 is returned. If exactly one swap interval time period is
+ * required, 1.0 is returned, and if more than one is required then
+ * a number greater than 1.0 will be returned.
+ *
+ * \sa glXSwapIntervalSGI glXGetMscRateOML
+ *
+ * \todo Instead of caching the \c glXGetMscRateOML function pointer, would it
+ * be possible to cache the sync rate?
+ */
+float
+driCalculateSwapUsage( __DRIdrawable *dPriv, int64_t last_swap_ust,
+ int64_t current_ust )
+{
+ int32_t n;
+ int32_t d;
+ int interval;
+ float usage = 1.0;
+ __DRIscreen *psp = dPriv->driScreenPriv;
+
+ if ( (*psp->systemTime->getMSCRate)(dPriv, &n, &d, dPriv->loaderPrivate) ) {
+ interval = (dPriv->swap_interval != 0) ? dPriv->swap_interval : 1;
+
+
+ /* We want to calculate
+ * (current_UST - last_swap_UST) / (interval * us_per_refresh). We get
+ * current_UST by calling __glXGetUST. last_swap_UST is stored in
+ * dPriv->swap_ust. interval has already been calculated.
+ *
+ * The only tricky part is us_per_refresh. us_per_refresh is
+ * 1000000 / MSC_rate. We know the MSC_rate is n / d. We can flip it
+ * around and say us_per_refresh = 1000000 * d / n. Since this goes in
+ * the denominator of the final calculation, we calculate
+ * (interval * 1000000 * d) and move n into the numerator.
+ */
+
+ usage = (current_ust - last_swap_ust);
+ usage *= n;
+ usage /= (interval * d);
+ usage /= 1000000.0;
+ }
+
+ return usage;
+}
+
+void
+dri2InvalidateDrawable(__DRIdrawable *drawable)
+{
+ drawable->dri2.stamp++;
+}
+
+/*@}*/
diff --git a/mesalib/src/mesa/drivers/dri/common/dri_util.h b/mesalib/src/mesa/drivers/dri/common/dri_util.h
index 3d3d5c9cd..8d2a38524 100644
--- a/mesalib/src/mesa/drivers/dri/common/dri_util.h
+++ b/mesalib/src/mesa/drivers/dri/common/dri_util.h
@@ -1,563 +1,563 @@
-/*
- * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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 dri_util.h
- * DRI utility functions definitions.
- *
- * This module acts as glue between GLX and the actual hardware driver. A DRI
- * driver doesn't really \e have to use any of this - it's optional. But, some
- * useful stuff is done here that otherwise would have to be duplicated in most
- * drivers.
- *
- * Basically, these utility functions take care of some of the dirty details of
- * screen initialization, context creation, context binding, DRM setup, etc.
- *
- * These functions are compiled into each DRI driver so libGL.so knows nothing
- * about them.
- *
- * \sa dri_util.c.
- *
- * \author Kevin E. Martin <kevin@precisioninsight.com>
- * \author Brian Paul <brian@precisioninsight.com>
- */
-
-#ifndef _DRI_UTIL_H_
-#define _DRI_UTIL_H_
-
-#include <GL/gl.h>
-#include <drm.h>
-#include <drm_sarea.h>
-#include <xf86drm.h>
-#include "xmlconfig.h"
-#include "main/glheader.h"
-#include "main/mtypes.h"
-#include "GL/internal/dri_interface.h"
-
-#define GLX_BAD_CONTEXT 5
-
-typedef struct __DRIswapInfoRec __DRIswapInfo;
-
-/**
- * Extensions.
- */
-extern const __DRIlegacyExtension driLegacyExtension;
-extern const __DRIcoreExtension driCoreExtension;
-extern const __DRIdri2Extension driDRI2Extension;
-extern const __DRIextension driReadDrawableExtension;
-extern const __DRIcopySubBufferExtension driCopySubBufferExtension;
-extern const __DRIswapControlExtension driSwapControlExtension;
-extern const __DRImediaStreamCounterExtension driMediaStreamCounterExtension;
-extern const __DRI2configQueryExtension dri2ConfigQueryExtension;
-
-/**
- * Used by DRI_VALIDATE_DRAWABLE_INFO
- */
-#define DRI_VALIDATE_DRAWABLE_INFO_ONCE(pDrawPriv) \
- do { \
- if (*(pDrawPriv->pStamp) != pDrawPriv->lastStamp) { \
- __driUtilUpdateDrawableInfo(pDrawPriv); \
- } \
- } while (0)
-
-
-/**
- * Utility macro to validate the drawable information.
- *
- * See __DRIdrawable::pStamp and __DRIdrawable::lastStamp.
- */
-#define DRI_VALIDATE_DRAWABLE_INFO(psp, pdp) \
-do { \
- while (*(pdp->pStamp) != pdp->lastStamp) { \
- register unsigned int hwContext = psp->pSAREA->lock.lock & \
- ~(DRM_LOCK_HELD | DRM_LOCK_CONT); \
- DRM_UNLOCK(psp->fd, &psp->pSAREA->lock, hwContext); \
- \
- DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \
- DRI_VALIDATE_DRAWABLE_INFO_ONCE(pdp); \
- DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \
- \
- DRM_LIGHT_LOCK(psp->fd, &psp->pSAREA->lock, hwContext); \
- } \
-} while (0)
-
-/**
- * Same as above, but for two drawables simultaneously.
- *
- */
-
-#define DRI_VALIDATE_TWO_DRAWABLES_INFO(psp, pdp, prp) \
-do { \
- while (*((pdp)->pStamp) != (pdp)->lastStamp || \
- *((prp)->pStamp) != (prp)->lastStamp) { \
- register unsigned int hwContext = (psp)->pSAREA->lock.lock & \
- ~(DRM_LOCK_HELD | DRM_LOCK_CONT); \
- DRM_UNLOCK((psp)->fd, &(psp)->pSAREA->lock, hwContext); \
- \
- DRM_SPINLOCK(&(psp)->pSAREA->drawable_lock, (psp)->drawLockID); \
- DRI_VALIDATE_DRAWABLE_INFO_ONCE(pdp); \
- DRI_VALIDATE_DRAWABLE_INFO_ONCE(prp); \
- DRM_SPINUNLOCK(&(psp)->pSAREA->drawable_lock, (psp)->drawLockID); \
- \
- DRM_LIGHT_LOCK((psp)->fd, &(psp)->pSAREA->lock, hwContext); \
- } \
-} while (0)
-
-
-/**
- * Driver callback functions.
- *
- * Each DRI driver must have one of these structures with all the pointers set
- * to appropriate functions within the driver.
- *
- * When glXCreateContext() is called, for example, it'll call a helper function
- * dri_util.c which in turn will jump through the \a CreateContext pointer in
- * this structure.
- */
-struct __DriverAPIRec {
- const __DRIconfig **(*InitScreen) (__DRIscreen * priv);
-
- /**
- * Screen destruction callback
- */
- void (*DestroyScreen)(__DRIscreen *driScrnPriv);
-
- /**
- * Context creation callback
- */
- GLboolean (*CreateContext)(gl_api api,
- const struct gl_config *glVis,
- __DRIcontext *driContextPriv,
- void *sharedContextPrivate);
-
- /**
- * Context destruction callback
- */
- void (*DestroyContext)(__DRIcontext *driContextPriv);
-
- /**
- * Buffer (drawable) creation callback
- */
- GLboolean (*CreateBuffer)(__DRIscreen *driScrnPriv,
- __DRIdrawable *driDrawPriv,
- const struct gl_config *glVis,
- GLboolean pixmapBuffer);
-
- /**
- * Buffer (drawable) destruction callback
- */
- void (*DestroyBuffer)(__DRIdrawable *driDrawPriv);
-
- /**
- * Buffer swapping callback
- */
- void (*SwapBuffers)(__DRIdrawable *driDrawPriv);
-
- /**
- * Context activation callback
- */
- GLboolean (*MakeCurrent)(__DRIcontext *driContextPriv,
- __DRIdrawable *driDrawPriv,
- __DRIdrawable *driReadPriv);
-
- /**
- * Context unbinding callback
- */
- GLboolean (*UnbindContext)(__DRIcontext *driContextPriv);
-
- /**
- * Retrieves statistics about buffer swap operations. Required if
- * GLX_OML_sync_control or GLX_MESA_swap_frame_usage is supported.
- */
- int (*GetSwapInfo)( __DRIdrawable *dPriv, __DRIswapInfo * sInfo );
-
-
- /**
- * These are required if GLX_OML_sync_control is supported.
- */
- /*@{*/
- int (*WaitForMSC)( __DRIdrawable *priv, int64_t target_msc,
- int64_t divisor, int64_t remainder,
- int64_t * msc );
- int (*WaitForSBC)( __DRIdrawable *priv, int64_t target_sbc,
- int64_t * msc, int64_t * sbc );
-
- int64_t (*SwapBuffersMSC)( __DRIdrawable *priv, int64_t target_msc,
- int64_t divisor, int64_t remainder );
- /*@}*/
- void (*CopySubBuffer)(__DRIdrawable *driDrawPriv,
- int x, int y, int w, int h);
-
- /**
- * New version of GetMSC so we can pass drawable data to the low
- * level DRM driver (e.g. pipe info). Required if
- * GLX_SGI_video_sync or GLX_OML_sync_control is supported.
- */
- int (*GetDrawableMSC) ( __DRIscreen * priv,
- __DRIdrawable *drawablePrivate,
- int64_t *count);
-
-
-
- /* DRI2 Entry point */
- const __DRIconfig **(*InitScreen2) (__DRIscreen * priv);
-
- __DRIbuffer *(*AllocateBuffer) (__DRIscreen *screenPrivate,
- unsigned int attachment,
- unsigned int format,
- int width, int height);
- void (*ReleaseBuffer) (__DRIscreen *screenPrivate, __DRIbuffer *buffer);
-};
-
-extern const struct __DriverAPIRec driDriverAPI;
-
-
-struct __DRIswapInfoRec {
- /**
- * Number of swapBuffers operations that have been *completed*.
- */
- uint64_t swap_count;
-
- /**
- * Unadjusted system time of the last buffer swap. This is the time
- * when the swap completed, not the time when swapBuffers was called.
- */
- int64_t swap_ust;
-
- /**
- * Number of swap operations that occurred after the swap deadline. That
- * is if a swap happens more than swap_interval frames after the previous
- * swap, it has missed its deadline. If swap_interval is 0, then the
- * swap deadline is 1 frame after the previous swap.
- */
- uint64_t swap_missed_count;
-
- /**
- * Amount of time used by the last swap that missed its deadline. This
- * is calculated as (__glXGetUST() - swap_ust) / (swap_interval *
- * time_for_single_vrefresh)). If the actual value of swap_interval is
- * 0, then 1 is used instead. If swap_missed_count is non-zero, this
- * should be greater-than 1.0.
- */
- float swap_missed_usage;
-};
-
-
-/**
- * Per-drawable private DRI driver information.
- */
-struct __DRIdrawableRec {
- /**
- * Kernel drawable handle
- */
- drm_drawable_t hHWDrawable;
-
- /**
- * Driver's private drawable information.
- *
- * This structure is opaque.
- */
- void *driverPrivate;
-
- /**
- * Private data from the loader. We just hold on to it and pass
- * it back when calling into loader provided functions.
- */
- void *loaderPrivate;
-
- /**
- * Reference count for number of context's currently bound to this
- * drawable.
- *
- * Once it reaches zero, the drawable can be destroyed.
- *
- * \note This behavior will change with GLX 1.3.
- */
- int refcount;
-
- /**
- * Index of this drawable information in the SAREA.
- */
- unsigned int index;
-
- /**
- * Pointer to the "drawable has changed ID" stamp in the SAREA (or
- * to dri2.stamp if DRI2 is being used).
- */
- unsigned int *pStamp;
-
- /**
- * Last value of the stamp.
- *
- * If this differs from the value stored at __DRIdrawable::pStamp,
- * then the drawable information has been modified by the X server, and the
- * drawable information (below) should be retrieved from the X server.
- */
- unsigned int lastStamp;
-
- /**
- * \name Drawable
- *
- * Drawable information used in software fallbacks.
- */
- /*@{*/
- int x;
- int y;
- int w;
- int h;
- int numClipRects;
- drm_clip_rect_t *pClipRects;
- /*@}*/
-
- /**
- * \name Back and depthbuffer
- *
- * Information about the back and depthbuffer where different from above.
- */
- /*@{*/
- int backX;
- int backY;
- int backClipRectType;
- int numBackClipRects;
- drm_clip_rect_t *pBackClipRects;
- /*@}*/
-
- /**
- * \name Vertical blank tracking information
- * Used for waiting on vertical blank events.
- */
- /*@{*/
- unsigned int vblSeq;
- unsigned int vblFlags;
- /*@}*/
-
- /**
- * \name Monotonic MSC tracking
- *
- * Low level driver is responsible for updating msc_base and
- * vblSeq values so that higher level code can calculate
- * a new msc value or msc target for a WaitMSC call. The new value
- * will be:
- * msc = msc_base + get_vblank_count() - vblank_base;
- *
- * And for waiting on a value, core code will use:
- * actual_target = target_msc - msc_base + vblank_base;
- */
- /*@{*/
- int64_t vblank_base;
- int64_t msc_base;
- /*@}*/
-
- /**
- * Pointer to context to which this drawable is currently bound.
- */
- __DRIcontext *driContextPriv;
-
- /**
- * Pointer to screen on which this drawable was created.
- */
- __DRIscreen *driScreenPriv;
-
- /**
- * Controls swap interval as used by GLX_SGI_swap_control and
- * GLX_MESA_swap_control.
- */
- unsigned int swap_interval;
-
- struct {
- unsigned int stamp;
- drm_clip_rect_t clipRect;
- } dri2;
-};
-
-/**
- * Per-context private driver information.
- */
-struct __DRIcontextRec {
- /**
- * Kernel context handle used to access the device lock.
- */
- drm_context_t hHWContext;
-
- /**
- * Device driver's private context data. This structure is opaque.
- */
- void *driverPrivate;
-
- /**
- * Pointer to drawable currently bound to this context for drawing.
- */
- __DRIdrawable *driDrawablePriv;
-
- /**
- * Pointer to drawable currently bound to this context for reading.
- */
- __DRIdrawable *driReadablePriv;
-
- /**
- * Pointer to screen on which this context was created.
- */
- __DRIscreen *driScreenPriv;
-
- /**
- * The loaders's private context data. This structure is opaque.
- */
- void *loaderPrivate;
-
- struct {
- int draw_stamp;
- int read_stamp;
- } dri2;
-};
-
-/**
- * Per-screen private driver information.
- */
-struct __DRIscreenRec {
- /**
- * Current screen's number
- */
- int myNum;
-
- /**
- * Callback functions into the hardware-specific DRI driver code.
- */
- struct __DriverAPIRec DriverAPI;
-
- const __DRIextension **extensions;
- /**
- * DDX / 2D driver version information.
- */
- __DRIversion ddx_version;
-
- /**
- * DRI X extension version information.
- */
- __DRIversion dri_version;
-
- /**
- * DRM (kernel module) version information.
- */
- __DRIversion drm_version;
-
- /**
- * ID used when the client sets the drawable lock.
- *
- * The X server uses this value to detect if the client has died while
- * holding the drawable lock.
- */
- int drawLockID;
-
- /**
- * File descriptor returned when the kernel device driver is opened.
- *
- * Used to:
- * - authenticate client to kernel
- * - map the frame buffer, SAREA, etc.
- * - close the kernel device driver
- */
- int fd;
-
- /**
- * SAREA pointer
- *
- * Used to access:
- * - the device lock
- * - the device-independent per-drawable and per-context(?) information
- */
- drm_sarea_t *pSAREA;
-
- /**
- * \name Direct frame buffer access information
- * Used for software fallbacks.
- */
- /*@{*/
- unsigned char *pFB;
- int fbSize;
- int fbOrigin;
- int fbStride;
- int fbWidth;
- int fbHeight;
- int fbBPP;
- /*@}*/
-
- /**
- * \name Device-dependent private information (stored in the SAREA).
- *
- * This data is accessed by the client driver only.
- */
- /*@{*/
- void *pDevPriv;
- int devPrivSize;
- /*@}*/
-
- /**
- * Device-dependent private information (not stored in the SAREA).
- *
- * This pointer is never touched by the DRI layer.
- */
-#ifdef __cplusplus
- void *priv;
-#else
- void *private;
-#endif
-
- /* Extensions provided by the loader. */
- const __DRIgetDrawableInfoExtension *getDrawableInfo;
- const __DRIsystemTimeExtension *systemTime;
- const __DRIdamageExtension *damage;
-
- struct {
- /* Flag to indicate that this is a DRI2 screen. Many of the above
- * fields will not be valid or initializaed in that case. */
- int enabled;
- __DRIdri2LoaderExtension *loader;
- __DRIimageLookupExtension *image;
- __DRIuseInvalidateExtension *useInvalidate;
- } dri2;
-
- /* The lock actually in use, old sarea or DRI2 */
- drmLock *lock;
-
- driOptionCache optionInfo;
- driOptionCache optionCache;
- unsigned int api_mask;
- void *loaderPrivate;
-};
-
-extern void
-__driUtilUpdateDrawableInfo(__DRIdrawable *pdp);
-
-extern float
-driCalculateSwapUsage( __DRIdrawable *dPriv,
- int64_t last_swap_ust, int64_t current_ust );
-
-extern GLint
-driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 );
-
-extern void
-dri2InvalidateDrawable(__DRIdrawable *drawable);
-
-#endif /* _DRI_UTIL_H_ */
+/*
+ * Copyright 1998-1999 Precision Insight, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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 dri_util.h
+ * DRI utility functions definitions.
+ *
+ * This module acts as glue between GLX and the actual hardware driver. A DRI
+ * driver doesn't really \e have to use any of this - it's optional. But, some
+ * useful stuff is done here that otherwise would have to be duplicated in most
+ * drivers.
+ *
+ * Basically, these utility functions take care of some of the dirty details of
+ * screen initialization, context creation, context binding, DRM setup, etc.
+ *
+ * These functions are compiled into each DRI driver so libGL.so knows nothing
+ * about them.
+ *
+ * \sa dri_util.c.
+ *
+ * \author Kevin E. Martin <kevin@precisioninsight.com>
+ * \author Brian Paul <brian@precisioninsight.com>
+ */
+
+#ifndef _DRI_UTIL_H_
+#define _DRI_UTIL_H_
+
+#include <GL/gl.h>
+#include <drm.h>
+#include <drm_sarea.h>
+#include <xf86drm.h>
+#include "xmlconfig.h"
+#include "main/glheader.h"
+#include "main/mtypes.h"
+#include "GL/internal/dri_interface.h"
+
+#define GLX_BAD_CONTEXT 5
+
+typedef struct __DRIswapInfoRec __DRIswapInfo;
+
+/**
+ * Extensions.
+ */
+extern const __DRIlegacyExtension driLegacyExtension;
+extern const __DRIcoreExtension driCoreExtension;
+extern const __DRIdri2Extension driDRI2Extension;
+extern const __DRIextension driReadDrawableExtension;
+extern const __DRIcopySubBufferExtension driCopySubBufferExtension;
+extern const __DRIswapControlExtension driSwapControlExtension;
+extern const __DRImediaStreamCounterExtension driMediaStreamCounterExtension;
+extern const __DRI2configQueryExtension dri2ConfigQueryExtension;
+
+/**
+ * Used by DRI_VALIDATE_DRAWABLE_INFO
+ */
+#define DRI_VALIDATE_DRAWABLE_INFO_ONCE(pDrawPriv) \
+ do { \
+ if (*(pDrawPriv->pStamp) != pDrawPriv->lastStamp) { \
+ __driUtilUpdateDrawableInfo(pDrawPriv); \
+ } \
+ } while (0)
+
+
+/**
+ * Utility macro to validate the drawable information.
+ *
+ * See __DRIdrawable::pStamp and __DRIdrawable::lastStamp.
+ */
+#define DRI_VALIDATE_DRAWABLE_INFO(psp, pdp) \
+do { \
+ while (*(pdp->pStamp) != pdp->lastStamp) { \
+ register unsigned int hwContext = psp->pSAREA->lock.lock & \
+ ~(DRM_LOCK_HELD | DRM_LOCK_CONT); \
+ DRM_UNLOCK(psp->fd, &psp->pSAREA->lock, hwContext); \
+ \
+ DRM_SPINLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \
+ DRI_VALIDATE_DRAWABLE_INFO_ONCE(pdp); \
+ DRM_SPINUNLOCK(&psp->pSAREA->drawable_lock, psp->drawLockID); \
+ \
+ DRM_LIGHT_LOCK(psp->fd, &psp->pSAREA->lock, hwContext); \
+ } \
+} while (0)
+
+/**
+ * Same as above, but for two drawables simultaneously.
+ *
+ */
+
+#define DRI_VALIDATE_TWO_DRAWABLES_INFO(psp, pdp, prp) \
+do { \
+ while (*((pdp)->pStamp) != (pdp)->lastStamp || \
+ *((prp)->pStamp) != (prp)->lastStamp) { \
+ register unsigned int hwContext = (psp)->pSAREA->lock.lock & \
+ ~(DRM_LOCK_HELD | DRM_LOCK_CONT); \
+ DRM_UNLOCK((psp)->fd, &(psp)->pSAREA->lock, hwContext); \
+ \
+ DRM_SPINLOCK(&(psp)->pSAREA->drawable_lock, (psp)->drawLockID); \
+ DRI_VALIDATE_DRAWABLE_INFO_ONCE(pdp); \
+ DRI_VALIDATE_DRAWABLE_INFO_ONCE(prp); \
+ DRM_SPINUNLOCK(&(psp)->pSAREA->drawable_lock, (psp)->drawLockID); \
+ \
+ DRM_LIGHT_LOCK((psp)->fd, &(psp)->pSAREA->lock, hwContext); \
+ } \
+} while (0)
+
+
+/**
+ * Driver callback functions.
+ *
+ * Each DRI driver must have one of these structures with all the pointers set
+ * to appropriate functions within the driver.
+ *
+ * When glXCreateContext() is called, for example, it'll call a helper function
+ * dri_util.c which in turn will jump through the \a CreateContext pointer in
+ * this structure.
+ */
+struct __DriverAPIRec {
+ const __DRIconfig **(*InitScreen) (__DRIscreen * priv);
+
+ /**
+ * Screen destruction callback
+ */
+ void (*DestroyScreen)(__DRIscreen *driScrnPriv);
+
+ /**
+ * Context creation callback
+ */
+ GLboolean (*CreateContext)(gl_api api,
+ const struct gl_config *glVis,
+ __DRIcontext *driContextPriv,
+ void *sharedContextPrivate);
+
+ /**
+ * Context destruction callback
+ */
+ void (*DestroyContext)(__DRIcontext *driContextPriv);
+
+ /**
+ * Buffer (drawable) creation callback
+ */
+ GLboolean (*CreateBuffer)(__DRIscreen *driScrnPriv,
+ __DRIdrawable *driDrawPriv,
+ const struct gl_config *glVis,
+ GLboolean pixmapBuffer);
+
+ /**
+ * Buffer (drawable) destruction callback
+ */
+ void (*DestroyBuffer)(__DRIdrawable *driDrawPriv);
+
+ /**
+ * Buffer swapping callback
+ */
+ void (*SwapBuffers)(__DRIdrawable *driDrawPriv);
+
+ /**
+ * Context activation callback
+ */
+ GLboolean (*MakeCurrent)(__DRIcontext *driContextPriv,
+ __DRIdrawable *driDrawPriv,
+ __DRIdrawable *driReadPriv);
+
+ /**
+ * Context unbinding callback
+ */
+ GLboolean (*UnbindContext)(__DRIcontext *driContextPriv);
+
+ /**
+ * Retrieves statistics about buffer swap operations. Required if
+ * GLX_OML_sync_control or GLX_MESA_swap_frame_usage is supported.
+ */
+ int (*GetSwapInfo)( __DRIdrawable *dPriv, __DRIswapInfo * sInfo );
+
+
+ /**
+ * These are required if GLX_OML_sync_control is supported.
+ */
+ /*@{*/
+ int (*WaitForMSC)( __DRIdrawable *priv, int64_t target_msc,
+ int64_t divisor, int64_t remainder,
+ int64_t * msc );
+ int (*WaitForSBC)( __DRIdrawable *priv, int64_t target_sbc,
+ int64_t * msc, int64_t * sbc );
+
+ int64_t (*SwapBuffersMSC)( __DRIdrawable *priv, int64_t target_msc,
+ int64_t divisor, int64_t remainder );
+ /*@}*/
+ void (*CopySubBuffer)(__DRIdrawable *driDrawPriv,
+ int x, int y, int w, int h);
+
+ /**
+ * New version of GetMSC so we can pass drawable data to the low
+ * level DRM driver (e.g. pipe info). Required if
+ * GLX_SGI_video_sync or GLX_OML_sync_control is supported.
+ */
+ int (*GetDrawableMSC) ( __DRIscreen * priv,
+ __DRIdrawable *drawablePrivate,
+ int64_t *count);
+
+
+
+ /* DRI2 Entry point */
+ const __DRIconfig **(*InitScreen2) (__DRIscreen * priv);
+
+ __DRIbuffer *(*AllocateBuffer) (__DRIscreen *screenPrivate,
+ unsigned int attachment,
+ unsigned int format,
+ int width, int height);
+ void (*ReleaseBuffer) (__DRIscreen *screenPrivate, __DRIbuffer *buffer);
+};
+
+extern const struct __DriverAPIRec driDriverAPI;
+
+
+struct __DRIswapInfoRec {
+ /**
+ * Number of swapBuffers operations that have been *completed*.
+ */
+ uint64_t swap_count;
+
+ /**
+ * Unadjusted system time of the last buffer swap. This is the time
+ * when the swap completed, not the time when swapBuffers was called.
+ */
+ int64_t swap_ust;
+
+ /**
+ * Number of swap operations that occurred after the swap deadline. That
+ * is if a swap happens more than swap_interval frames after the previous
+ * swap, it has missed its deadline. If swap_interval is 0, then the
+ * swap deadline is 1 frame after the previous swap.
+ */
+ uint64_t swap_missed_count;
+
+ /**
+ * Amount of time used by the last swap that missed its deadline. This
+ * is calculated as (__glXGetUST() - swap_ust) / (swap_interval *
+ * time_for_single_vrefresh)). If the actual value of swap_interval is
+ * 0, then 1 is used instead. If swap_missed_count is non-zero, this
+ * should be greater-than 1.0.
+ */
+ float swap_missed_usage;
+};
+
+
+/**
+ * Per-drawable private DRI driver information.
+ */
+struct __DRIdrawableRec {
+ /**
+ * Kernel drawable handle
+ */
+ drm_drawable_t hHWDrawable;
+
+ /**
+ * Driver's private drawable information.
+ *
+ * This structure is opaque.
+ */
+ void *driverPrivate;
+
+ /**
+ * Private data from the loader. We just hold on to it and pass
+ * it back when calling into loader provided functions.
+ */
+ void *loaderPrivate;
+
+ /**
+ * Reference count for number of context's currently bound to this
+ * drawable.
+ *
+ * Once it reaches zero, the drawable can be destroyed.
+ *
+ * \note This behavior will change with GLX 1.3.
+ */
+ int refcount;
+
+ /**
+ * Index of this drawable information in the SAREA.
+ */
+ unsigned int index;
+
+ /**
+ * Pointer to the "drawable has changed ID" stamp in the SAREA (or
+ * to dri2.stamp if DRI2 is being used).
+ */
+ unsigned int *pStamp;
+
+ /**
+ * Last value of the stamp.
+ *
+ * If this differs from the value stored at __DRIdrawable::pStamp,
+ * then the drawable information has been modified by the X server, and the
+ * drawable information (below) should be retrieved from the X server.
+ */
+ unsigned int lastStamp;
+
+ /**
+ * \name Drawable
+ *
+ * Drawable information used in software fallbacks.
+ */
+ /*@{*/
+ int x;
+ int y;
+ int w;
+ int h;
+ int numClipRects;
+ drm_clip_rect_t *pClipRects;
+ /*@}*/
+
+ /**
+ * \name Back and depthbuffer
+ *
+ * Information about the back and depthbuffer where different from above.
+ */
+ /*@{*/
+ int backX;
+ int backY;
+ int backClipRectType;
+ int numBackClipRects;
+ drm_clip_rect_t *pBackClipRects;
+ /*@}*/
+
+ /**
+ * \name Vertical blank tracking information
+ * Used for waiting on vertical blank events.
+ */
+ /*@{*/
+ unsigned int vblSeq;
+ unsigned int vblFlags;
+ /*@}*/
+
+ /**
+ * \name Monotonic MSC tracking
+ *
+ * Low level driver is responsible for updating msc_base and
+ * vblSeq values so that higher level code can calculate
+ * a new msc value or msc target for a WaitMSC call. The new value
+ * will be:
+ * msc = msc_base + get_vblank_count() - vblank_base;
+ *
+ * And for waiting on a value, core code will use:
+ * actual_target = target_msc - msc_base + vblank_base;
+ */
+ /*@{*/
+ int64_t vblank_base;
+ int64_t msc_base;
+ /*@}*/
+
+ /**
+ * Pointer to context to which this drawable is currently bound.
+ */
+ __DRIcontext *driContextPriv;
+
+ /**
+ * Pointer to screen on which this drawable was created.
+ */
+ __DRIscreen *driScreenPriv;
+
+ /**
+ * Controls swap interval as used by GLX_SGI_swap_control and
+ * GLX_MESA_swap_control.
+ */
+ unsigned int swap_interval;
+
+ struct {
+ unsigned int stamp;
+ drm_clip_rect_t clipRect;
+ } dri2;
+};
+
+/**
+ * Per-context private driver information.
+ */
+struct __DRIcontextRec {
+ /**
+ * Kernel context handle used to access the device lock.
+ */
+ drm_context_t hHWContext;
+
+ /**
+ * Device driver's private context data. This structure is opaque.
+ */
+ void *driverPrivate;
+
+ /**
+ * Pointer to drawable currently bound to this context for drawing.
+ */
+ __DRIdrawable *driDrawablePriv;
+
+ /**
+ * Pointer to drawable currently bound to this context for reading.
+ */
+ __DRIdrawable *driReadablePriv;
+
+ /**
+ * Pointer to screen on which this context was created.
+ */
+ __DRIscreen *driScreenPriv;
+
+ /**
+ * The loaders's private context data. This structure is opaque.
+ */
+ void *loaderPrivate;
+
+ struct {
+ int draw_stamp;
+ int read_stamp;
+ } dri2;
+};
+
+/**
+ * Per-screen private driver information.
+ */
+struct __DRIscreenRec {
+ /**
+ * Current screen's number
+ */
+ int myNum;
+
+ /**
+ * Callback functions into the hardware-specific DRI driver code.
+ */
+ struct __DriverAPIRec DriverAPI;
+
+ const __DRIextension **extensions;
+ /**
+ * DDX / 2D driver version information.
+ */
+ __DRIversion ddx_version;
+
+ /**
+ * DRI X extension version information.
+ */
+ __DRIversion dri_version;
+
+ /**
+ * DRM (kernel module) version information.
+ */
+ __DRIversion drm_version;
+
+ /**
+ * ID used when the client sets the drawable lock.
+ *
+ * The X server uses this value to detect if the client has died while
+ * holding the drawable lock.
+ */
+ int drawLockID;
+
+ /**
+ * File descriptor returned when the kernel device driver is opened.
+ *
+ * Used to:
+ * - authenticate client to kernel
+ * - map the frame buffer, SAREA, etc.
+ * - close the kernel device driver
+ */
+ int fd;
+
+ /**
+ * SAREA pointer
+ *
+ * Used to access:
+ * - the device lock
+ * - the device-independent per-drawable and per-context(?) information
+ */
+ drm_sarea_t *pSAREA;
+
+ /**
+ * \name Direct frame buffer access information
+ * Used for software fallbacks.
+ */
+ /*@{*/
+ unsigned char *pFB;
+ int fbSize;
+ int fbOrigin;
+ int fbStride;
+ int fbWidth;
+ int fbHeight;
+ int fbBPP;
+ /*@}*/
+
+ /**
+ * \name Device-dependent private information (stored in the SAREA).
+ *
+ * This data is accessed by the client driver only.
+ */
+ /*@{*/
+ void *pDevPriv;
+ int devPrivSize;
+ /*@}*/
+
+ /**
+ * Device-dependent private information (not stored in the SAREA).
+ *
+ * This pointer is never touched by the DRI layer.
+ */
+#ifdef __cplusplus
+ void *priv;
+#else
+ void *private;
+#endif
+
+ /* Extensions provided by the loader. */
+ const __DRIgetDrawableInfoExtension *getDrawableInfo;
+ const __DRIsystemTimeExtension *systemTime;
+ const __DRIdamageExtension *damage;
+
+ struct {
+ /* Flag to indicate that this is a DRI2 screen. Many of the above
+ * fields will not be valid or initializaed in that case. */
+ int enabled;
+ __DRIdri2LoaderExtension *loader;
+ __DRIimageLookupExtension *image;
+ __DRIuseInvalidateExtension *useInvalidate;
+ } dri2;
+
+ /* The lock actually in use, old sarea or DRI2 */
+ drmLock *lock;
+
+ driOptionCache optionInfo;
+ driOptionCache optionCache;
+ unsigned int api_mask;
+ void *loaderPrivate;
+};
+
+extern void
+__driUtilUpdateDrawableInfo(__DRIdrawable *pdp);
+
+extern float
+driCalculateSwapUsage( __DRIdrawable *dPriv,
+ int64_t last_swap_ust, int64_t current_ust );
+
+extern GLint
+driIntersectArea( drm_clip_rect_t rect1, drm_clip_rect_t rect2 );
+
+extern void
+dri2InvalidateDrawable(__DRIdrawable *drawable);
+
+#endif /* _DRI_UTIL_H_ */
diff --git a/mesalib/src/mesa/drivers/dri/common/utils.c b/mesalib/src/mesa/drivers/dri/common/utils.c
index a2b0b4e94..02c8cc6f5 100644
--- a/mesalib/src/mesa/drivers/dri/common/utils.c
+++ b/mesalib/src/mesa/drivers/dri/common/utils.c
@@ -219,7 +219,9 @@ void driInitExtensions( struct gl_context * ctx,
/* Map the static functions. Together with those mapped by remap
* table, this should cover everything mesa core knows.
*/
+#ifdef _GLAPI_USE_REMAP_TABLE
_mesa_map_static_functions();
+#endif
return;
}
diff --git a/mesalib/src/mesa/drivers/dri/swrast/swrast.c b/mesalib/src/mesa/drivers/dri/swrast/swrast.c
index 719b406ec..e6d1ab741 100644
--- a/mesalib/src/mesa/drivers/dri/swrast/swrast.c
+++ b/mesalib/src/mesa/drivers/dri/swrast/swrast.c
@@ -1,806 +1,811 @@
-/*
- * Copyright 2008, 2010 George Sapountzis <gsapountzis@gmail.com>
- *
- * 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.
- */
-
-/*
- * DRI software rasterizer
- *
- * This is the mesa swrast module packaged into a DRI driver structure.
- *
- * The front-buffer is allocated by the loader. The loader provides read/write
- * callbacks for access to the front-buffer. The driver uses a scratch row for
- * front-buffer rendering to avoid repeated calls to the loader.
- *
- * The back-buffer is allocated by the driver and is private.
- */
-
-#include "main/context.h"
-#include "main/extensions.h"
-#include "main/formats.h"
-#include "main/framebuffer.h"
-#include "main/imports.h"
-#include "main/renderbuffer.h"
-#include "swrast/swrast.h"
-#include "swrast_setup/swrast_setup.h"
-#include "tnl/tnl.h"
-#include "tnl/t_context.h"
-#include "tnl/t_pipeline.h"
-#include "vbo/vbo.h"
-#include "drivers/common/driverfuncs.h"
-#include "drivers/common/meta.h"
-#include "utils.h"
-
-#include "main/teximage.h"
-#include "main/texformat.h"
-#include "main/texstate.h"
-
-#include "swrast_priv.h"
-
-
-/**
- * Screen and config-related functions
- */
-
-static void swrastSetTexBuffer2(__DRIcontext *pDRICtx, GLint target,
- GLint texture_format, __DRIdrawable *dPriv)
-{
- struct dri_context *dri_ctx;
- int x, y, w, h;
- __DRIscreen *sPriv = dPriv->driScreenPriv;
- struct gl_texture_unit *texUnit;
- struct gl_texture_object *texObj;
- struct gl_texture_image *texImage;
- uint32_t internalFormat;
- gl_format texFormat;
-
- dri_ctx = pDRICtx->driverPrivate;
-
- internalFormat = (texture_format == __DRI_TEXTURE_FORMAT_RGB ? 3 : 4);
-
- texUnit = _mesa_get_current_tex_unit(&dri_ctx->Base);
- texObj = _mesa_select_tex_object(&dri_ctx->Base, texUnit, target);
- texImage = _mesa_get_tex_image(&dri_ctx->Base, texObj, target, 0);
-
- _mesa_lock_texture(&dri_ctx->Base, texObj);
-
- sPriv->swrast_loader->getDrawableInfo(dPriv, &x, &y, &w, &h, dPriv->loaderPrivate);
-
- if (texture_format == __DRI_TEXTURE_FORMAT_RGB)
- texFormat = MESA_FORMAT_XRGB8888;
- else
- texFormat = MESA_FORMAT_ARGB8888;
-
- _mesa_init_teximage_fields(&dri_ctx->Base, target, texImage,
- w, h, 1, 0, internalFormat, texFormat);
-
- sPriv->swrast_loader->getImage(dPriv, x, y, w, h, (char *)texImage->Data,
- dPriv->loaderPrivate);
-
- _mesa_unlock_texture(&dri_ctx->Base, texObj);
-}
-
-static void swrastSetTexBuffer(__DRIcontext *pDRICtx, GLint target,
- __DRIdrawable *dPriv)
-{
- swrastSetTexBuffer2(pDRICtx, target, __DRI_TEXTURE_FORMAT_RGBA, dPriv);
-}
-
-static const __DRItexBufferExtension swrastTexBufferExtension = {
- { __DRI_TEX_BUFFER, __DRI_TEX_BUFFER_VERSION },
- swrastSetTexBuffer,
- swrastSetTexBuffer2,
-};
-
-static const __DRIextension *dri_screen_extensions[] = {
- &swrastTexBufferExtension.base,
- NULL
-};
-
-static __DRIconfig **
-swrastFillInModes(__DRIscreen *psp,
- unsigned pixel_bits, unsigned depth_bits,
- unsigned stencil_bits, GLboolean have_back_buffer)
-{
- __DRIconfig **configs;
- unsigned depth_buffer_factor;
- unsigned back_buffer_factor;
- GLenum fb_format;
- GLenum fb_type;
-
- /* GLX_SWAP_COPY_OML is only supported because the Intel driver doesn't
- * support pageflipping at all.
- */
- static const GLenum back_buffer_modes[] = {
- GLX_NONE, GLX_SWAP_UNDEFINED_OML
- };
-
- uint8_t depth_bits_array[4];
- uint8_t stencil_bits_array[4];
- uint8_t msaa_samples_array[1];
-
- depth_bits_array[0] = 0;
- depth_bits_array[1] = 0;
- depth_bits_array[2] = depth_bits;
- depth_bits_array[3] = depth_bits;
-
- /* Just like with the accumulation buffer, always provide some modes
- * with a stencil buffer.
- */
- stencil_bits_array[0] = 0;
- stencil_bits_array[1] = (stencil_bits == 0) ? 8 : stencil_bits;
- stencil_bits_array[2] = 0;
- stencil_bits_array[3] = (stencil_bits == 0) ? 8 : stencil_bits;
-
- msaa_samples_array[0] = 0;
-
- depth_buffer_factor = 4;
- back_buffer_factor = 2;
-
- switch (pixel_bits) {
- case 8:
- fb_format = GL_RGB;
- fb_type = GL_UNSIGNED_BYTE_2_3_3_REV;
- break;
- case 16:
- fb_format = GL_RGB;
- fb_type = GL_UNSIGNED_SHORT_5_6_5;
- break;
- case 24:
- fb_format = GL_BGR;
- fb_type = GL_UNSIGNED_INT_8_8_8_8_REV;
- break;
- case 32:
- fb_format = GL_BGRA;
- fb_type = GL_UNSIGNED_INT_8_8_8_8_REV;
- break;
- default:
- fprintf(stderr, "[%s:%u] bad depth %d\n", __func__, __LINE__,
- pixel_bits);
- return NULL;
- }
-
- configs = driCreateConfigs(fb_format, fb_type,
- depth_bits_array, stencil_bits_array,
- depth_buffer_factor, back_buffer_modes,
- back_buffer_factor, msaa_samples_array, 1,
- GL_TRUE);
- if (configs == NULL) {
- fprintf(stderr, "[%s:%u] Error creating FBConfig!\n", __func__,
- __LINE__);
- return NULL;
- }
-
- return configs;
-}
-
-static const __DRIconfig **
-dri_init_screen(__DRIscreen * psp)
-{
- __DRIconfig **configs8, **configs16, **configs24, **configs32;
-
- TRACE;
-
- psp->extensions = dri_screen_extensions;
-
- configs8 = swrastFillInModes(psp, 8, 8, 0, 1);
- configs16 = swrastFillInModes(psp, 16, 16, 0, 1);
- configs24 = swrastFillInModes(psp, 24, 24, 8, 1);
- configs32 = swrastFillInModes(psp, 32, 24, 8, 1);
-
- configs16 = driConcatConfigs(configs8, configs16);
- configs24 = driConcatConfigs(configs16, configs24);
- configs32 = driConcatConfigs(configs24, configs32);
-
- return (const __DRIconfig **)configs32;
-}
-
-static void
-dri_destroy_screen(__DRIscreen * sPriv)
-{
- TRACE;
-}
-
-
-/**
- * Framebuffer and renderbuffer-related functions.
- */
-
-static GLuint
-choose_pixel_format(const struct gl_config *v)
-{
- int depth = v->rgbBits;
-
- if (depth == 32
- && v->redMask == 0xff0000
- && v->greenMask == 0x00ff00
- && v->blueMask == 0x0000ff)
- return PF_A8R8G8B8;
- else if (depth == 24
- && v->redMask == 0xff0000
- && v->greenMask == 0x00ff00
- && v->blueMask == 0x0000ff)
- return PF_X8R8G8B8;
- else if (depth == 16
- && v->redMask == 0xf800
- && v->greenMask == 0x07e0
- && v->blueMask == 0x001f)
- return PF_R5G6B5;
- else if (depth == 8
- && v->redMask == 0x07
- && v->greenMask == 0x38
- && v->blueMask == 0xc0)
- return PF_R3G3B2;
-
- _mesa_problem( NULL, "unexpected format in %s", __FUNCTION__ );
- return 0;
-}
-
-static void
-swrast_delete_renderbuffer(struct gl_renderbuffer *rb)
-{
- TRACE;
-
- free(rb->Data);
- free(rb);
-}
-
-/* see bytes_per_line in libGL */
-static INLINE int
-bytes_per_line(unsigned pitch_bits, unsigned mul)
-{
- unsigned mask = mul - 1;
-
- return ((pitch_bits + mask) & ~mask) / 8;
-}
-
-static GLboolean
-swrast_alloc_front_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
- GLenum internalFormat, GLuint width, GLuint height)
-{
- struct swrast_renderbuffer *xrb = swrast_renderbuffer(rb);
-
- TRACE;
-
- rb->Data = NULL;
- rb->Width = width;
- rb->Height = height;
-
- xrb->pitch = bytes_per_line(width * xrb->bpp, 32);
-
- return GL_TRUE;
-}
-
-static GLboolean
-swrast_alloc_back_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
- GLenum internalFormat, GLuint width, GLuint height)
-{
- struct swrast_renderbuffer *xrb = swrast_renderbuffer(rb);
-
- TRACE;
-
- free(rb->Data);
-
- swrast_alloc_front_storage(ctx, rb, internalFormat, width, height);
-
- rb->Data = malloc(height * xrb->pitch);
-
- return GL_TRUE;
-}
-
-static struct swrast_renderbuffer *
-swrast_new_renderbuffer(const struct gl_config *visual, GLboolean front)
-{
- struct swrast_renderbuffer *xrb = calloc(1, sizeof *xrb);
- GLuint pixel_format;
-
- TRACE;
-
- if (!xrb)
- return NULL;
-
- _mesa_init_renderbuffer(&xrb->Base, 0);
-
- pixel_format = choose_pixel_format(visual);
-
- xrb->Base.Delete = swrast_delete_renderbuffer;
- if (front) {
- xrb->Base.AllocStorage = swrast_alloc_front_storage;
- swrast_set_span_funcs_front(xrb, pixel_format);
- }
- else {
- xrb->Base.AllocStorage = swrast_alloc_back_storage;
- swrast_set_span_funcs_back(xrb, pixel_format);
- }
-
- switch (pixel_format) {
- case PF_A8R8G8B8:
- xrb->Base.Format = MESA_FORMAT_ARGB8888;
- xrb->Base.InternalFormat = GL_RGBA;
- xrb->Base._BaseFormat = GL_RGBA;
- xrb->Base.DataType = GL_UNSIGNED_BYTE;
- xrb->bpp = 32;
- break;
- case PF_X8R8G8B8:
- xrb->Base.Format = MESA_FORMAT_ARGB8888; /* XXX */
- xrb->Base.InternalFormat = GL_RGB;
- xrb->Base._BaseFormat = GL_RGB;
- xrb->Base.DataType = GL_UNSIGNED_BYTE;
- xrb->bpp = 32;
- break;
- case PF_R5G6B5:
- xrb->Base.Format = MESA_FORMAT_RGB565;
- xrb->Base.InternalFormat = GL_RGB;
- xrb->Base._BaseFormat = GL_RGB;
- xrb->Base.DataType = GL_UNSIGNED_BYTE;
- xrb->bpp = 16;
- break;
- case PF_R3G3B2:
- xrb->Base.Format = MESA_FORMAT_RGB332;
- xrb->Base.InternalFormat = GL_RGB;
- xrb->Base._BaseFormat = GL_RGB;
- xrb->Base.DataType = GL_UNSIGNED_BYTE;
- xrb->bpp = 8;
- break;
- default:
- return NULL;
- }
-
- return xrb;
-}
-
-static GLboolean
-dri_create_buffer(__DRIscreen * sPriv,
- __DRIdrawable * dPriv,
- const struct gl_config * visual, GLboolean isPixmap)
-{
- struct dri_drawable *drawable = NULL;
- struct gl_framebuffer *fb;
- struct swrast_renderbuffer *frontrb, *backrb;
-
- TRACE;
-
- drawable = CALLOC_STRUCT(dri_drawable);
- if (drawable == NULL)
- goto drawable_fail;
-
- dPriv->driverPrivate = drawable;
- drawable->dPriv = dPriv;
-
- drawable->row = malloc(MAX_WIDTH * 4);
- if (drawable->row == NULL)
- goto drawable_fail;
-
- fb = &drawable->Base;
-
- /* basic framebuffer setup */
- _mesa_initialize_window_framebuffer(fb, visual);
-
- /* add front renderbuffer */
- frontrb = swrast_new_renderbuffer(visual, GL_TRUE);
- _mesa_add_renderbuffer(fb, BUFFER_FRONT_LEFT, &frontrb->Base);
-
- /* add back renderbuffer */
- if (visual->doubleBufferMode) {
- backrb = swrast_new_renderbuffer(visual, GL_FALSE);
- _mesa_add_renderbuffer(fb, BUFFER_BACK_LEFT, &backrb->Base);
- }
-
- /* add software renderbuffers */
- _mesa_add_soft_renderbuffers(fb,
- GL_FALSE, /* color */
- visual->haveDepthBuffer,
- visual->haveStencilBuffer,
- visual->haveAccumBuffer,
- GL_FALSE, /* alpha */
- GL_FALSE /* aux bufs */);
-
- return GL_TRUE;
-
-drawable_fail:
-
- if (drawable)
- free(drawable->row);
-
- FREE(drawable);
-
- return GL_FALSE;
-}
-
-static void
-dri_destroy_buffer(__DRIdrawable * dPriv)
-{
- TRACE;
-
- if (dPriv) {
- struct dri_drawable *drawable = dri_drawable(dPriv);
- struct gl_framebuffer *fb;
-
- free(drawable->row);
-
- fb = &drawable->Base;
-
- fb->DeletePending = GL_TRUE;
- _mesa_reference_framebuffer(&fb, NULL);
- }
-}
-
-static void
-dri_swap_buffers(__DRIdrawable * dPriv)
-{
- __DRIscreen *sPriv = dPriv->driScreenPriv;
-
- GET_CURRENT_CONTEXT(ctx);
-
- struct dri_drawable *drawable = dri_drawable(dPriv);
- struct gl_framebuffer *fb;
- struct swrast_renderbuffer *frontrb, *backrb;
-
- TRACE;
-
- fb = &drawable->Base;
-
- frontrb =
- swrast_renderbuffer(fb->Attachment[BUFFER_FRONT_LEFT].Renderbuffer);
- backrb =
- swrast_renderbuffer(fb->Attachment[BUFFER_BACK_LEFT].Renderbuffer);
-
- /* check for signle-buffered */
- if (backrb == NULL)
- return;
-
- /* check if swapping currently bound buffer */
- if (ctx && ctx->DrawBuffer == fb) {
- /* flush pending rendering */
- _mesa_notifySwapBuffers(ctx);
- }
-
- sPriv->swrast_loader->putImage(dPriv, __DRI_SWRAST_IMAGE_OP_SWAP,
- 0, 0,
- frontrb->Base.Width,
- frontrb->Base.Height,
- backrb->Base.Data,
- dPriv->loaderPrivate);
-}
-
-
-/**
- * General device driver functions.
- */
-
-static void
-get_window_size( struct gl_framebuffer *fb, GLsizei *w, GLsizei *h )
-{
- __DRIdrawable *dPriv = swrast_drawable(fb)->dPriv;
- __DRIscreen *sPriv = dPriv->driScreenPriv;
- int x, y;
-
- sPriv->swrast_loader->getDrawableInfo(dPriv,
- &x, &y, w, h,
- dPriv->loaderPrivate);
-}
-
-static void
-swrast_check_and_update_window_size( struct gl_context *ctx, struct gl_framebuffer *fb )
-{
- GLsizei width, height;
-
- get_window_size(fb, &width, &height);
- if (fb->Width != width || fb->Height != height) {
- _mesa_resize_framebuffer(ctx, fb, width, height);
- }
-}
-
-static const GLubyte *
-get_string(struct gl_context *ctx, GLenum pname)
-{
- (void) ctx;
- switch (pname) {
- case GL_VENDOR:
- return (const GLubyte *) "Mesa Project";
- case GL_RENDERER:
- return (const GLubyte *) "Software Rasterizer";
- default:
- return NULL;
- }
-}
-
-static void
-update_state( struct gl_context *ctx, GLuint new_state )
-{
- /* not much to do here - pass it on */
- _swrast_InvalidateState( ctx, new_state );
- _swsetup_InvalidateState( ctx, new_state );
- _vbo_InvalidateState( ctx, new_state );
- _tnl_InvalidateState( ctx, new_state );
-}
-
-static void
-viewport(struct gl_context *ctx, GLint x, GLint y, GLsizei w, GLsizei h)
-{
- struct gl_framebuffer *draw = ctx->WinSysDrawBuffer;
- struct gl_framebuffer *read = ctx->WinSysReadBuffer;
-
- swrast_check_and_update_window_size(ctx, draw);
- swrast_check_and_update_window_size(ctx, read);
-}
-
-static gl_format swrastChooseTextureFormat(struct gl_context * ctx,
- GLint internalFormat,
- GLenum format,
- GLenum type)
-{
- if (internalFormat == GL_RGB)
- return MESA_FORMAT_XRGB8888;
- return _mesa_choose_tex_format(ctx, internalFormat, format, type);
-}
-
-static void
-swrast_init_driver_functions(struct dd_function_table *driver)
-{
- driver->GetString = get_string;
- driver->UpdateState = update_state;
- driver->GetBufferSize = NULL;
- driver->Viewport = viewport;
- driver->ChooseTextureFormat = swrastChooseTextureFormat;
-}
-
-static const char *es2_extensions[] = {
- /* Used by mesa internally (cf all_mesa_extensions in ../common/utils.c) */
- "GL_ARB_draw_buffers",
- "GL_ARB_multisample",
- "GL_ARB_texture_compression",
- "GL_ARB_transpose_matrix",
- "GL_ARB_vertex_buffer_object",
- "GL_ARB_window_pos",
- "GL_EXT_blend_func_separate",
- "GL_EXT_compiled_vertex_array",
- "GL_EXT_framebuffer_blit",
- "GL_EXT_multi_draw_arrays",
- "GL_EXT_polygon_offset",
- "GL_EXT_texture_object",
- "GL_EXT_vertex_array",
- "GL_IBM_multimode_draw_arrays",
- "GL_MESA_window_pos",
- "GL_NV_vertex_program",
-
- /* Required by GLES2 */
- "GL_ARB_fragment_program",
- "GL_ARB_fragment_shader",
- "GL_ARB_multitexture",
- "GL_ARB_shader_objects",
- "GL_ARB_texture_cube_map",
- "GL_ARB_texture_mirrored_repeat",
- "GL_ARB_texture_non_power_of_two",
- "GL_ARB_vertex_shader",
- "GL_EXT_blend_color",
- "GL_EXT_blend_equation_separate",
- "GL_EXT_blend_minmax",
- "GL_EXT_blend_subtract",
- "GL_EXT_stencil_wrap",
-
- /* Optional GLES2 */
- "GL_ARB_framebuffer_object",
- "GL_EXT_texture_filter_anisotropic",
- "GL_ARB_depth_texture",
- "GL_EXT_packed_depth_stencil",
- "GL_EXT_framebuffer_object",
- NULL,
-};
-
-static void
-InitExtensionsES2(struct gl_context *ctx)
-{
- int i;
-
- /* Can't use driInitExtensions() since it uses extensions from
- * main/remap_helper.h when called the first time. */
-
- for (i = 0; es2_extensions[i]; i++)
- _mesa_enable_extension(ctx, es2_extensions[i]);
-}
-
-/**
- * Context-related functions.
- */
-
-static GLboolean
-dri_create_context(gl_api api,
- const struct gl_config * visual,
- __DRIcontext * cPriv, void *sharedContextPrivate)
-{
- struct dri_context *ctx = NULL;
- struct dri_context *share = (struct dri_context *)sharedContextPrivate;
- struct gl_context *mesaCtx = NULL;
- struct gl_context *sharedCtx = NULL;
- struct dd_function_table functions;
-
- TRACE;
-
- ctx = CALLOC_STRUCT(dri_context);
- if (ctx == NULL)
- goto context_fail;
-
- cPriv->driverPrivate = ctx;
- ctx->cPriv = cPriv;
-
- /* build table of device driver functions */
- _mesa_init_driver_functions(&functions);
- swrast_init_driver_functions(&functions);
-
- if (share) {
- sharedCtx = &share->Base;
- }
-
- mesaCtx = &ctx->Base;
-
- /* basic context setup */
- if (!_mesa_initialize_context(mesaCtx, api, visual, sharedCtx, &functions, (void *) cPriv)) {
- goto context_fail;
- }
-
- /* do bounds checking to prevent segfaults and server crashes! */
- mesaCtx->Const.CheckArrayBounds = GL_TRUE;
-
- /* create module contexts */
- _swrast_CreateContext( mesaCtx );
- _vbo_CreateContext( mesaCtx );
- _tnl_CreateContext( mesaCtx );
- _swsetup_CreateContext( mesaCtx );
- _swsetup_Wakeup( mesaCtx );
-
- /* use default TCL pipeline */
- {
- TNLcontext *tnl = TNL_CONTEXT(mesaCtx);
- tnl->Driver.RunPipeline = _tnl_run_pipeline;
- }
-
- _mesa_meta_init(mesaCtx);
- _mesa_enable_sw_extensions(mesaCtx);
-
- switch (api) {
- case API_OPENGL:
- _mesa_enable_1_3_extensions(mesaCtx);
- _mesa_enable_1_4_extensions(mesaCtx);
- _mesa_enable_1_5_extensions(mesaCtx);
- _mesa_enable_2_0_extensions(mesaCtx);
- _mesa_enable_2_1_extensions(mesaCtx);
-
- driInitExtensions( mesaCtx, NULL, GL_FALSE );
- break;
- case API_OPENGLES:
- _mesa_enable_1_3_extensions(mesaCtx);
- _mesa_enable_1_4_extensions(mesaCtx);
- _mesa_enable_1_5_extensions(mesaCtx);
-
- break;
- case API_OPENGLES2:
- InitExtensionsES2( mesaCtx);
- break;
- }
-
- return GL_TRUE;
-
-context_fail:
-
- FREE(ctx);
-
- return GL_FALSE;
-}
-
-static void
-dri_destroy_context(__DRIcontext * cPriv)
-{
- TRACE;
-
- if (cPriv) {
- struct dri_context *ctx = dri_context(cPriv);
- struct gl_context *mesaCtx;
-
- mesaCtx = &ctx->Base;
-
- _mesa_meta_free(mesaCtx);
- _swsetup_DestroyContext( mesaCtx );
- _swrast_DestroyContext( mesaCtx );
- _tnl_DestroyContext( mesaCtx );
- _vbo_DestroyContext( mesaCtx );
- _mesa_destroy_context( mesaCtx );
- }
-}
-
-static GLboolean
-dri_make_current(__DRIcontext * cPriv,
- __DRIdrawable * driDrawPriv,
- __DRIdrawable * driReadPriv)
-{
- struct gl_context *mesaCtx;
- struct gl_framebuffer *mesaDraw;
- struct gl_framebuffer *mesaRead;
- TRACE;
-
- if (cPriv) {
- struct dri_context *ctx = dri_context(cPriv);
- struct dri_drawable *draw;
- struct dri_drawable *read;
-
- if (!driDrawPriv || !driReadPriv)
- return GL_FALSE;
-
- draw = dri_drawable(driDrawPriv);
- read = dri_drawable(driReadPriv);
- mesaCtx = &ctx->Base;
- mesaDraw = &draw->Base;
- mesaRead = &read->Base;
-
- /* check for same context and buffer */
- if (mesaCtx == _mesa_get_current_context()
- && mesaCtx->DrawBuffer == mesaDraw
- && mesaCtx->ReadBuffer == mesaRead) {
- return GL_TRUE;
- }
-
- _glapi_check_multithread();
-
- swrast_check_and_update_window_size(mesaCtx, mesaDraw);
- if (mesaRead != mesaDraw)
- swrast_check_and_update_window_size(mesaCtx, mesaRead);
-
- _mesa_make_current( mesaCtx,
- mesaDraw,
- mesaRead );
- }
- else {
- /* unbind */
- _mesa_make_current( NULL, NULL, NULL );
- }
-
- return GL_TRUE;
-}
-
-static GLboolean
-dri_unbind_context(__DRIcontext * cPriv)
-{
- TRACE;
- (void) cPriv;
-
- /* Unset current context and dispath table */
- _mesa_make_current(NULL, NULL, NULL);
-
- return GL_TRUE;
-}
-
-
-const struct __DriverAPIRec driDriverAPI = {
- .InitScreen = dri_init_screen,
- .DestroyScreen = dri_destroy_screen,
- .CreateContext = dri_create_context,
- .DestroyContext = dri_destroy_context,
- .CreateBuffer = dri_create_buffer,
- .DestroyBuffer = dri_destroy_buffer,
- .SwapBuffers = dri_swap_buffers,
- .MakeCurrent = dri_make_current,
- .UnbindContext = dri_unbind_context,
-};
-
-/* This is the table of extensions that the loader will dlsym() for. */
-PUBLIC const __DRIextension *__driDriverExtensions[] = {
- &driCoreExtension.base,
- &driSWRastExtension.base,
- NULL
-};
+/*
+ * Copyright 2008, 2010 George Sapountzis <gsapountzis@gmail.com>
+ *
+ * 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.
+ */
+
+/*
+ * DRI software rasterizer
+ *
+ * This is the mesa swrast module packaged into a DRI driver structure.
+ *
+ * The front-buffer is allocated by the loader. The loader provides read/write
+ * callbacks for access to the front-buffer. The driver uses a scratch row for
+ * front-buffer rendering to avoid repeated calls to the loader.
+ *
+ * The back-buffer is allocated by the driver and is private.
+ */
+
+#ifdef _MSC_VER
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+#endif
+
+#include "main/context.h"
+#include "main/extensions.h"
+#include "main/formats.h"
+#include "main/framebuffer.h"
+#include "main/imports.h"
+#include "main/renderbuffer.h"
+#include "swrast/swrast.h"
+#include "swrast_setup/swrast_setup.h"
+#include "tnl/tnl.h"
+#include "tnl/t_context.h"
+#include "tnl/t_pipeline.h"
+#include "vbo/vbo.h"
+#include "drivers/common/driverfuncs.h"
+#include "drivers/common/meta.h"
+#include "utils.h"
+
+#include "main/teximage.h"
+#include "main/texformat.h"
+#include "main/texstate.h"
+
+#include "swrast_priv.h"
+
+
+/**
+ * Screen and config-related functions
+ */
+
+static void swrastSetTexBuffer2(__DRIcontext *pDRICtx, GLint target,
+ GLint texture_format, __DRIdrawable *dPriv)
+{
+ struct dri_context *dri_ctx;
+ int x, y, w, h;
+ __DRIscreen *sPriv = dPriv->driScreenPriv;
+ struct gl_texture_unit *texUnit;
+ struct gl_texture_object *texObj;
+ struct gl_texture_image *texImage;
+ uint32_t internalFormat;
+ gl_format texFormat;
+
+ dri_ctx = pDRICtx->driverPrivate;
+
+ internalFormat = (texture_format == __DRI_TEXTURE_FORMAT_RGB ? 3 : 4);
+
+ texUnit = _mesa_get_current_tex_unit(&dri_ctx->Base);
+ texObj = _mesa_select_tex_object(&dri_ctx->Base, texUnit, target);
+ texImage = _mesa_get_tex_image(&dri_ctx->Base, texObj, target, 0);
+
+ _mesa_lock_texture(&dri_ctx->Base, texObj);
+
+ sPriv->swrast_loader->getDrawableInfo(dPriv, &x, &y, &w, &h, dPriv->loaderPrivate);
+
+ if (texture_format == __DRI_TEXTURE_FORMAT_RGB)
+ texFormat = MESA_FORMAT_XRGB8888;
+ else
+ texFormat = MESA_FORMAT_ARGB8888;
+
+ _mesa_init_teximage_fields(&dri_ctx->Base, target, texImage,
+ w, h, 1, 0, internalFormat, texFormat);
+
+ sPriv->swrast_loader->getImage(dPriv, x, y, w, h, (char *)texImage->Data,
+ dPriv->loaderPrivate);
+
+ _mesa_unlock_texture(&dri_ctx->Base, texObj);
+}
+
+static void swrastSetTexBuffer(__DRIcontext *pDRICtx, GLint target,
+ __DRIdrawable *dPriv)
+{
+ swrastSetTexBuffer2(pDRICtx, target, __DRI_TEXTURE_FORMAT_RGBA, dPriv);
+}
+
+static const __DRItexBufferExtension swrastTexBufferExtension = {
+ { __DRI_TEX_BUFFER, __DRI_TEX_BUFFER_VERSION },
+ swrastSetTexBuffer,
+ swrastSetTexBuffer2,
+};
+
+static const __DRIextension *dri_screen_extensions[] = {
+ &swrastTexBufferExtension.base,
+ NULL
+};
+
+static __DRIconfig **
+swrastFillInModes(__DRIscreen *psp,
+ unsigned pixel_bits, unsigned depth_bits,
+ unsigned stencil_bits, GLboolean have_back_buffer)
+{
+ __DRIconfig **configs;
+ unsigned depth_buffer_factor;
+ unsigned back_buffer_factor;
+ GLenum fb_format;
+ GLenum fb_type;
+
+ /* GLX_SWAP_COPY_OML is only supported because the Intel driver doesn't
+ * support pageflipping at all.
+ */
+ static const GLenum back_buffer_modes[] = {
+ GLX_NONE, GLX_SWAP_UNDEFINED_OML
+ };
+
+ uint8_t depth_bits_array[4];
+ uint8_t stencil_bits_array[4];
+ uint8_t msaa_samples_array[1];
+
+ depth_bits_array[0] = 0;
+ depth_bits_array[1] = 0;
+ depth_bits_array[2] = depth_bits;
+ depth_bits_array[3] = depth_bits;
+
+ /* Just like with the accumulation buffer, always provide some modes
+ * with a stencil buffer.
+ */
+ stencil_bits_array[0] = 0;
+ stencil_bits_array[1] = (stencil_bits == 0) ? 8 : stencil_bits;
+ stencil_bits_array[2] = 0;
+ stencil_bits_array[3] = (stencil_bits == 0) ? 8 : stencil_bits;
+
+ msaa_samples_array[0] = 0;
+
+ depth_buffer_factor = 4;
+ back_buffer_factor = 2;
+
+ switch (pixel_bits) {
+ case 8:
+ fb_format = GL_RGB;
+ fb_type = GL_UNSIGNED_BYTE_2_3_3_REV;
+ break;
+ case 16:
+ fb_format = GL_RGB;
+ fb_type = GL_UNSIGNED_SHORT_5_6_5;
+ break;
+ case 24:
+ fb_format = GL_BGR;
+ fb_type = GL_UNSIGNED_INT_8_8_8_8_REV;
+ break;
+ case 32:
+ fb_format = GL_BGRA;
+ fb_type = GL_UNSIGNED_INT_8_8_8_8_REV;
+ break;
+ default:
+ fprintf(stderr, "[%s:%u] bad depth %d\n", __FUNCTION__, __LINE__,
+ pixel_bits);
+ return NULL;
+ }
+
+ configs = driCreateConfigs(fb_format, fb_type,
+ depth_bits_array, stencil_bits_array,
+ depth_buffer_factor, back_buffer_modes,
+ back_buffer_factor, msaa_samples_array, 1,
+ GL_TRUE);
+ if (configs == NULL) {
+ fprintf(stderr, "[%s:%u] Error creating FBConfig!\n", __FUNCTION__,
+ __LINE__);
+ return NULL;
+ }
+
+ return configs;
+}
+
+static const __DRIconfig **
+dri_init_screen(__DRIscreen * psp)
+{
+ __DRIconfig **configs8, **configs16, **configs24, **configs32;
+
+ TRACE;
+
+ psp->extensions = dri_screen_extensions;
+
+ configs8 = swrastFillInModes(psp, 8, 8, 0, 1);
+ configs16 = swrastFillInModes(psp, 16, 16, 0, 1);
+ configs24 = swrastFillInModes(psp, 24, 24, 8, 1);
+ configs32 = swrastFillInModes(psp, 32, 24, 8, 1);
+
+ configs16 = driConcatConfigs(configs8, configs16);
+ configs24 = driConcatConfigs(configs16, configs24);
+ configs32 = driConcatConfigs(configs24, configs32);
+
+ return (const __DRIconfig **)configs32;
+}
+
+static void
+dri_destroy_screen(__DRIscreen * sPriv)
+{
+ TRACE;
+}
+
+
+/**
+ * Framebuffer and renderbuffer-related functions.
+ */
+
+static GLuint
+choose_pixel_format(const struct gl_config *v)
+{
+ int depth = v->rgbBits;
+
+ if (depth == 32
+ && v->redMask == 0xff0000
+ && v->greenMask == 0x00ff00
+ && v->blueMask == 0x0000ff)
+ return PF_A8R8G8B8;
+ else if (depth == 24
+ && v->redMask == 0xff0000
+ && v->greenMask == 0x00ff00
+ && v->blueMask == 0x0000ff)
+ return PF_X8R8G8B8;
+ else if (depth == 16
+ && v->redMask == 0xf800
+ && v->greenMask == 0x07e0
+ && v->blueMask == 0x001f)
+ return PF_R5G6B5;
+ else if (depth == 8
+ && v->redMask == 0x07
+ && v->greenMask == 0x38
+ && v->blueMask == 0xc0)
+ return PF_R3G3B2;
+
+ _mesa_problem( NULL, "unexpected format in %s", __FUNCTION__ );
+ return 0;
+}
+
+static void
+swrast_delete_renderbuffer(struct gl_renderbuffer *rb)
+{
+ TRACE;
+
+ free(rb->Data);
+ free(rb);
+}
+
+/* see bytes_per_line in libGL */
+static INLINE int
+bytes_per_line(unsigned pitch_bits, unsigned mul)
+{
+ unsigned mask = mul - 1;
+
+ return ((pitch_bits + mask) & ~mask) / 8;
+}
+
+static GLboolean
+swrast_alloc_front_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
+ GLenum internalFormat, GLuint width, GLuint height)
+{
+ struct swrast_renderbuffer *xrb = swrast_renderbuffer(rb);
+
+ TRACE;
+
+ rb->Data = NULL;
+ rb->Width = width;
+ rb->Height = height;
+
+ xrb->pitch = bytes_per_line(width * xrb->bpp, 32);
+
+ return GL_TRUE;
+}
+
+static GLboolean
+swrast_alloc_back_storage(struct gl_context *ctx, struct gl_renderbuffer *rb,
+ GLenum internalFormat, GLuint width, GLuint height)
+{
+ struct swrast_renderbuffer *xrb = swrast_renderbuffer(rb);
+
+ TRACE;
+
+ free(rb->Data);
+
+ swrast_alloc_front_storage(ctx, rb, internalFormat, width, height);
+
+ rb->Data = malloc(height * xrb->pitch);
+
+ return GL_TRUE;
+}
+
+static struct swrast_renderbuffer *
+swrast_new_renderbuffer(const struct gl_config *visual, GLboolean front)
+{
+ struct swrast_renderbuffer *xrb = calloc(1, sizeof *xrb);
+ GLuint pixel_format;
+
+ TRACE;
+
+ if (!xrb)
+ return NULL;
+
+ _mesa_init_renderbuffer(&xrb->Base, 0);
+
+ pixel_format = choose_pixel_format(visual);
+
+ xrb->Base.Delete = swrast_delete_renderbuffer;
+ if (front) {
+ xrb->Base.AllocStorage = swrast_alloc_front_storage;
+ swrast_set_span_funcs_front(xrb, pixel_format);
+ }
+ else {
+ xrb->Base.AllocStorage = swrast_alloc_back_storage;
+ swrast_set_span_funcs_back(xrb, pixel_format);
+ }
+
+ switch (pixel_format) {
+ case PF_A8R8G8B8:
+ xrb->Base.Format = MESA_FORMAT_ARGB8888;
+ xrb->Base.InternalFormat = GL_RGBA;
+ xrb->Base._BaseFormat = GL_RGBA;
+ xrb->Base.DataType = GL_UNSIGNED_BYTE;
+ xrb->bpp = 32;
+ break;
+ case PF_X8R8G8B8:
+ xrb->Base.Format = MESA_FORMAT_ARGB8888; /* XXX */
+ xrb->Base.InternalFormat = GL_RGB;
+ xrb->Base._BaseFormat = GL_RGB;
+ xrb->Base.DataType = GL_UNSIGNED_BYTE;
+ xrb->bpp = 32;
+ break;
+ case PF_R5G6B5:
+ xrb->Base.Format = MESA_FORMAT_RGB565;
+ xrb->Base.InternalFormat = GL_RGB;
+ xrb->Base._BaseFormat = GL_RGB;
+ xrb->Base.DataType = GL_UNSIGNED_BYTE;
+ xrb->bpp = 16;
+ break;
+ case PF_R3G3B2:
+ xrb->Base.Format = MESA_FORMAT_RGB332;
+ xrb->Base.InternalFormat = GL_RGB;
+ xrb->Base._BaseFormat = GL_RGB;
+ xrb->Base.DataType = GL_UNSIGNED_BYTE;
+ xrb->bpp = 8;
+ break;
+ default:
+ return NULL;
+ }
+
+ return xrb;
+}
+
+static GLboolean
+dri_create_buffer(__DRIscreen * sPriv,
+ __DRIdrawable * dPriv,
+ const struct gl_config * visual, GLboolean isPixmap)
+{
+ struct dri_drawable *drawable = NULL;
+ struct gl_framebuffer *fb;
+ struct swrast_renderbuffer *frontrb, *backrb;
+
+ TRACE;
+
+ drawable = CALLOC_STRUCT(dri_drawable);
+ if (drawable == NULL)
+ goto drawable_fail;
+
+ dPriv->driverPrivate = drawable;
+ drawable->dPriv = dPriv;
+
+ drawable->row = malloc(MAX_WIDTH * 4);
+ if (drawable->row == NULL)
+ goto drawable_fail;
+
+ fb = &drawable->Base;
+
+ /* basic framebuffer setup */
+ _mesa_initialize_window_framebuffer(fb, visual);
+
+ /* add front renderbuffer */
+ frontrb = swrast_new_renderbuffer(visual, GL_TRUE);
+ _mesa_add_renderbuffer(fb, BUFFER_FRONT_LEFT, &frontrb->Base);
+
+ /* add back renderbuffer */
+ if (visual->doubleBufferMode) {
+ backrb = swrast_new_renderbuffer(visual, GL_FALSE);
+ _mesa_add_renderbuffer(fb, BUFFER_BACK_LEFT, &backrb->Base);
+ }
+
+ /* add software renderbuffers */
+ _mesa_add_soft_renderbuffers(fb,
+ GL_FALSE, /* color */
+ visual->haveDepthBuffer,
+ visual->haveStencilBuffer,
+ visual->haveAccumBuffer,
+ GL_FALSE, /* alpha */
+ GL_FALSE /* aux bufs */);
+
+ return GL_TRUE;
+
+drawable_fail:
+
+ if (drawable)
+ free(drawable->row);
+
+ FREE(drawable);
+
+ return GL_FALSE;
+}
+
+static void
+dri_destroy_buffer(__DRIdrawable * dPriv)
+{
+ TRACE;
+
+ if (dPriv) {
+ struct dri_drawable *drawable = dri_drawable(dPriv);
+ struct gl_framebuffer *fb;
+
+ free(drawable->row);
+
+ fb = &drawable->Base;
+
+ fb->DeletePending = GL_TRUE;
+ _mesa_reference_framebuffer(&fb, NULL);
+ }
+}
+
+static void
+dri_swap_buffers(__DRIdrawable * dPriv)
+{
+ __DRIscreen *sPriv = dPriv->driScreenPriv;
+
+ GET_CURRENT_CONTEXT(ctx);
+
+ struct dri_drawable *drawable = dri_drawable(dPriv);
+ struct gl_framebuffer *fb;
+ struct swrast_renderbuffer *frontrb, *backrb;
+
+ TRACE;
+
+ fb = &drawable->Base;
+
+ frontrb =
+ swrast_renderbuffer(fb->Attachment[BUFFER_FRONT_LEFT].Renderbuffer);
+ backrb =
+ swrast_renderbuffer(fb->Attachment[BUFFER_BACK_LEFT].Renderbuffer);
+
+ /* check for signle-buffered */
+ if (backrb == NULL)
+ return;
+
+ /* check if swapping currently bound buffer */
+ if (ctx && ctx->DrawBuffer == fb) {
+ /* flush pending rendering */
+ _mesa_notifySwapBuffers(ctx);
+ }
+
+ sPriv->swrast_loader->putImage(dPriv, __DRI_SWRAST_IMAGE_OP_SWAP,
+ 0, 0,
+ frontrb->Base.Width,
+ frontrb->Base.Height,
+ backrb->Base.Data,
+ dPriv->loaderPrivate);
+}
+
+
+/**
+ * General device driver functions.
+ */
+
+static void
+get_window_size( struct gl_framebuffer *fb, GLsizei *w, GLsizei *h )
+{
+ __DRIdrawable *dPriv = swrast_drawable(fb)->dPriv;
+ __DRIscreen *sPriv = dPriv->driScreenPriv;
+ int x, y;
+
+ sPriv->swrast_loader->getDrawableInfo(dPriv,
+ &x, &y, w, h,
+ dPriv->loaderPrivate);
+}
+
+static void
+swrast_check_and_update_window_size( struct gl_context *ctx, struct gl_framebuffer *fb )
+{
+ GLsizei width, height;
+
+ get_window_size(fb, &width, &height);
+ if (fb->Width != width || fb->Height != height) {
+ _mesa_resize_framebuffer(ctx, fb, width, height);
+ }
+}
+
+static const GLubyte *
+get_string(struct gl_context *ctx, GLenum pname)
+{
+ (void) ctx;
+ switch (pname) {
+ case GL_VENDOR:
+ return (const GLubyte *) "Mesa Project";
+ case GL_RENDERER:
+ return (const GLubyte *) "Software Rasterizer";
+ default:
+ return NULL;
+ }
+}
+
+static void
+update_state( struct gl_context *ctx, GLuint new_state )
+{
+ /* not much to do here - pass it on */
+ _swrast_InvalidateState( ctx, new_state );
+ _swsetup_InvalidateState( ctx, new_state );
+ _vbo_InvalidateState( ctx, new_state );
+ _tnl_InvalidateState( ctx, new_state );
+}
+
+static void
+viewport(struct gl_context *ctx, GLint x, GLint y, GLsizei w, GLsizei h)
+{
+ struct gl_framebuffer *draw = ctx->WinSysDrawBuffer;
+ struct gl_framebuffer *read = ctx->WinSysReadBuffer;
+
+ swrast_check_and_update_window_size(ctx, draw);
+ swrast_check_and_update_window_size(ctx, read);
+}
+
+static gl_format swrastChooseTextureFormat(struct gl_context * ctx,
+ GLint internalFormat,
+ GLenum format,
+ GLenum type)
+{
+ if (internalFormat == GL_RGB)
+ return MESA_FORMAT_XRGB8888;
+ return _mesa_choose_tex_format(ctx, internalFormat, format, type);
+}
+
+static void
+swrast_init_driver_functions(struct dd_function_table *driver)
+{
+ driver->GetString = get_string;
+ driver->UpdateState = update_state;
+ driver->GetBufferSize = NULL;
+ driver->Viewport = viewport;
+ driver->ChooseTextureFormat = swrastChooseTextureFormat;
+}
+
+static const char *es2_extensions[] = {
+ /* Used by mesa internally (cf all_mesa_extensions in ../common/utils.c) */
+ "GL_ARB_draw_buffers",
+ "GL_ARB_multisample",
+ "GL_ARB_texture_compression",
+ "GL_ARB_transpose_matrix",
+ "GL_ARB_vertex_buffer_object",
+ "GL_ARB_window_pos",
+ "GL_EXT_blend_func_separate",
+ "GL_EXT_compiled_vertex_array",
+ "GL_EXT_framebuffer_blit",
+ "GL_EXT_multi_draw_arrays",
+ "GL_EXT_polygon_offset",
+ "GL_EXT_texture_object",
+ "GL_EXT_vertex_array",
+ "GL_IBM_multimode_draw_arrays",
+ "GL_MESA_window_pos",
+ "GL_NV_vertex_program",
+
+ /* Required by GLES2 */
+ "GL_ARB_fragment_program",
+ "GL_ARB_fragment_shader",
+ "GL_ARB_multitexture",
+ "GL_ARB_shader_objects",
+ "GL_ARB_texture_cube_map",
+ "GL_ARB_texture_mirrored_repeat",
+ "GL_ARB_texture_non_power_of_two",
+ "GL_ARB_vertex_shader",
+ "GL_EXT_blend_color",
+ "GL_EXT_blend_equation_separate",
+ "GL_EXT_blend_minmax",
+ "GL_EXT_blend_subtract",
+ "GL_EXT_stencil_wrap",
+
+ /* Optional GLES2 */
+ "GL_ARB_framebuffer_object",
+ "GL_EXT_texture_filter_anisotropic",
+ "GL_ARB_depth_texture",
+ "GL_EXT_packed_depth_stencil",
+ "GL_EXT_framebuffer_object",
+ NULL,
+};
+
+static void
+InitExtensionsES2(struct gl_context *ctx)
+{
+ int i;
+
+ /* Can't use driInitExtensions() since it uses extensions from
+ * main/remap_helper.h when called the first time. */
+
+ for (i = 0; es2_extensions[i]; i++)
+ _mesa_enable_extension(ctx, es2_extensions[i]);
+}
+
+/**
+ * Context-related functions.
+ */
+
+static GLboolean
+dri_create_context(gl_api api,
+ const struct gl_config * visual,
+ __DRIcontext * cPriv, void *sharedContextPrivate)
+{
+ struct dri_context *ctx = NULL;
+ struct dri_context *share = (struct dri_context *)sharedContextPrivate;
+ struct gl_context *mesaCtx = NULL;
+ struct gl_context *sharedCtx = NULL;
+ struct dd_function_table functions;
+
+ TRACE;
+
+ ctx = CALLOC_STRUCT(dri_context);
+ if (ctx == NULL)
+ goto context_fail;
+
+ cPriv->driverPrivate = ctx;
+ ctx->cPriv = cPriv;
+
+ /* build table of device driver functions */
+ _mesa_init_driver_functions(&functions);
+ swrast_init_driver_functions(&functions);
+
+ if (share) {
+ sharedCtx = &share->Base;
+ }
+
+ mesaCtx = &ctx->Base;
+
+ /* basic context setup */
+ if (!_mesa_initialize_context(mesaCtx, api, visual, sharedCtx, &functions, (void *) cPriv)) {
+ goto context_fail;
+ }
+
+ /* do bounds checking to prevent segfaults and server crashes! */
+ mesaCtx->Const.CheckArrayBounds = GL_TRUE;
+
+ /* create module contexts */
+ _swrast_CreateContext( mesaCtx );
+ _vbo_CreateContext( mesaCtx );
+ _tnl_CreateContext( mesaCtx );
+ _swsetup_CreateContext( mesaCtx );
+ _swsetup_Wakeup( mesaCtx );
+
+ /* use default TCL pipeline */
+ {
+ TNLcontext *tnl = TNL_CONTEXT(mesaCtx);
+ tnl->Driver.RunPipeline = _tnl_run_pipeline;
+ }
+
+ _mesa_meta_init(mesaCtx);
+ _mesa_enable_sw_extensions(mesaCtx);
+
+ switch (api) {
+ case API_OPENGL:
+ _mesa_enable_1_3_extensions(mesaCtx);
+ _mesa_enable_1_4_extensions(mesaCtx);
+ _mesa_enable_1_5_extensions(mesaCtx);
+ _mesa_enable_2_0_extensions(mesaCtx);
+ _mesa_enable_2_1_extensions(mesaCtx);
+
+ driInitExtensions( mesaCtx, NULL, GL_FALSE );
+ break;
+ case API_OPENGLES:
+ _mesa_enable_1_3_extensions(mesaCtx);
+ _mesa_enable_1_4_extensions(mesaCtx);
+ _mesa_enable_1_5_extensions(mesaCtx);
+
+ break;
+ case API_OPENGLES2:
+ InitExtensionsES2( mesaCtx);
+ break;
+ }
+
+ return GL_TRUE;
+
+context_fail:
+
+ FREE(ctx);
+
+ return GL_FALSE;
+}
+
+static void
+dri_destroy_context(__DRIcontext * cPriv)
+{
+ TRACE;
+
+ if (cPriv) {
+ struct dri_context *ctx = dri_context(cPriv);
+ struct gl_context *mesaCtx;
+
+ mesaCtx = &ctx->Base;
+
+ _mesa_meta_free(mesaCtx);
+ _swsetup_DestroyContext( mesaCtx );
+ _swrast_DestroyContext( mesaCtx );
+ _tnl_DestroyContext( mesaCtx );
+ _vbo_DestroyContext( mesaCtx );
+ _mesa_destroy_context( mesaCtx );
+ }
+}
+
+static GLboolean
+dri_make_current(__DRIcontext * cPriv,
+ __DRIdrawable * driDrawPriv,
+ __DRIdrawable * driReadPriv)
+{
+ struct gl_context *mesaCtx;
+ struct gl_framebuffer *mesaDraw;
+ struct gl_framebuffer *mesaRead;
+ TRACE;
+
+ if (cPriv) {
+ struct dri_context *ctx = dri_context(cPriv);
+ struct dri_drawable *draw;
+ struct dri_drawable *read;
+
+ if (!driDrawPriv || !driReadPriv)
+ return GL_FALSE;
+
+ draw = dri_drawable(driDrawPriv);
+ read = dri_drawable(driReadPriv);
+ mesaCtx = &ctx->Base;
+ mesaDraw = &draw->Base;
+ mesaRead = &read->Base;
+
+ /* check for same context and buffer */
+ if (mesaCtx == _mesa_get_current_context()
+ && mesaCtx->DrawBuffer == mesaDraw
+ && mesaCtx->ReadBuffer == mesaRead) {
+ return GL_TRUE;
+ }
+
+ _glapi_check_multithread();
+
+ swrast_check_and_update_window_size(mesaCtx, mesaDraw);
+ if (mesaRead != mesaDraw)
+ swrast_check_and_update_window_size(mesaCtx, mesaRead);
+
+ _mesa_make_current( mesaCtx,
+ mesaDraw,
+ mesaRead );
+ }
+ else {
+ /* unbind */
+ _mesa_make_current( NULL, NULL, NULL );
+ }
+
+ return GL_TRUE;
+}
+
+static GLboolean
+dri_unbind_context(__DRIcontext * cPriv)
+{
+ TRACE;
+ (void) cPriv;
+
+ /* Unset current context and dispath table */
+ _mesa_make_current(NULL, NULL, NULL);
+
+ return GL_TRUE;
+}
+
+
+const struct __DriverAPIRec driDriverAPI = {
+ /*.InitScreen = */dri_init_screen,
+ /*.DestroyScreen = */dri_destroy_screen,
+ /*.CreateContext = */dri_create_context,
+ /*.DestroyContext = */dri_destroy_context,
+ /*.CreateBuffer = */dri_create_buffer,
+ /*.DestroyBuffer = */dri_destroy_buffer,
+ /*.SwapBuffers = */dri_swap_buffers,
+ /*.MakeCurrent = */dri_make_current,
+ /*.UnbindContext = */dri_unbind_context,
+};
+
+/* This is the table of extensions that the loader will dlsym() for. */
+PUBLIC const __DRIextension *__driDriverExtensions[] = {
+ &driCoreExtension.base,
+ &driSWRastExtension.base,
+ NULL
+};
diff --git a/mesalib/src/mesa/drivers/dri/swrast/swrast_priv.h b/mesalib/src/mesa/drivers/dri/swrast/swrast_priv.h
index 4c3c9830f..e61965147 100644
--- a/mesalib/src/mesa/drivers/dri/swrast/swrast_priv.h
+++ b/mesalib/src/mesa/drivers/dri/swrast/swrast_priv.h
@@ -32,6 +32,13 @@
#include "main/mtypes.h"
#include "drisw_util.h"
+#ifdef _MSC_VER
+#ifdef PUBLIC
+#undef PUBLIC
+#endif
+#define PUBLIC __declspec(dllexport)
+#endif
+
/**
* Debugging
diff --git a/mesalib/src/mesa/drivers/windows/gdi/wmesa.c b/mesalib/src/mesa/drivers/windows/gdi/wmesa.c
index 4a8b1b283..1a13e9f5c 100644
--- a/mesalib/src/mesa/drivers/windows/gdi/wmesa.c
+++ b/mesalib/src/mesa/drivers/windows/gdi/wmesa.c
@@ -1,1662 +1,1662 @@
-/*
- * Windows (Win32/Win64) device driver for Mesa
- *
- */
-
-#include "wmesadef.h"
-#include "colors.h"
-#include <GL/wmesa.h>
-#include <winuser.h>
-#include "context.h"
-#include "extensions.h"
-#include "framebuffer.h"
-#include "renderbuffer.h"
-#include "drivers/common/driverfuncs.h"
-#include "drivers/common/meta.h"
-#include "vbo/vbo.h"
-#include "swrast/swrast.h"
-#include "swrast_setup/swrast_setup.h"
-#include "tnl/tnl.h"
-#include "tnl/t_context.h"
-#include "tnl/t_pipeline.h"
-
-
-/* linked list of our Framebuffers (windows) */
-static WMesaFramebuffer FirstFramebuffer = NULL;
-
-
-/**
- * Create a new WMesaFramebuffer object which will correspond to the
- * given HDC (Window handle).
- */
-WMesaFramebuffer
-wmesa_new_framebuffer(HDC hdc, struct gl_config *visual)
-{
- WMesaFramebuffer pwfb
- = (WMesaFramebuffer) malloc(sizeof(struct wmesa_framebuffer));
- if (pwfb) {
- _mesa_initialize_window_framebuffer(&pwfb->Base, visual);
- pwfb->hDC = hdc;
- /* insert at head of list */
- pwfb->next = FirstFramebuffer;
- FirstFramebuffer = pwfb;
- }
- return pwfb;
-}
-
-/**
- * Given an hdc, free the corresponding WMesaFramebuffer
- */
-void
-wmesa_free_framebuffer(HDC hdc)
-{
- WMesaFramebuffer pwfb, prev;
- for (pwfb = FirstFramebuffer; pwfb; pwfb = pwfb->next) {
- if (pwfb->hDC == hdc)
- break;
- prev = pwfb;
- }
- if (pwfb) {
- struct gl_framebuffer *fb;
- if (pwfb == FirstFramebuffer)
- FirstFramebuffer = pwfb->next;
- else
- prev->next = pwfb->next;
- fb = &pwfb->Base;
- _mesa_reference_framebuffer(&fb, NULL);
- }
-}
-
-/**
- * Given an hdc, return the corresponding WMesaFramebuffer
- */
-WMesaFramebuffer
-wmesa_lookup_framebuffer(HDC hdc)
-{
- WMesaFramebuffer pwfb;
- for (pwfb = FirstFramebuffer; pwfb; pwfb = pwfb->next) {
- if (pwfb->hDC == hdc)
- return pwfb;
- }
- return NULL;
-}
-
-
-/**
- * Given a struct gl_framebuffer, return the corresponding WMesaFramebuffer.
- */
-static WMesaFramebuffer wmesa_framebuffer(struct gl_framebuffer *fb)
-{
- return (WMesaFramebuffer) fb;
-}
-
-
-/**
- * Given a struct gl_context, return the corresponding WMesaContext.
- */
-static WMesaContext wmesa_context(const struct gl_context *ctx)
-{
- return (WMesaContext) ctx;
-}
-
-
-/*
- * Every driver should implement a GetString function in order to
- * return a meaningful GL_RENDERER string.
- */
-static const GLubyte *wmesa_get_string(struct gl_context *ctx, GLenum name)
-{
- return (name == GL_RENDERER) ?
- (GLubyte *) "Mesa Windows GDI Driver" : NULL;
-}
-
-
-/*
- * Determine the pixel format based on the pixel size.
- */
-static void wmSetPixelFormat(WMesaFramebuffer pwfb, HDC hDC)
-{
- pwfb->cColorBits = GetDeviceCaps(hDC, BITSPIXEL);
-
- /* Only 16 and 32 bit targets are supported now */
- assert(pwfb->cColorBits == 0 ||
- pwfb->cColorBits == 16 ||
- pwfb->cColorBits == 24 ||
- pwfb->cColorBits == 32);
-
- switch(pwfb->cColorBits){
- case 8:
- pwfb->pixelformat = PF_INDEX8;
- break;
- case 16:
- pwfb->pixelformat = PF_5R6G5B;
- break;
- case 24:
- case 32:
- pwfb->pixelformat = PF_8R8G8B;
- break;
- default:
- pwfb->pixelformat = PF_BADFORMAT;
- }
-}
-
-
-/**
- * Create DIB for back buffer.
- * We write into this memory with the span routines and then blit it
- * to the window on a buffer swap.
- */
-BOOL wmCreateBackingStore(WMesaFramebuffer pwfb, long lxSize, long lySize)
-{
- HDC hdc = pwfb->hDC;
- LPBITMAPINFO pbmi = &(pwfb->bmi);
- HDC hic;
-
- pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
- pbmi->bmiHeader.biWidth = lxSize;
- pbmi->bmiHeader.biHeight= -lySize;
- pbmi->bmiHeader.biPlanes = 1;
- pbmi->bmiHeader.biBitCount = GetDeviceCaps(pwfb->hDC, BITSPIXEL);
- pbmi->bmiHeader.biCompression = BI_RGB;
- pbmi->bmiHeader.biSizeImage = 0;
- pbmi->bmiHeader.biXPelsPerMeter = 0;
- pbmi->bmiHeader.biYPelsPerMeter = 0;
- pbmi->bmiHeader.biClrUsed = 0;
- pbmi->bmiHeader.biClrImportant = 0;
-
- pwfb->cColorBits = pbmi->bmiHeader.biBitCount;
- pwfb->ScanWidth = (lxSize * (pwfb->cColorBits / 8) + 3) & ~3;
-
- hic = CreateIC("display", NULL, NULL, NULL);
- pwfb->dib_hDC = CreateCompatibleDC(hic);
-
- pwfb->hbmDIB = CreateDIBSection(hic,
- &pwfb->bmi,
- DIB_RGB_COLORS,
- (void **)&(pwfb->pbPixels),
- 0,
- 0);
- pwfb->hOldBitmap = SelectObject(pwfb->dib_hDC, pwfb->hbmDIB);
-
- DeleteDC(hic);
-
- wmSetPixelFormat(pwfb, pwfb->hDC);
- return TRUE;
-}
-
-
-static wmDeleteBackingStore(WMesaFramebuffer pwfb)
-{
- if (pwfb->hbmDIB) {
- SelectObject(pwfb->dib_hDC, pwfb->hOldBitmap);
- DeleteDC(pwfb->dib_hDC);
- DeleteObject(pwfb->hbmDIB);
- }
-}
-
-
-/**
- * Find the width and height of the window named by hdc.
- */
-static void
-get_window_size(HDC hdc, GLuint *width, GLuint *height)
-{
- if (WindowFromDC(hdc)) {
- RECT rect;
- GetClientRect(WindowFromDC(hdc), &rect);
- *width = rect.right - rect.left;
- *height = rect.bottom - rect.top;
- }
- else { /* Memory context */
- /* From contributed code - use the size of the desktop
- * for the size of a memory context (?) */
- *width = GetDeviceCaps(hdc, HORZRES);
- *height = GetDeviceCaps(hdc, VERTRES);
- }
-}
-
-
-static void
-wmesa_get_buffer_size(struct gl_framebuffer *buffer, GLuint *width, GLuint *height)
-{
- WMesaFramebuffer pwfb = wmesa_framebuffer(buffer);
- get_window_size(pwfb->hDC, width, height);
-}
-
-
-static void wmesa_flush(struct gl_context *ctx)
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->WinSysDrawBuffer);
-
- if (ctx->Visual.doubleBufferMode == 1) {
- BitBlt(pwfb->hDC, 0, 0, pwfb->Base.Width, pwfb->Base.Height,
- pwfb->dib_hDC, 0, 0, SRCCOPY);
- }
- else {
- /* Do nothing for single buffer */
- }
-}
-
-
-/**********************************************************************/
-/***** CLEAR Functions *****/
-/**********************************************************************/
-
-/* If we do not implement these, Mesa clears the buffers via the pixel
- * span writing interface, which is very slow for a clear operation.
- */
-
-/*
- * Set the color used to clear the color buffer.
- */
-static void clear_color(struct gl_context *ctx, const GLfloat color[4])
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLubyte col[3];
- UINT bytesPerPixel = pwfb->cColorBits / 8;
-
- CLAMPED_FLOAT_TO_UBYTE(col[0], color[0]);
- CLAMPED_FLOAT_TO_UBYTE(col[1], color[1]);
- CLAMPED_FLOAT_TO_UBYTE(col[2], color[2]);
- pwc->clearColorRef = RGB(col[0], col[1], col[2]);
- DeleteObject(pwc->clearPen);
- DeleteObject(pwc->clearBrush);
- pwc->clearPen = CreatePen(PS_SOLID, 1, pwc->clearColorRef);
- pwc->clearBrush = CreateSolidBrush(pwc->clearColorRef);
-}
-
-
-/*
- * Clear the specified region of the color buffer using the clear color
- * or index as specified by one of the two functions above.
- *
- * This procedure clears either the front and/or the back COLOR buffers.
- * Only the "left" buffer is cleared since we are not stereo.
- * Clearing of the other non-color buffers is left to the swrast.
- */
-
-static void clear(struct gl_context *ctx, GLbitfield mask)
-{
-#define FLIP(Y) (ctx->DrawBuffer->Height - (Y) - 1)
- const GLint x = ctx->DrawBuffer->_Xmin;
- const GLint y = ctx->DrawBuffer->_Ymin;
- const GLint height = ctx->DrawBuffer->_Ymax - ctx->DrawBuffer->_Ymin;
- const GLint width = ctx->DrawBuffer->_Xmax - ctx->DrawBuffer->_Xmin;
-
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- int done = 0;
-
- /* Let swrast do all the work if the masks are not set to
- * clear all channels. */
- if (!ctx->Color.ColorMask[0][0] ||
- !ctx->Color.ColorMask[0][1] ||
- !ctx->Color.ColorMask[0][2] ||
- !ctx->Color.ColorMask[0][3]) {
- _swrast_Clear(ctx, mask);
- return;
- }
-
- /* Back buffer */
- if (mask & BUFFER_BIT_BACK_LEFT) {
-
- int i, rowSize;
- UINT bytesPerPixel = pwfb->cColorBits / 8;
- LPBYTE lpb, clearRow;
- LPWORD lpw;
- BYTE bColor;
- WORD wColor;
- BYTE r, g, b;
- DWORD dwColor;
- LPDWORD lpdw;
-
- /* Try for a fast clear - clearing entire buffer with a single
- * byte value. */
- if (width == ctx->DrawBuffer->Width &&
- height == ctx->DrawBuffer->Height) { /* entire buffer */
- /* Now check for an easy clear value */
- switch (bytesPerPixel) {
- case 1:
- bColor = BGR8(GetRValue(pwc->clearColorRef),
- GetGValue(pwc->clearColorRef),
- GetBValue(pwc->clearColorRef));
- memset(pwfb->pbPixels, bColor,
- pwfb->ScanWidth * height);
- done = 1;
- break;
- case 2:
- wColor = BGR16(GetRValue(pwc->clearColorRef),
- GetGValue(pwc->clearColorRef),
- GetBValue(pwc->clearColorRef));
- if (((wColor >> 8) & 0xff) == (wColor & 0xff)) {
- memset(pwfb->pbPixels, wColor & 0xff,
- pwfb->ScanWidth * height);
- done = 1;
- }
- break;
- case 3:
- /* fall through */
- case 4:
- if (GetRValue(pwc->clearColorRef) ==
- GetGValue(pwc->clearColorRef) &&
- GetRValue(pwc->clearColorRef) ==
- GetBValue(pwc->clearColorRef)) {
- memset(pwfb->pbPixels,
- GetRValue(pwc->clearColorRef),
- pwfb->ScanWidth * height);
- done = 1;
- }
- break;
- default:
- break;
- }
- } /* all */
-
- if (!done) {
- /* Need to clear a row at a time. Begin by setting the first
- * row in the area to be cleared to the clear color. */
-
- clearRow = pwfb->pbPixels +
- pwfb->ScanWidth * FLIP(y) +
- bytesPerPixel * x;
- switch (bytesPerPixel) {
- case 1:
- lpb = clearRow;
- bColor = BGR8(GetRValue(pwc->clearColorRef),
- GetGValue(pwc->clearColorRef),
- GetBValue(pwc->clearColorRef));
- memset(lpb, bColor, width);
- break;
- case 2:
- lpw = (LPWORD)clearRow;
- wColor = BGR16(GetRValue(pwc->clearColorRef),
- GetGValue(pwc->clearColorRef),
- GetBValue(pwc->clearColorRef));
- for (i=0; i<width; i++)
- *lpw++ = wColor;
- break;
- case 3:
- lpb = clearRow;
- r = GetRValue(pwc->clearColorRef);
- g = GetGValue(pwc->clearColorRef);
- b = GetBValue(pwc->clearColorRef);
- for (i=0; i<width; i++) {
- *lpb++ = b;
- *lpb++ = g;
- *lpb++ = r;
- }
- break;
- case 4:
- lpdw = (LPDWORD)clearRow;
- dwColor = BGR32(GetRValue(pwc->clearColorRef),
- GetGValue(pwc->clearColorRef),
- GetBValue(pwc->clearColorRef));
- for (i=0; i<width; i++)
- *lpdw++ = dwColor;
- break;
- default:
- break;
- } /* switch */
-
- /* copy cleared row to other rows in buffer */
- lpb = clearRow - pwfb->ScanWidth;
- rowSize = width * bytesPerPixel;
- for (i=1; i<height; i++) {
- memcpy(lpb, clearRow, rowSize);
- lpb -= pwfb->ScanWidth;
- }
- } /* not done */
- mask &= ~BUFFER_BIT_BACK_LEFT;
- } /* back buffer */
-
- /* front buffer */
- if (mask & BUFFER_BIT_FRONT_LEFT) {
- HDC DC = pwc->hDC;
- HPEN Old_Pen = SelectObject(DC, pwc->clearPen);
- HBRUSH Old_Brush = SelectObject(DC, pwc->clearBrush);
- Rectangle(DC,
- x,
- FLIP(y) + 1,
- x + width + 1,
- FLIP(y) - height + 1);
- SelectObject(DC, Old_Pen);
- SelectObject(DC, Old_Brush);
- mask &= ~BUFFER_BIT_FRONT_LEFT;
- } /* front buffer */
-
- /* Call swrast if there is anything left to clear (like DEPTH) */
- if (mask)
- _swrast_Clear(ctx, mask);
-
-#undef FLIP
-}
-
-
-/**********************************************************************/
-/***** PIXEL Functions *****/
-/**********************************************************************/
-
-#define FLIP(Y) (rb->Height - (Y) - 1)
-
-
-/**
- ** Front Buffer reading/writing
- ** These are slow, but work with all non-indexed visual types.
- **/
-
-/* Write a horizontal span of RGBA color pixels with a boolean mask. */
-static void write_rgba_span_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgba[][4],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_lookup_framebuffer(pwc->hDC);
- CONST BITMAPINFO bmi=
- {
- {
- sizeof(BITMAPINFOHEADER),
- n, 1, 1, 32, BI_RGB, 0, 1, 1, 0, 0
- }
- };
- HBITMAP bmp=0;
- HDC mdc=0;
- typedef union
- {
- unsigned i;
- struct {
- unsigned b:8, g:8, r:8, a:8;
- };
- } BGRA;
- BGRA *bgra, c;
- GLuint i;
-
- if (n < 16) { // the value 16 is just guessed
- y=FLIP(y);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- SetPixel(pwc->hDC, x+i, y,
- RGB(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]));
- }
- else {
- for (i=0; i<n; i++)
- SetPixel(pwc->hDC, x+i, y,
- RGB(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]));
- }
- }
- else {
- if (!pwfb) {
- _mesa_problem(NULL, "wmesa: write_rgba_span_front on unknown hdc");
- return;
- }
- bgra=malloc(n*sizeof(BGRA));
- if (!bgra) {
- _mesa_problem(NULL, "wmesa: write_rgba_span_front: out of memory");
- return;
- }
- c.a=0;
- if (mask) {
- for (i=0; i<n; i++) {
- if (mask[i]) {
- c.r=rgba[i][RCOMP];
- c.g=rgba[i][GCOMP];
- c.b=rgba[i][BCOMP];
- c.a=rgba[i][ACOMP];
- bgra[i]=c;
- }
- else
- bgra[i].i=0;
- }
- }
- else {
- for (i=0; i<n; i++) {
- c.r=rgba[i][RCOMP];
- c.g=rgba[i][GCOMP];
- c.b=rgba[i][BCOMP];
- c.a=rgba[i][ACOMP];
- bgra[i]=c;
- }
- }
- bmp=CreateBitmap(n, 1, 1, 32, bgra);
- mdc=CreateCompatibleDC(pwfb->hDC);
- SelectObject(mdc, bmp);
- y=FLIP(y);
- BitBlt(pwfb->hDC, x, y, n, 1, mdc, 0, 0, SRCCOPY);
- SelectObject(mdc, 0);
- DeleteObject(bmp);
- DeleteDC(mdc);
- free(bgra);
- }
-}
-
-/* Write a horizontal span of RGB color pixels with a boolean mask. */
-static void write_rgb_span_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgb[][3],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- GLuint i;
-
- (void) ctx;
- y=FLIP(y);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- SetPixel(pwc->hDC, x+i, y, RGB(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]));
- }
- else {
- for (i=0; i<n; i++)
- SetPixel(pwc->hDC, x+i, y, RGB(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]));
- }
-
-}
-
-/*
- * Write a horizontal span of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_span_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLchan color[4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- COLORREF colorref;
-
- (void) ctx;
- colorref = RGB(color[RCOMP], color[GCOMP], color[BCOMP]);
- y=FLIP(y);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- SetPixel(pwc->hDC, x+i, y, colorref);
- }
- else
- for (i=0; i<n; i++)
- SetPixel(pwc->hDC, x+i, y, colorref);
-
-}
-
-/* Write an array of RGBA pixels with a boolean mask. */
-static void write_rgba_pixels_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n,
- const GLint x[], const GLint y[],
- const GLubyte rgba[][4],
- const GLubyte mask[] )
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- (void) ctx;
- for (i=0; i<n; i++)
- if (mask[i])
- SetPixel(pwc->hDC, x[i], FLIP(y[i]),
- RGB(rgba[i][RCOMP], rgba[i][GCOMP],
- rgba[i][BCOMP]));
-}
-
-
-
-/*
- * Write an array of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_pixels_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n,
- const GLint x[], const GLint y[],
- const GLchan color[4],
- const GLubyte mask[] )
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- COLORREF colorref;
- (void) ctx;
- colorref = RGB(color[RCOMP], color[GCOMP], color[BCOMP]);
- for (i=0; i<n; i++)
- if (mask[i])
- SetPixel(pwc->hDC, x[i], FLIP(y[i]), colorref);
-}
-
-/* Read a horizontal span of color pixels. */
-static void read_rgba_span_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- GLubyte rgba[][4] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- GLuint i;
- COLORREF Color;
- y = FLIP(y);
- for (i=0; i<n; i++) {
- Color = GetPixel(pwc->hDC, x+i, y);
- rgba[i][RCOMP] = GetRValue(Color);
- rgba[i][GCOMP] = GetGValue(Color);
- rgba[i][BCOMP] = GetBValue(Color);
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/* Read an array of color pixels. */
-static void read_rgba_pixels_front(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- GLubyte rgba[][4])
-{
- WMesaContext pwc = wmesa_context(ctx);
- GLuint i;
- COLORREF Color;
- for (i=0; i<n; i++) {
- GLint y2 = FLIP(y[i]);
- Color = GetPixel(pwc->hDC, x[i], y2);
- rgba[i][RCOMP] = GetRValue(Color);
- rgba[i][GCOMP] = GetGValue(Color);
- rgba[i][BCOMP] = GetBValue(Color);
- rgba[i][ACOMP] = 255;
- }
-}
-
-/*********************************************************************/
-
-/* DOUBLE BUFFER 32-bit */
-
-#define WMSETPIXEL32(pwc, y, x, r, g, b) { \
-LPDWORD lpdw = ((LPDWORD)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (x)); \
-*lpdw = BGR32((r),(g),(b)); }
-
-
-
-/* Write a horizontal span of RGBA color pixels with a boolean mask. */
-static void write_rgba_span_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgba[][4],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPDWORD lpdw;
-
- (void) ctx;
-
- y=FLIP(y);
- lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpdw[i] = BGR32(rgba[i][RCOMP], rgba[i][GCOMP],
- rgba[i][BCOMP]);
- }
- else {
- for (i=0; i<n; i++)
- *lpdw++ = BGR32(rgba[i][RCOMP], rgba[i][GCOMP],
- rgba[i][BCOMP]);
- }
-}
-
-
-/* Write a horizontal span of RGB color pixels with a boolean mask. */
-static void write_rgb_span_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgb[][3],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPDWORD lpdw;
-
- (void) ctx;
-
- y=FLIP(y);
- lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpdw[i] = BGR32(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]);
- }
- else {
- for (i=0; i<n; i++)
- *lpdw++ = BGR32(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]);
- }
-}
-
-/*
- * Write a horizontal span of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_span_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLchan color[4],
- const GLubyte mask[])
-{
- LPDWORD lpdw;
- DWORD pixel;
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- y=FLIP(y);
- pixel = BGR32(color[RCOMP], color[GCOMP], color[BCOMP]);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpdw[i] = pixel;
- }
- else
- for (i=0; i<n; i++)
- *lpdw++ = pixel;
-
-}
-
-/* Write an array of RGBA pixels with a boolean mask. */
-static void write_rgba_pixels_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- const GLubyte rgba[][4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL32(pwfb, FLIP(y[i]), x[i],
- rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
-}
-
-/*
- * Write an array of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_pixels_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n,
- const GLint x[], const GLint y[],
- const GLchan color[4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL32(pwfb, FLIP(y[i]),x[i],color[RCOMP],
- color[GCOMP], color[BCOMP]);
-}
-
-/* Read a horizontal span of color pixels. */
-static void read_rgba_span_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- GLubyte rgba[][4] )
-{
- GLuint i;
- DWORD pixel;
- LPDWORD lpdw;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- y = FLIP(y);
- lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- for (i=0; i<n; i++) {
- pixel = lpdw[i];
- rgba[i][RCOMP] = (GLubyte)((pixel & 0x00ff0000) >> 16);
- rgba[i][GCOMP] = (GLubyte)((pixel & 0x0000ff00) >> 8);
- rgba[i][BCOMP] = (GLubyte)(pixel & 0x000000ff);
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/* Read an array of color pixels. */
-static void read_rgba_pixels_32(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- GLubyte rgba[][4])
-{
- GLuint i;
- DWORD pixel;
- LPDWORD lpdw;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- for (i=0; i<n; i++) {
- GLint y2 = FLIP(y[i]);
- lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + x[i];
- pixel = *lpdw;
- rgba[i][RCOMP] = (GLubyte)((pixel & 0x00ff0000) >> 16);
- rgba[i][GCOMP] = (GLubyte)((pixel & 0x0000ff00) >> 8);
- rgba[i][BCOMP] = (GLubyte)(pixel & 0x000000ff);
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/*********************************************************************/
-
-/* DOUBLE BUFFER 24-bit */
-
-#define WMSETPIXEL24(pwc, y, x, r, g, b) { \
-LPBYTE lpb = ((LPBYTE)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (3 * x)); \
-lpb[0] = (b); \
-lpb[1] = (g); \
-lpb[2] = (r); }
-
-/* Write a horizontal span of RGBA color pixels with a boolean mask. */
-static void write_rgba_span_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgba[][4],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPBYTE lpb;
-
- (void) ctx;
-
- y=FLIP(y);
- lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i]) {
- lpb[3*i] = rgba[i][BCOMP];
- lpb[3*i+1] = rgba[i][GCOMP];
- lpb[3*i+2] = rgba[i][RCOMP];
- }
- }
- else {
- for (i=0; i<n; i++) {
- *lpb++ = rgba[i][BCOMP];
- *lpb++ = rgba[i][GCOMP];
- *lpb++ = rgba[i][RCOMP];
- }
- }
-}
-
-
-/* Write a horizontal span of RGB color pixels with a boolean mask. */
-static void write_rgb_span_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgb[][3],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPBYTE lpb;
-
- (void) ctx;
-
- y=FLIP(y);
- lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i]) {
- lpb[3*i] = rgb[i][BCOMP];
- lpb[3*i+1] = rgb[i][GCOMP];
- lpb[3*i+2] = rgb[i][RCOMP];
- }
- }
- else {
- for (i=0; i<n; i++) {
- *lpb++ = rgb[i][BCOMP];
- *lpb++ = rgb[i][GCOMP];
- *lpb++ = rgb[i][RCOMP];
- }
- }
-}
-
-/*
- * Write a horizontal span of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_span_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLchan color[4],
- const GLubyte mask[])
-{
- LPBYTE lpb;
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
- y=FLIP(y);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i]) {
- lpb[3*i] = color[BCOMP];
- lpb[3*i+1] = color[GCOMP];
- lpb[3*i+2] = color[RCOMP];
- }
- }
- else
- for (i=0; i<n; i++) {
- *lpb++ = color[BCOMP];
- *lpb++ = color[GCOMP];
- *lpb++ = color[RCOMP];
- }
-}
-
-/* Write an array of RGBA pixels with a boolean mask. */
-static void write_rgba_pixels_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- const GLubyte rgba[][4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL24(pwfb, FLIP(y[i]), x[i],
- rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
-}
-
-/*
- * Write an array of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_pixels_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n,
- const GLint x[], const GLint y[],
- const GLchan color[4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL24(pwfb, FLIP(y[i]),x[i],color[RCOMP],
- color[GCOMP], color[BCOMP]);
-}
-
-/* Read a horizontal span of color pixels. */
-static void read_rgba_span_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- GLubyte rgba[][4] )
-{
- GLuint i;
- LPBYTE lpb;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- y = FLIP(y);
- lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
- for (i=0; i<n; i++) {
- rgba[i][RCOMP] = lpb[3*i+2];
- rgba[i][GCOMP] = lpb[3*i+1];
- rgba[i][BCOMP] = lpb[3*i];
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/* Read an array of color pixels. */
-static void read_rgba_pixels_24(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- GLubyte rgba[][4])
-{
- GLuint i;
- LPBYTE lpb;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- for (i=0; i<n; i++) {
- GLint y2 = FLIP(y[i]);
- lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + (3 * x[i]);
- rgba[i][RCOMP] = lpb[3*i+2];
- rgba[i][GCOMP] = lpb[3*i+1];
- rgba[i][BCOMP] = lpb[3*i];
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/*********************************************************************/
-
-/* DOUBLE BUFFER 16-bit */
-
-#define WMSETPIXEL16(pwc, y, x, r, g, b) { \
-LPWORD lpw = ((LPWORD)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (x)); \
-*lpw = BGR16((r),(g),(b)); }
-
-
-
-/* Write a horizontal span of RGBA color pixels with a boolean mask. */
-static void write_rgba_span_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgba[][4],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPWORD lpw;
-
- (void) ctx;
-
- y=FLIP(y);
- lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpw[i] = BGR16(rgba[i][RCOMP], rgba[i][GCOMP],
- rgba[i][BCOMP]);
- }
- else {
- for (i=0; i<n; i++)
- *lpw++ = BGR16(rgba[i][RCOMP], rgba[i][GCOMP],
- rgba[i][BCOMP]);
- }
-}
-
-
-/* Write a horizontal span of RGB color pixels with a boolean mask. */
-static void write_rgb_span_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLubyte rgb[][3],
- const GLubyte mask[] )
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- GLuint i;
- LPWORD lpw;
-
- (void) ctx;
-
- y=FLIP(y);
- lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpw[i] = BGR16(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]);
- }
- else {
- for (i=0; i<n; i++)
- *lpw++ = BGR16(rgb[i][RCOMP], rgb[i][GCOMP],
- rgb[i][BCOMP]);
- }
-}
-
-/*
- * Write a horizontal span of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_span_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- const GLchan color[4],
- const GLubyte mask[])
-{
- LPWORD lpw;
- WORD pixel;
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- (void) ctx;
- lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- y=FLIP(y);
- pixel = BGR16(color[RCOMP], color[GCOMP], color[BCOMP]);
- if (mask) {
- for (i=0; i<n; i++)
- if (mask[i])
- lpw[i] = pixel;
- }
- else
- for (i=0; i<n; i++)
- *lpw++ = pixel;
-
-}
-
-/* Write an array of RGBA pixels with a boolean mask. */
-static void write_rgba_pixels_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- const GLubyte rgba[][4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- (void) ctx;
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL16(pwfb, FLIP(y[i]), x[i],
- rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
-}
-
-/*
- * Write an array of pixels with a boolean mask. The current color
- * is used for all pixels.
- */
-static void write_mono_rgba_pixels_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n,
- const GLint x[], const GLint y[],
- const GLchan color[4],
- const GLubyte mask[])
-{
- GLuint i;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
- (void) ctx;
- for (i=0; i<n; i++)
- if (mask[i])
- WMSETPIXEL16(pwfb, FLIP(y[i]),x[i],color[RCOMP],
- color[GCOMP], color[BCOMP]);
-}
-
-/* Read a horizontal span of color pixels. */
-static void read_rgba_span_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, GLint x, GLint y,
- GLubyte rgba[][4] )
-{
- GLuint i, pixel;
- LPWORD lpw;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- y = FLIP(y);
- lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
- for (i=0; i<n; i++) {
- pixel = lpw[i];
- /* Windows uses 5,5,5 for 16-bit */
- rgba[i][RCOMP] = (pixel & 0x7c00) >> 7;
- rgba[i][GCOMP] = (pixel & 0x03e0) >> 2;
- rgba[i][BCOMP] = (pixel & 0x001f) << 3;
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-/* Read an array of color pixels. */
-static void read_rgba_pixels_16(const struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLuint n, const GLint x[], const GLint y[],
- GLubyte rgba[][4])
-{
- GLuint i, pixel;
- LPWORD lpw;
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
-
- for (i=0; i<n; i++) {
- GLint y2 = FLIP(y[i]);
- lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + x[i];
- pixel = *lpw;
- /* Windows uses 5,5,5 for 16-bit */
- rgba[i][RCOMP] = (pixel & 0x7c00) >> 7;
- rgba[i][GCOMP] = (pixel & 0x03e0) >> 2;
- rgba[i][BCOMP] = (pixel & 0x001f) << 3;
- rgba[i][ACOMP] = 255;
- }
-}
-
-
-
-
-/**********************************************************************/
-/***** BUFFER Functions *****/
-/**********************************************************************/
-
-
-
-
-static void
-wmesa_delete_renderbuffer(struct gl_renderbuffer *rb)
-{
- free(rb);
-}
-
-
-/**
- * This is called by Mesa whenever it determines that the window size
- * has changed. Do whatever's needed to cope with that.
- */
-static GLboolean
-wmesa_renderbuffer_storage(struct gl_context *ctx,
- struct gl_renderbuffer *rb,
- GLenum internalFormat,
- GLuint width,
- GLuint height)
-{
- rb->Width = width;
- rb->Height = height;
- return GL_TRUE;
-}
-
-
-/**
- * Plug in the Get/PutRow/Values functions for a renderbuffer depending
- * on if we're drawing to the front or back color buffer.
- */
-void wmesa_set_renderbuffer_funcs(struct gl_renderbuffer *rb, int pixelformat,
- int cColorBits, int double_buffer)
-{
- if (double_buffer) {
- /* back buffer */
- /* Picking the correct span functions is important because
- * the DIB was allocated with the indicated depth. */
- switch(pixelformat) {
- case PF_5R6G5B:
- rb->PutRow = write_rgba_span_16;
- rb->PutRowRGB = write_rgb_span_16;
- rb->PutMonoRow = write_mono_rgba_span_16;
- rb->PutValues = write_rgba_pixels_16;
- rb->PutMonoValues = write_mono_rgba_pixels_16;
- rb->GetRow = read_rgba_span_16;
- rb->GetValues = read_rgba_pixels_16;
- break;
- case PF_8R8G8B:
- if (cColorBits == 24)
- {
- rb->PutRow = write_rgba_span_24;
- rb->PutRowRGB = write_rgb_span_24;
- rb->PutMonoRow = write_mono_rgba_span_24;
- rb->PutValues = write_rgba_pixels_24;
- rb->PutMonoValues = write_mono_rgba_pixels_24;
- rb->GetRow = read_rgba_span_24;
- rb->GetValues = read_rgba_pixels_24;
- }
- else
- {
- rb->PutRow = write_rgba_span_32;
- rb->PutRowRGB = write_rgb_span_32;
- rb->PutMonoRow = write_mono_rgba_span_32;
- rb->PutValues = write_rgba_pixels_32;
- rb->PutMonoValues = write_mono_rgba_pixels_32;
- rb->GetRow = read_rgba_span_32;
- rb->GetValues = read_rgba_pixels_32;
- }
- break;
- default:
- break;
- }
- }
- else {
- /* front buffer (actual Windows window) */
- rb->PutRow = write_rgba_span_front;
- rb->PutRowRGB = write_rgb_span_front;
- rb->PutMonoRow = write_mono_rgba_span_front;
- rb->PutValues = write_rgba_pixels_front;
- rb->PutMonoValues = write_mono_rgba_pixels_front;
- rb->GetRow = read_rgba_span_front;
- rb->GetValues = read_rgba_pixels_front;
- }
-}
-
-/**
- * Called by ctx->Driver.ResizeBuffers()
- * Resize the front/back colorbuffers to match the latest window size.
- */
-static void
-wmesa_resize_buffers(struct gl_context *ctx, struct gl_framebuffer *buffer,
- GLuint width, GLuint height)
-{
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_framebuffer(buffer);
-
- if (pwfb->Base.Width != width || pwfb->Base.Height != height) {
- /* Realloc back buffer */
- if (ctx->Visual.doubleBufferMode == 1) {
- wmDeleteBackingStore(pwfb);
- wmCreateBackingStore(pwfb, width, height);
- }
- }
- _mesa_resize_framebuffer(ctx, buffer, width, height);
-}
-
-
-/**
- * Called by glViewport.
- * This is a good time for us to poll the current window size and adjust
- * our renderbuffers to match the current window size.
- * Remember, we have no opportunity to respond to conventional
- * resize events since the driver has no event loop.
- * Thus, we poll.
- * MakeCurrent also ends up making a call here, so that ensures
- * we get the viewport set correctly, even if the app does not call
- * glViewport and relies on the defaults.
- */
-static void wmesa_viewport(struct gl_context *ctx,
- GLint x, GLint y,
- GLsizei width, GLsizei height)
-{
- WMesaContext pwc = wmesa_context(ctx);
- GLuint new_width, new_height;
-
- wmesa_get_buffer_size(ctx->WinSysDrawBuffer, &new_width, &new_height);
-
- /**
- * Resize buffers if the window size changed.
- */
- wmesa_resize_buffers(ctx, ctx->WinSysDrawBuffer, new_width, new_height);
- ctx->NewState |= _NEW_BUFFERS; /* to update scissor / window bounds */
-}
-
-
-
-
-/**
- * Called when the driver should update it's state, based on the new_state
- * flags.
- */
-static void wmesa_update_state(struct gl_context *ctx, GLuint new_state)
-{
- _swrast_InvalidateState(ctx, new_state);
- _swsetup_InvalidateState(ctx, new_state);
- _vbo_InvalidateState(ctx, new_state);
- _tnl_InvalidateState(ctx, new_state);
-
- /* TODO - This code is not complete yet because I
- * don't know what to do for all state updates.
- */
-
- if (new_state & _NEW_BUFFERS) {
- }
-}
-
-
-
-
-
-/**********************************************************************/
-/***** WMESA Functions *****/
-/**********************************************************************/
-
-WMesaContext WMesaCreateContext(HDC hDC,
- HPALETTE* Pal,
- GLboolean rgb_flag,
- GLboolean db_flag,
- GLboolean alpha_flag)
-{
- WMesaContext c;
- struct dd_function_table functions;
- GLint red_bits, green_bits, blue_bits, alpha_bits;
- struct gl_context *ctx;
- struct gl_config *visual;
-
- (void) Pal;
-
- /* Indexed mode not supported */
- if (!rgb_flag)
- return NULL;
-
- /* Allocate wmesa context */
- c = CALLOC_STRUCT(wmesa_context);
- if (!c)
- return NULL;
-
-#if 0
- /* I do not understand this contributed code */
- /* Support memory and device contexts */
- if(WindowFromDC(hDC) != NULL) {
- c->hDC = GetDC(WindowFromDC(hDC)); /* huh ???? */
- }
- else {
- c->hDC = hDC;
- }
-#else
- c->hDC = hDC;
-#endif
-
- /* Get data for visual */
- /* Dealing with this is actually a bit of overkill because Mesa will end
- * up treating all color component size requests less than 8 by using
- * a single byte per channel. In addition, the interface to the span
- * routines passes colors as an entire byte per channel anyway, so there
- * is nothing to be saved by telling the visual to be 16 bits if the device
- * is 16 bits. That is, Mesa is going to compute colors down to 8 bits per
- * channel anyway.
- * But we go through the motions here anyway.
- */
- switch (GetDeviceCaps(c->hDC, BITSPIXEL)) {
- case 16:
- red_bits = green_bits = blue_bits = 5;
- alpha_bits = 0;
- break;
- default:
- red_bits = green_bits = blue_bits = 8;
- alpha_bits = 8;
- break;
- }
- /* Create visual based on flags */
- visual = _mesa_create_visual(db_flag, /* db_flag */
- GL_FALSE, /* stereo */
- red_bits, green_bits, blue_bits, /* color RGB */
- alpha_flag ? alpha_bits : 0, /* color A */
- DEFAULT_SOFTWARE_DEPTH_BITS, /* depth_bits */
- 8, /* stencil_bits */
- 16,16,16, /* accum RGB */
- alpha_flag ? 16 : 0, /* accum A */
- 1); /* num samples */
-
- if (!visual) {
- free(c);
- return NULL;
- }
-
- /* Set up driver functions */
- _mesa_init_driver_functions(&functions);
- functions.GetString = wmesa_get_string;
- functions.UpdateState = wmesa_update_state;
- functions.GetBufferSize = wmesa_get_buffer_size;
- functions.Flush = wmesa_flush;
- functions.Clear = clear;
- functions.ClearColor = clear_color;
- functions.ResizeBuffers = wmesa_resize_buffers;
- functions.Viewport = wmesa_viewport;
-
- /* initialize the Mesa context data */
- ctx = &c->gl_ctx;
- _mesa_initialize_context(ctx, API_OPENGL, visual,
- NULL, &functions, (void *)c);
-
- /* visual no longer needed - it was copied by _mesa_initialize_context() */
- _mesa_destroy_visual(visual);
-
- _mesa_enable_sw_extensions(ctx);
- _mesa_enable_1_3_extensions(ctx);
- _mesa_enable_1_4_extensions(ctx);
- _mesa_enable_1_5_extensions(ctx);
- _mesa_enable_2_0_extensions(ctx);
- _mesa_enable_2_1_extensions(ctx);
-
- _mesa_meta_init(ctx);
-
- /* Initialize the software rasterizer and helper modules. */
- if (!_swrast_CreateContext(ctx) ||
- !_vbo_CreateContext(ctx) ||
- !_tnl_CreateContext(ctx) ||
- !_swsetup_CreateContext(ctx)) {
- _mesa_free_context_data(ctx);
- free(c);
- return NULL;
- }
- _swsetup_Wakeup(ctx);
- TNL_CONTEXT(ctx)->Driver.RunPipeline = _tnl_run_pipeline;
-
- return c;
-}
-
-
-void WMesaDestroyContext( WMesaContext pwc )
-{
- struct gl_context *ctx = &pwc->gl_ctx;
- WMesaFramebuffer pwfb;
- GET_CURRENT_CONTEXT(cur_ctx);
-
- if (cur_ctx == ctx) {
- /* unbind current if deleting current context */
- WMesaMakeCurrent(NULL, NULL);
- }
-
- /* clean up frame buffer resources */
- pwfb = wmesa_lookup_framebuffer(pwc->hDC);
- if (pwfb) {
- if (ctx->Visual.doubleBufferMode == 1)
- wmDeleteBackingStore(pwfb);
- wmesa_free_framebuffer(pwc->hDC);
- }
-
- /* Release for device, not memory contexts */
- if (WindowFromDC(pwc->hDC) != NULL)
- {
- ReleaseDC(WindowFromDC(pwc->hDC), pwc->hDC);
- }
- DeleteObject(pwc->clearPen);
- DeleteObject(pwc->clearBrush);
-
- _mesa_meta_free(ctx);
-
- _swsetup_DestroyContext(ctx);
- _tnl_DestroyContext(ctx);
- _vbo_DestroyContext(ctx);
- _swrast_DestroyContext(ctx);
-
- _mesa_free_context_data(ctx);
- free(pwc);
-}
-
-
-/**
- * Create a new color renderbuffer.
- */
-struct gl_renderbuffer *
-wmesa_new_renderbuffer(void)
-{
- struct gl_renderbuffer *rb = CALLOC_STRUCT(gl_renderbuffer);
- if (!rb)
- return NULL;
-
- _mesa_init_renderbuffer(rb, (GLuint)0);
-
- rb->_BaseFormat = GL_RGBA;
- rb->InternalFormat = GL_RGBA;
- rb->DataType = CHAN_TYPE;
- rb->Delete = wmesa_delete_renderbuffer;
- rb->AllocStorage = wmesa_renderbuffer_storage;
- return rb;
-}
-
-
-void WMesaMakeCurrent(WMesaContext c, HDC hdc)
-{
- WMesaFramebuffer pwfb;
-
- {
- /* return if already current */
- GET_CURRENT_CONTEXT(ctx);
- WMesaContext pwc = wmesa_context(ctx);
- if (pwc && c == pwc && pwc->hDC == hdc)
- return;
- }
-
- pwfb = wmesa_lookup_framebuffer(hdc);
-
- /* Lazy creation of framebuffers */
- if (c && !pwfb && hdc) {
- struct gl_renderbuffer *rb;
- struct gl_config *visual = &c->gl_ctx.Visual;
- GLuint width, height;
-
- get_window_size(hdc, &width, &height);
-
- c->clearPen = CreatePen(PS_SOLID, 1, 0);
- c->clearBrush = CreateSolidBrush(0);
-
- pwfb = wmesa_new_framebuffer(hdc, visual);
-
- /* Create back buffer if double buffered */
- if (visual->doubleBufferMode == 1) {
- wmCreateBackingStore(pwfb, width, height);
- }
-
- /* make render buffers */
- if (visual->doubleBufferMode == 1) {
- rb = wmesa_new_renderbuffer();
- _mesa_add_renderbuffer(&pwfb->Base, BUFFER_BACK_LEFT, rb);
- wmesa_set_renderbuffer_funcs(rb, pwfb->pixelformat, pwfb->cColorBits, 1);
- }
- rb = wmesa_new_renderbuffer();
- _mesa_add_renderbuffer(&pwfb->Base, BUFFER_FRONT_LEFT, rb);
- wmesa_set_renderbuffer_funcs(rb, pwfb->pixelformat, pwfb->cColorBits, 0);
-
- /* Let Mesa own the Depth, Stencil, and Accum buffers */
- _mesa_add_soft_renderbuffers(&pwfb->Base,
- GL_FALSE, /* color */
- visual->depthBits > 0,
- visual->stencilBits > 0,
- visual->accumRedBits > 0,
- visual->alphaBits >0,
- GL_FALSE);
- }
-
- if (c && pwfb)
- _mesa_make_current(&c->gl_ctx, &pwfb->Base, &pwfb->Base);
- else
- _mesa_make_current(NULL, NULL, NULL);
-}
-
-
-void WMesaSwapBuffers( HDC hdc )
-{
- GET_CURRENT_CONTEXT(ctx);
- WMesaContext pwc = wmesa_context(ctx);
- WMesaFramebuffer pwfb = wmesa_lookup_framebuffer(hdc);
-
- if (!pwfb) {
- _mesa_problem(NULL, "wmesa: swapbuffers on unknown hdc");
- return;
- }
-
- /* If we're swapping the buffer associated with the current context
- * we have to flush any pending rendering commands first.
- */
- if (pwc->hDC == hdc) {
- _mesa_notifySwapBuffers(ctx);
-
- BitBlt(pwfb->hDC, 0, 0, pwfb->Base.Width, pwfb->Base.Height,
- pwfb->dib_hDC, 0, 0, SRCCOPY);
- }
- else {
- /* XXX for now only allow swapping current window */
- _mesa_problem(NULL, "wmesa: can't swap non-current window");
- }
-}
-
-void WMesaShareLists(WMesaContext ctx_to_share, WMesaContext ctx)
-{
- _mesa_share_state(&ctx->gl_ctx, &ctx_to_share->gl_ctx);
-}
-
+/*
+ * Windows (Win32/Win64) device driver for Mesa
+ *
+ */
+
+#include "wmesadef.h"
+#include "colors.h"
+#include <GL/wmesa.h>
+#include <winuser.h>
+#include "context.h"
+#include "extensions.h"
+#include "framebuffer.h"
+#include "renderbuffer.h"
+#include "drivers/common/driverfuncs.h"
+#include "drivers/common/meta.h"
+#include "vbo/vbo.h"
+#include "swrast/swrast.h"
+#include "swrast_setup/swrast_setup.h"
+#include "tnl/tnl.h"
+#include "tnl/t_context.h"
+#include "tnl/t_pipeline.h"
+
+
+/* linked list of our Framebuffers (windows) */
+static WMesaFramebuffer FirstFramebuffer = NULL;
+
+
+/**
+ * Create a new WMesaFramebuffer object which will correspond to the
+ * given HDC (Window handle).
+ */
+WMesaFramebuffer
+wmesa_new_framebuffer(HDC hdc, struct gl_config *visual)
+{
+ WMesaFramebuffer pwfb
+ = (WMesaFramebuffer) malloc(sizeof(struct wmesa_framebuffer));
+ if (pwfb) {
+ _mesa_initialize_window_framebuffer(&pwfb->Base, visual);
+ pwfb->hDC = hdc;
+ /* insert at head of list */
+ pwfb->next = FirstFramebuffer;
+ FirstFramebuffer = pwfb;
+ }
+ return pwfb;
+}
+
+/**
+ * Given an hdc, free the corresponding WMesaFramebuffer
+ */
+void
+wmesa_free_framebuffer(HDC hdc)
+{
+ WMesaFramebuffer pwfb, prev;
+ for (pwfb = FirstFramebuffer; pwfb; pwfb = pwfb->next) {
+ if (pwfb->hDC == hdc)
+ break;
+ prev = pwfb;
+ }
+ if (pwfb) {
+ struct gl_framebuffer *fb;
+ if (pwfb == FirstFramebuffer)
+ FirstFramebuffer = pwfb->next;
+ else
+ prev->next = pwfb->next;
+ fb = &pwfb->Base;
+ _mesa_reference_framebuffer(&fb, NULL);
+ }
+}
+
+/**
+ * Given an hdc, return the corresponding WMesaFramebuffer
+ */
+WMesaFramebuffer
+wmesa_lookup_framebuffer(HDC hdc)
+{
+ WMesaFramebuffer pwfb;
+ for (pwfb = FirstFramebuffer; pwfb; pwfb = pwfb->next) {
+ if (pwfb->hDC == hdc)
+ return pwfb;
+ }
+ return NULL;
+}
+
+
+/**
+ * Given a struct gl_framebuffer, return the corresponding WMesaFramebuffer.
+ */
+static WMesaFramebuffer wmesa_framebuffer(struct gl_framebuffer *fb)
+{
+ return (WMesaFramebuffer) fb;
+}
+
+
+/**
+ * Given a struct gl_context, return the corresponding WMesaContext.
+ */
+static WMesaContext wmesa_context(const struct gl_context *ctx)
+{
+ return (WMesaContext) ctx;
+}
+
+
+/*
+ * Every driver should implement a GetString function in order to
+ * return a meaningful GL_RENDERER string.
+ */
+static const GLubyte *wmesa_get_string(struct gl_context *ctx, GLenum name)
+{
+ return (name == GL_RENDERER) ?
+ (GLubyte *) "Mesa Windows GDI Driver" : NULL;
+}
+
+
+/*
+ * Determine the pixel format based on the pixel size.
+ */
+static void wmSetPixelFormat(WMesaFramebuffer pwfb, HDC hDC)
+{
+ pwfb->cColorBits = GetDeviceCaps(hDC, BITSPIXEL);
+
+ /* Only 16 and 32 bit targets are supported now */
+ assert(pwfb->cColorBits == 0 ||
+ pwfb->cColorBits == 16 ||
+ pwfb->cColorBits == 24 ||
+ pwfb->cColorBits == 32);
+
+ switch(pwfb->cColorBits){
+ case 8:
+ pwfb->pixelformat = PF_INDEX8;
+ break;
+ case 16:
+ pwfb->pixelformat = PF_5R6G5B;
+ break;
+ case 24:
+ case 32:
+ pwfb->pixelformat = PF_8R8G8B;
+ break;
+ default:
+ pwfb->pixelformat = PF_BADFORMAT;
+ }
+}
+
+
+/**
+ * Create DIB for back buffer.
+ * We write into this memory with the span routines and then blit it
+ * to the window on a buffer swap.
+ */
+BOOL wmCreateBackingStore(WMesaFramebuffer pwfb, long lxSize, long lySize)
+{
+ HDC hdc = pwfb->hDC;
+ LPBITMAPINFO pbmi = &(pwfb->bmi);
+ HDC hic;
+
+ pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ pbmi->bmiHeader.biWidth = lxSize;
+ pbmi->bmiHeader.biHeight= -lySize;
+ pbmi->bmiHeader.biPlanes = 1;
+ pbmi->bmiHeader.biBitCount = GetDeviceCaps(pwfb->hDC, BITSPIXEL);
+ pbmi->bmiHeader.biCompression = BI_RGB;
+ pbmi->bmiHeader.biSizeImage = 0;
+ pbmi->bmiHeader.biXPelsPerMeter = 0;
+ pbmi->bmiHeader.biYPelsPerMeter = 0;
+ pbmi->bmiHeader.biClrUsed = 0;
+ pbmi->bmiHeader.biClrImportant = 0;
+
+ pwfb->cColorBits = pbmi->bmiHeader.biBitCount;
+ pwfb->ScanWidth = (lxSize * (pwfb->cColorBits / 8) + 3) & ~3;
+
+ hic = CreateIC("display", NULL, NULL, NULL);
+ pwfb->dib_hDC = CreateCompatibleDC(hic);
+
+ pwfb->hbmDIB = CreateDIBSection(hic,
+ &pwfb->bmi,
+ DIB_RGB_COLORS,
+ (void **)&(pwfb->pbPixels),
+ 0,
+ 0);
+ pwfb->hOldBitmap = SelectObject(pwfb->dib_hDC, pwfb->hbmDIB);
+
+ DeleteDC(hic);
+
+ wmSetPixelFormat(pwfb, pwfb->hDC);
+ return TRUE;
+}
+
+
+static wmDeleteBackingStore(WMesaFramebuffer pwfb)
+{
+ if (pwfb->hbmDIB) {
+ SelectObject(pwfb->dib_hDC, pwfb->hOldBitmap);
+ DeleteDC(pwfb->dib_hDC);
+ DeleteObject(pwfb->hbmDIB);
+ }
+}
+
+
+/**
+ * Find the width and height of the window named by hdc.
+ */
+static void
+get_window_size(HDC hdc, GLuint *width, GLuint *height)
+{
+ if (WindowFromDC(hdc)) {
+ RECT rect;
+ GetClientRect(WindowFromDC(hdc), &rect);
+ *width = rect.right - rect.left;
+ *height = rect.bottom - rect.top;
+ }
+ else { /* Memory context */
+ /* From contributed code - use the size of the desktop
+ * for the size of a memory context (?) */
+ *width = GetDeviceCaps(hdc, HORZRES);
+ *height = GetDeviceCaps(hdc, VERTRES);
+ }
+}
+
+
+static void
+wmesa_get_buffer_size(struct gl_framebuffer *buffer, GLuint *width, GLuint *height)
+{
+ WMesaFramebuffer pwfb = wmesa_framebuffer(buffer);
+ get_window_size(pwfb->hDC, width, height);
+}
+
+
+static void wmesa_flush(struct gl_context *ctx)
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->WinSysDrawBuffer);
+
+ if (ctx->Visual.doubleBufferMode == 1) {
+ BitBlt(pwfb->hDC, 0, 0, pwfb->Base.Width, pwfb->Base.Height,
+ pwfb->dib_hDC, 0, 0, SRCCOPY);
+ }
+ else {
+ /* Do nothing for single buffer */
+ }
+}
+
+
+/**********************************************************************/
+/***** CLEAR Functions *****/
+/**********************************************************************/
+
+/* If we do not implement these, Mesa clears the buffers via the pixel
+ * span writing interface, which is very slow for a clear operation.
+ */
+
+/*
+ * Set the color used to clear the color buffer.
+ */
+static void clear_color(struct gl_context *ctx, const GLfloat color[4])
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLubyte col[3];
+ UINT bytesPerPixel = pwfb->cColorBits / 8;
+
+ CLAMPED_FLOAT_TO_UBYTE(col[0], color[0]);
+ CLAMPED_FLOAT_TO_UBYTE(col[1], color[1]);
+ CLAMPED_FLOAT_TO_UBYTE(col[2], color[2]);
+ pwc->clearColorRef = RGB(col[0], col[1], col[2]);
+ DeleteObject(pwc->clearPen);
+ DeleteObject(pwc->clearBrush);
+ pwc->clearPen = CreatePen(PS_SOLID, 1, pwc->clearColorRef);
+ pwc->clearBrush = CreateSolidBrush(pwc->clearColorRef);
+}
+
+
+/*
+ * Clear the specified region of the color buffer using the clear color
+ * or index as specified by one of the two functions above.
+ *
+ * This procedure clears either the front and/or the back COLOR buffers.
+ * Only the "left" buffer is cleared since we are not stereo.
+ * Clearing of the other non-color buffers is left to the swrast.
+ */
+
+static void clear(struct gl_context *ctx, GLbitfield mask)
+{
+#define FLIP(Y) (ctx->DrawBuffer->Height - (Y) - 1)
+ const GLint x = ctx->DrawBuffer->_Xmin;
+ const GLint y = ctx->DrawBuffer->_Ymin;
+ const GLint height = ctx->DrawBuffer->_Ymax - ctx->DrawBuffer->_Ymin;
+ const GLint width = ctx->DrawBuffer->_Xmax - ctx->DrawBuffer->_Xmin;
+
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ int done = 0;
+
+ /* Let swrast do all the work if the masks are not set to
+ * clear all channels. */
+ if (!ctx->Color.ColorMask[0][0] ||
+ !ctx->Color.ColorMask[0][1] ||
+ !ctx->Color.ColorMask[0][2] ||
+ !ctx->Color.ColorMask[0][3]) {
+ _swrast_Clear(ctx, mask);
+ return;
+ }
+
+ /* Back buffer */
+ if (mask & BUFFER_BIT_BACK_LEFT) {
+
+ int i, rowSize;
+ UINT bytesPerPixel = pwfb->cColorBits / 8;
+ LPBYTE lpb, clearRow;
+ LPWORD lpw;
+ BYTE bColor;
+ WORD wColor;
+ BYTE r, g, b;
+ DWORD dwColor;
+ LPDWORD lpdw;
+
+ /* Try for a fast clear - clearing entire buffer with a single
+ * byte value. */
+ if (width == ctx->DrawBuffer->Width &&
+ height == ctx->DrawBuffer->Height) { /* entire buffer */
+ /* Now check for an easy clear value */
+ switch (bytesPerPixel) {
+ case 1:
+ bColor = BGR8(GetRValue(pwc->clearColorRef),
+ GetGValue(pwc->clearColorRef),
+ GetBValue(pwc->clearColorRef));
+ memset(pwfb->pbPixels, bColor,
+ pwfb->ScanWidth * height);
+ done = 1;
+ break;
+ case 2:
+ wColor = BGR16(GetRValue(pwc->clearColorRef),
+ GetGValue(pwc->clearColorRef),
+ GetBValue(pwc->clearColorRef));
+ if (((wColor >> 8) & 0xff) == (wColor & 0xff)) {
+ memset(pwfb->pbPixels, wColor & 0xff,
+ pwfb->ScanWidth * height);
+ done = 1;
+ }
+ break;
+ case 3:
+ /* fall through */
+ case 4:
+ if (GetRValue(pwc->clearColorRef) ==
+ GetGValue(pwc->clearColorRef) &&
+ GetRValue(pwc->clearColorRef) ==
+ GetBValue(pwc->clearColorRef)) {
+ memset(pwfb->pbPixels,
+ GetRValue(pwc->clearColorRef),
+ pwfb->ScanWidth * height);
+ done = 1;
+ }
+ break;
+ default:
+ break;
+ }
+ } /* all */
+
+ if (!done) {
+ /* Need to clear a row at a time. Begin by setting the first
+ * row in the area to be cleared to the clear color. */
+
+ clearRow = pwfb->pbPixels +
+ pwfb->ScanWidth * FLIP(y) +
+ bytesPerPixel * x;
+ switch (bytesPerPixel) {
+ case 1:
+ lpb = clearRow;
+ bColor = BGR8(GetRValue(pwc->clearColorRef),
+ GetGValue(pwc->clearColorRef),
+ GetBValue(pwc->clearColorRef));
+ memset(lpb, bColor, width);
+ break;
+ case 2:
+ lpw = (LPWORD)clearRow;
+ wColor = BGR16(GetRValue(pwc->clearColorRef),
+ GetGValue(pwc->clearColorRef),
+ GetBValue(pwc->clearColorRef));
+ for (i=0; i<width; i++)
+ *lpw++ = wColor;
+ break;
+ case 3:
+ lpb = clearRow;
+ r = GetRValue(pwc->clearColorRef);
+ g = GetGValue(pwc->clearColorRef);
+ b = GetBValue(pwc->clearColorRef);
+ for (i=0; i<width; i++) {
+ *lpb++ = b;
+ *lpb++ = g;
+ *lpb++ = r;
+ }
+ break;
+ case 4:
+ lpdw = (LPDWORD)clearRow;
+ dwColor = BGR32(GetRValue(pwc->clearColorRef),
+ GetGValue(pwc->clearColorRef),
+ GetBValue(pwc->clearColorRef));
+ for (i=0; i<width; i++)
+ *lpdw++ = dwColor;
+ break;
+ default:
+ break;
+ } /* switch */
+
+ /* copy cleared row to other rows in buffer */
+ lpb = clearRow - pwfb->ScanWidth;
+ rowSize = width * bytesPerPixel;
+ for (i=1; i<height; i++) {
+ memcpy(lpb, clearRow, rowSize);
+ lpb -= pwfb->ScanWidth;
+ }
+ } /* not done */
+ mask &= ~BUFFER_BIT_BACK_LEFT;
+ } /* back buffer */
+
+ /* front buffer */
+ if (mask & BUFFER_BIT_FRONT_LEFT) {
+ HDC DC = pwc->hDC;
+ HPEN Old_Pen = SelectObject(DC, pwc->clearPen);
+ HBRUSH Old_Brush = SelectObject(DC, pwc->clearBrush);
+ Rectangle(DC,
+ x,
+ FLIP(y) + 1,
+ x + width + 1,
+ FLIP(y) - height + 1);
+ SelectObject(DC, Old_Pen);
+ SelectObject(DC, Old_Brush);
+ mask &= ~BUFFER_BIT_FRONT_LEFT;
+ } /* front buffer */
+
+ /* Call swrast if there is anything left to clear (like DEPTH) */
+ if (mask)
+ _swrast_Clear(ctx, mask);
+
+#undef FLIP
+}
+
+
+/**********************************************************************/
+/***** PIXEL Functions *****/
+/**********************************************************************/
+
+#define FLIP(Y) (rb->Height - (Y) - 1)
+
+
+/**
+ ** Front Buffer reading/writing
+ ** These are slow, but work with all non-indexed visual types.
+ **/
+
+/* Write a horizontal span of RGBA color pixels with a boolean mask. */
+static void write_rgba_span_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgba[][4],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_lookup_framebuffer(pwc->hDC);
+ CONST BITMAPINFO bmi=
+ {
+ {
+ sizeof(BITMAPINFOHEADER),
+ n, 1, 1, 32, BI_RGB, 0, 1, 1, 0, 0
+ }
+ };
+ HBITMAP bmp=0;
+ HDC mdc=0;
+ typedef union
+ {
+ unsigned i;
+ struct {
+ unsigned b:8, g:8, r:8, a:8;
+ };
+ } BGRA;
+ BGRA *bgra, c;
+ GLuint i;
+
+ if (n < 16) { // the value 16 is just guessed
+ y=FLIP(y);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ SetPixel(pwc->hDC, x+i, y,
+ RGB(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]));
+ }
+ else {
+ for (i=0; i<n; i++)
+ SetPixel(pwc->hDC, x+i, y,
+ RGB(rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]));
+ }
+ }
+ else {
+ if (!pwfb) {
+ _mesa_problem(NULL, "wmesa: write_rgba_span_front on unknown hdc");
+ return;
+ }
+ bgra=malloc(n*sizeof(BGRA));
+ if (!bgra) {
+ _mesa_problem(NULL, "wmesa: write_rgba_span_front: out of memory");
+ return;
+ }
+ c.a=0;
+ if (mask) {
+ for (i=0; i<n; i++) {
+ if (mask[i]) {
+ c.r=rgba[i][RCOMP];
+ c.g=rgba[i][GCOMP];
+ c.b=rgba[i][BCOMP];
+ c.a=rgba[i][ACOMP];
+ bgra[i]=c;
+ }
+ else
+ bgra[i].i=0;
+ }
+ }
+ else {
+ for (i=0; i<n; i++) {
+ c.r=rgba[i][RCOMP];
+ c.g=rgba[i][GCOMP];
+ c.b=rgba[i][BCOMP];
+ c.a=rgba[i][ACOMP];
+ bgra[i]=c;
+ }
+ }
+ bmp=CreateBitmap(n, 1, 1, 32, bgra);
+ mdc=CreateCompatibleDC(pwfb->hDC);
+ SelectObject(mdc, bmp);
+ y=FLIP(y);
+ BitBlt(pwfb->hDC, x, y, n, 1, mdc, 0, 0, SRCCOPY);
+ SelectObject(mdc, 0);
+ DeleteObject(bmp);
+ DeleteDC(mdc);
+ free(bgra);
+ }
+}
+
+/* Write a horizontal span of RGB color pixels with a boolean mask. */
+static void write_rgb_span_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgb[][3],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ GLuint i;
+
+ (void) ctx;
+ y=FLIP(y);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ SetPixel(pwc->hDC, x+i, y, RGB(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]));
+ }
+ else {
+ for (i=0; i<n; i++)
+ SetPixel(pwc->hDC, x+i, y, RGB(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]));
+ }
+
+}
+
+/*
+ * Write a horizontal span of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_span_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ COLORREF colorref;
+
+ (void) ctx;
+ colorref = RGB(color[RCOMP], color[GCOMP], color[BCOMP]);
+ y=FLIP(y);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ SetPixel(pwc->hDC, x+i, y, colorref);
+ }
+ else
+ for (i=0; i<n; i++)
+ SetPixel(pwc->hDC, x+i, y, colorref);
+
+}
+
+/* Write an array of RGBA pixels with a boolean mask. */
+static void write_rgba_pixels_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n,
+ const GLint x[], const GLint y[],
+ const GLubyte rgba[][4],
+ const GLubyte mask[] )
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ (void) ctx;
+ for (i=0; i<n; i++)
+ if (mask[i])
+ SetPixel(pwc->hDC, x[i], FLIP(y[i]),
+ RGB(rgba[i][RCOMP], rgba[i][GCOMP],
+ rgba[i][BCOMP]));
+}
+
+
+
+/*
+ * Write an array of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_pixels_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n,
+ const GLint x[], const GLint y[],
+ const GLchan color[4],
+ const GLubyte mask[] )
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ COLORREF colorref;
+ (void) ctx;
+ colorref = RGB(color[RCOMP], color[GCOMP], color[BCOMP]);
+ for (i=0; i<n; i++)
+ if (mask[i])
+ SetPixel(pwc->hDC, x[i], FLIP(y[i]), colorref);
+}
+
+/* Read a horizontal span of color pixels. */
+static void read_rgba_span_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ GLubyte rgba[][4] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ GLuint i;
+ COLORREF Color;
+ y = FLIP(y);
+ for (i=0; i<n; i++) {
+ Color = GetPixel(pwc->hDC, x+i, y);
+ rgba[i][RCOMP] = GetRValue(Color);
+ rgba[i][GCOMP] = GetGValue(Color);
+ rgba[i][BCOMP] = GetBValue(Color);
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/* Read an array of color pixels. */
+static void read_rgba_pixels_front(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ GLubyte rgba[][4])
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ GLuint i;
+ COLORREF Color;
+ for (i=0; i<n; i++) {
+ GLint y2 = FLIP(y[i]);
+ Color = GetPixel(pwc->hDC, x[i], y2);
+ rgba[i][RCOMP] = GetRValue(Color);
+ rgba[i][GCOMP] = GetGValue(Color);
+ rgba[i][BCOMP] = GetBValue(Color);
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+/*********************************************************************/
+
+/* DOUBLE BUFFER 32-bit */
+
+#define WMSETPIXEL32(pwc, y, x, r, g, b) { \
+LPDWORD lpdw = ((LPDWORD)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (x)); \
+*lpdw = BGR32((r),(g),(b)); }
+
+
+
+/* Write a horizontal span of RGBA color pixels with a boolean mask. */
+static void write_rgba_span_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgba[][4],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPDWORD lpdw;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpdw[i] = BGR32(rgba[i][RCOMP], rgba[i][GCOMP],
+ rgba[i][BCOMP]);
+ }
+ else {
+ for (i=0; i<n; i++)
+ *lpdw++ = BGR32(rgba[i][RCOMP], rgba[i][GCOMP],
+ rgba[i][BCOMP]);
+ }
+}
+
+
+/* Write a horizontal span of RGB color pixels with a boolean mask. */
+static void write_rgb_span_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgb[][3],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPDWORD lpdw;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpdw[i] = BGR32(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]);
+ }
+ else {
+ for (i=0; i<n; i++)
+ *lpdw++ = BGR32(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]);
+ }
+}
+
+/*
+ * Write a horizontal span of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_span_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ LPDWORD lpdw;
+ DWORD pixel;
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ y=FLIP(y);
+ pixel = BGR32(color[RCOMP], color[GCOMP], color[BCOMP]);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpdw[i] = pixel;
+ }
+ else
+ for (i=0; i<n; i++)
+ *lpdw++ = pixel;
+
+}
+
+/* Write an array of RGBA pixels with a boolean mask. */
+static void write_rgba_pixels_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ const GLubyte rgba[][4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL32(pwfb, FLIP(y[i]), x[i],
+ rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
+}
+
+/*
+ * Write an array of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_pixels_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n,
+ const GLint x[], const GLint y[],
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL32(pwfb, FLIP(y[i]),x[i],color[RCOMP],
+ color[GCOMP], color[BCOMP]);
+}
+
+/* Read a horizontal span of color pixels. */
+static void read_rgba_span_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ GLubyte rgba[][4] )
+{
+ GLuint i;
+ DWORD pixel;
+ LPDWORD lpdw;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ y = FLIP(y);
+ lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ for (i=0; i<n; i++) {
+ pixel = lpdw[i];
+ rgba[i][RCOMP] = (GLubyte)((pixel & 0x00ff0000) >> 16);
+ rgba[i][GCOMP] = (GLubyte)((pixel & 0x0000ff00) >> 8);
+ rgba[i][BCOMP] = (GLubyte)(pixel & 0x000000ff);
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/* Read an array of color pixels. */
+static void read_rgba_pixels_32(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ GLubyte rgba[][4])
+{
+ GLuint i;
+ DWORD pixel;
+ LPDWORD lpdw;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ for (i=0; i<n; i++) {
+ GLint y2 = FLIP(y[i]);
+ lpdw = ((LPDWORD)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + x[i];
+ pixel = *lpdw;
+ rgba[i][RCOMP] = (GLubyte)((pixel & 0x00ff0000) >> 16);
+ rgba[i][GCOMP] = (GLubyte)((pixel & 0x0000ff00) >> 8);
+ rgba[i][BCOMP] = (GLubyte)(pixel & 0x000000ff);
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/*********************************************************************/
+
+/* DOUBLE BUFFER 24-bit */
+
+#define WMSETPIXEL24(pwc, y, x, r, g, b) { \
+LPBYTE lpb = ((LPBYTE)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (3 * x)); \
+lpb[0] = (b); \
+lpb[1] = (g); \
+lpb[2] = (r); }
+
+/* Write a horizontal span of RGBA color pixels with a boolean mask. */
+static void write_rgba_span_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgba[][4],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPBYTE lpb;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i]) {
+ lpb[3*i] = rgba[i][BCOMP];
+ lpb[3*i+1] = rgba[i][GCOMP];
+ lpb[3*i+2] = rgba[i][RCOMP];
+ }
+ }
+ else {
+ for (i=0; i<n; i++) {
+ *lpb++ = rgba[i][BCOMP];
+ *lpb++ = rgba[i][GCOMP];
+ *lpb++ = rgba[i][RCOMP];
+ }
+ }
+}
+
+
+/* Write a horizontal span of RGB color pixels with a boolean mask. */
+static void write_rgb_span_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgb[][3],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPBYTE lpb;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i]) {
+ lpb[3*i] = rgb[i][BCOMP];
+ lpb[3*i+1] = rgb[i][GCOMP];
+ lpb[3*i+2] = rgb[i][RCOMP];
+ }
+ }
+ else {
+ for (i=0; i<n; i++) {
+ *lpb++ = rgb[i][BCOMP];
+ *lpb++ = rgb[i][GCOMP];
+ *lpb++ = rgb[i][RCOMP];
+ }
+ }
+}
+
+/*
+ * Write a horizontal span of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_span_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ LPBYTE lpb;
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
+ y=FLIP(y);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i]) {
+ lpb[3*i] = color[BCOMP];
+ lpb[3*i+1] = color[GCOMP];
+ lpb[3*i+2] = color[RCOMP];
+ }
+ }
+ else
+ for (i=0; i<n; i++) {
+ *lpb++ = color[BCOMP];
+ *lpb++ = color[GCOMP];
+ *lpb++ = color[RCOMP];
+ }
+}
+
+/* Write an array of RGBA pixels with a boolean mask. */
+static void write_rgba_pixels_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ const GLubyte rgba[][4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL24(pwfb, FLIP(y[i]), x[i],
+ rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
+}
+
+/*
+ * Write an array of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_pixels_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n,
+ const GLint x[], const GLint y[],
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL24(pwfb, FLIP(y[i]),x[i],color[RCOMP],
+ color[GCOMP], color[BCOMP]);
+}
+
+/* Read a horizontal span of color pixels. */
+static void read_rgba_span_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ GLubyte rgba[][4] )
+{
+ GLuint i;
+ LPBYTE lpb;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ y = FLIP(y);
+ lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y)) + (3 * x);
+ for (i=0; i<n; i++) {
+ rgba[i][RCOMP] = lpb[3*i+2];
+ rgba[i][GCOMP] = lpb[3*i+1];
+ rgba[i][BCOMP] = lpb[3*i];
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/* Read an array of color pixels. */
+static void read_rgba_pixels_24(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ GLubyte rgba[][4])
+{
+ GLuint i;
+ LPBYTE lpb;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ for (i=0; i<n; i++) {
+ GLint y2 = FLIP(y[i]);
+ lpb = ((LPBYTE)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + (3 * x[i]);
+ rgba[i][RCOMP] = lpb[3*i+2];
+ rgba[i][GCOMP] = lpb[3*i+1];
+ rgba[i][BCOMP] = lpb[3*i];
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/*********************************************************************/
+
+/* DOUBLE BUFFER 16-bit */
+
+#define WMSETPIXEL16(pwc, y, x, r, g, b) { \
+LPWORD lpw = ((LPWORD)((pwc)->pbPixels + (pwc)->ScanWidth * (y)) + (x)); \
+*lpw = BGR16((r),(g),(b)); }
+
+
+
+/* Write a horizontal span of RGBA color pixels with a boolean mask. */
+static void write_rgba_span_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgba[][4],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPWORD lpw;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpw[i] = BGR16(rgba[i][RCOMP], rgba[i][GCOMP],
+ rgba[i][BCOMP]);
+ }
+ else {
+ for (i=0; i<n; i++)
+ *lpw++ = BGR16(rgba[i][RCOMP], rgba[i][GCOMP],
+ rgba[i][BCOMP]);
+ }
+}
+
+
+/* Write a horizontal span of RGB color pixels with a boolean mask. */
+static void write_rgb_span_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLubyte rgb[][3],
+ const GLubyte mask[] )
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ GLuint i;
+ LPWORD lpw;
+
+ (void) ctx;
+
+ y=FLIP(y);
+ lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpw[i] = BGR16(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]);
+ }
+ else {
+ for (i=0; i<n; i++)
+ *lpw++ = BGR16(rgb[i][RCOMP], rgb[i][GCOMP],
+ rgb[i][BCOMP]);
+ }
+}
+
+/*
+ * Write a horizontal span of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_span_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ LPWORD lpw;
+ WORD pixel;
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ (void) ctx;
+ lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ y=FLIP(y);
+ pixel = BGR16(color[RCOMP], color[GCOMP], color[BCOMP]);
+ if (mask) {
+ for (i=0; i<n; i++)
+ if (mask[i])
+ lpw[i] = pixel;
+ }
+ else
+ for (i=0; i<n; i++)
+ *lpw++ = pixel;
+
+}
+
+/* Write an array of RGBA pixels with a boolean mask. */
+static void write_rgba_pixels_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ const GLubyte rgba[][4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ (void) ctx;
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL16(pwfb, FLIP(y[i]), x[i],
+ rgba[i][RCOMP], rgba[i][GCOMP], rgba[i][BCOMP]);
+}
+
+/*
+ * Write an array of pixels with a boolean mask. The current color
+ * is used for all pixels.
+ */
+static void write_mono_rgba_pixels_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n,
+ const GLint x[], const GLint y[],
+ const GLchan color[4],
+ const GLubyte mask[])
+{
+ GLuint i;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+ (void) ctx;
+ for (i=0; i<n; i++)
+ if (mask[i])
+ WMSETPIXEL16(pwfb, FLIP(y[i]),x[i],color[RCOMP],
+ color[GCOMP], color[BCOMP]);
+}
+
+/* Read a horizontal span of color pixels. */
+static void read_rgba_span_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, GLint x, GLint y,
+ GLubyte rgba[][4] )
+{
+ GLuint i, pixel;
+ LPWORD lpw;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ y = FLIP(y);
+ lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y)) + x;
+ for (i=0; i<n; i++) {
+ pixel = lpw[i];
+ /* Windows uses 5,5,5 for 16-bit */
+ rgba[i][RCOMP] = (pixel & 0x7c00) >> 7;
+ rgba[i][GCOMP] = (pixel & 0x03e0) >> 2;
+ rgba[i][BCOMP] = (pixel & 0x001f) << 3;
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+/* Read an array of color pixels. */
+static void read_rgba_pixels_16(const struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLuint n, const GLint x[], const GLint y[],
+ GLubyte rgba[][4])
+{
+ GLuint i, pixel;
+ LPWORD lpw;
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(ctx->DrawBuffer);
+
+ for (i=0; i<n; i++) {
+ GLint y2 = FLIP(y[i]);
+ lpw = ((LPWORD)(pwfb->pbPixels + pwfb->ScanWidth * y2)) + x[i];
+ pixel = *lpw;
+ /* Windows uses 5,5,5 for 16-bit */
+ rgba[i][RCOMP] = (pixel & 0x7c00) >> 7;
+ rgba[i][GCOMP] = (pixel & 0x03e0) >> 2;
+ rgba[i][BCOMP] = (pixel & 0x001f) << 3;
+ rgba[i][ACOMP] = 255;
+ }
+}
+
+
+
+
+/**********************************************************************/
+/***** BUFFER Functions *****/
+/**********************************************************************/
+
+
+
+
+static void
+wmesa_delete_renderbuffer(struct gl_renderbuffer *rb)
+{
+ free(rb);
+}
+
+
+/**
+ * This is called by Mesa whenever it determines that the window size
+ * has changed. Do whatever's needed to cope with that.
+ */
+static GLboolean
+wmesa_renderbuffer_storage(struct gl_context *ctx,
+ struct gl_renderbuffer *rb,
+ GLenum internalFormat,
+ GLuint width,
+ GLuint height)
+{
+ rb->Width = width;
+ rb->Height = height;
+ return GL_TRUE;
+}
+
+
+/**
+ * Plug in the Get/PutRow/Values functions for a renderbuffer depending
+ * on if we're drawing to the front or back color buffer.
+ */
+void wmesa_set_renderbuffer_funcs(struct gl_renderbuffer *rb, int pixelformat,
+ int cColorBits, int double_buffer)
+{
+ if (double_buffer) {
+ /* back buffer */
+ /* Picking the correct span functions is important because
+ * the DIB was allocated with the indicated depth. */
+ switch(pixelformat) {
+ case PF_5R6G5B:
+ rb->PutRow = write_rgba_span_16;
+ rb->PutRowRGB = write_rgb_span_16;
+ rb->PutMonoRow = write_mono_rgba_span_16;
+ rb->PutValues = write_rgba_pixels_16;
+ rb->PutMonoValues = write_mono_rgba_pixels_16;
+ rb->GetRow = read_rgba_span_16;
+ rb->GetValues = read_rgba_pixels_16;
+ break;
+ case PF_8R8G8B:
+ if (cColorBits == 24)
+ {
+ rb->PutRow = write_rgba_span_24;
+ rb->PutRowRGB = write_rgb_span_24;
+ rb->PutMonoRow = write_mono_rgba_span_24;
+ rb->PutValues = write_rgba_pixels_24;
+ rb->PutMonoValues = write_mono_rgba_pixels_24;
+ rb->GetRow = read_rgba_span_24;
+ rb->GetValues = read_rgba_pixels_24;
+ }
+ else
+ {
+ rb->PutRow = write_rgba_span_32;
+ rb->PutRowRGB = write_rgb_span_32;
+ rb->PutMonoRow = write_mono_rgba_span_32;
+ rb->PutValues = write_rgba_pixels_32;
+ rb->PutMonoValues = write_mono_rgba_pixels_32;
+ rb->GetRow = read_rgba_span_32;
+ rb->GetValues = read_rgba_pixels_32;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ else {
+ /* front buffer (actual Windows window) */
+ rb->PutRow = write_rgba_span_front;
+ rb->PutRowRGB = write_rgb_span_front;
+ rb->PutMonoRow = write_mono_rgba_span_front;
+ rb->PutValues = write_rgba_pixels_front;
+ rb->PutMonoValues = write_mono_rgba_pixels_front;
+ rb->GetRow = read_rgba_span_front;
+ rb->GetValues = read_rgba_pixels_front;
+ }
+}
+
+/**
+ * Called by ctx->Driver.ResizeBuffers()
+ * Resize the front/back colorbuffers to match the latest window size.
+ */
+static void
+wmesa_resize_buffers(struct gl_context *ctx, struct gl_framebuffer *buffer,
+ GLuint width, GLuint height)
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_framebuffer(buffer);
+
+ if (pwfb->Base.Width != width || pwfb->Base.Height != height) {
+ /* Realloc back buffer */
+ if (ctx->Visual.doubleBufferMode == 1) {
+ wmDeleteBackingStore(pwfb);
+ wmCreateBackingStore(pwfb, width, height);
+ }
+ }
+ _mesa_resize_framebuffer(ctx, buffer, width, height);
+}
+
+
+/**
+ * Called by glViewport.
+ * This is a good time for us to poll the current window size and adjust
+ * our renderbuffers to match the current window size.
+ * Remember, we have no opportunity to respond to conventional
+ * resize events since the driver has no event loop.
+ * Thus, we poll.
+ * MakeCurrent also ends up making a call here, so that ensures
+ * we get the viewport set correctly, even if the app does not call
+ * glViewport and relies on the defaults.
+ */
+static void wmesa_viewport(struct gl_context *ctx,
+ GLint x, GLint y,
+ GLsizei width, GLsizei height)
+{
+ WMesaContext pwc = wmesa_context(ctx);
+ GLuint new_width, new_height;
+
+ wmesa_get_buffer_size(ctx->WinSysDrawBuffer, &new_width, &new_height);
+
+ /**
+ * Resize buffers if the window size changed.
+ */
+ wmesa_resize_buffers(ctx, ctx->WinSysDrawBuffer, new_width, new_height);
+ ctx->NewState |= _NEW_BUFFERS; /* to update scissor / window bounds */
+}
+
+
+
+
+/**
+ * Called when the driver should update it's state, based on the new_state
+ * flags.
+ */
+static void wmesa_update_state(struct gl_context *ctx, GLuint new_state)
+{
+ _swrast_InvalidateState(ctx, new_state);
+ _swsetup_InvalidateState(ctx, new_state);
+ _vbo_InvalidateState(ctx, new_state);
+ _tnl_InvalidateState(ctx, new_state);
+
+ /* TODO - This code is not complete yet because I
+ * don't know what to do for all state updates.
+ */
+
+ if (new_state & _NEW_BUFFERS) {
+ }
+}
+
+
+
+
+
+/**********************************************************************/
+/***** WMESA Functions *****/
+/**********************************************************************/
+
+WMesaContext WMesaCreateContext(HDC hDC,
+ HPALETTE* Pal,
+ GLboolean rgb_flag,
+ GLboolean db_flag,
+ GLboolean alpha_flag)
+{
+ WMesaContext c;
+ struct dd_function_table functions;
+ GLint red_bits, green_bits, blue_bits, alpha_bits;
+ struct gl_context *ctx;
+ struct gl_config *visual;
+
+ (void) Pal;
+
+ /* Indexed mode not supported */
+ if (!rgb_flag)
+ return NULL;
+
+ /* Allocate wmesa context */
+ c = CALLOC_STRUCT(wmesa_context);
+ if (!c)
+ return NULL;
+
+#if 0
+ /* I do not understand this contributed code */
+ /* Support memory and device contexts */
+ if(WindowFromDC(hDC) != NULL) {
+ c->hDC = GetDC(WindowFromDC(hDC)); /* huh ???? */
+ }
+ else {
+ c->hDC = hDC;
+ }
+#else
+ c->hDC = hDC;
+#endif
+
+ /* Get data for visual */
+ /* Dealing with this is actually a bit of overkill because Mesa will end
+ * up treating all color component size requests less than 8 by using
+ * a single byte per channel. In addition, the interface to the span
+ * routines passes colors as an entire byte per channel anyway, so there
+ * is nothing to be saved by telling the visual to be 16 bits if the device
+ * is 16 bits. That is, Mesa is going to compute colors down to 8 bits per
+ * channel anyway.
+ * But we go through the motions here anyway.
+ */
+ switch (GetDeviceCaps(c->hDC, BITSPIXEL)) {
+ case 16:
+ red_bits = green_bits = blue_bits = 5;
+ alpha_bits = 0;
+ break;
+ default:
+ red_bits = green_bits = blue_bits = 8;
+ alpha_bits = 8;
+ break;
+ }
+ /* Create visual based on flags */
+ visual = _mesa_create_visual(db_flag, /* db_flag */
+ GL_FALSE, /* stereo */
+ red_bits, green_bits, blue_bits, /* color RGB */
+ alpha_flag ? alpha_bits : 0, /* color A */
+ DEFAULT_SOFTWARE_DEPTH_BITS, /* depth_bits */
+ 8, /* stencil_bits */
+ 16,16,16, /* accum RGB */
+ alpha_flag ? 16 : 0, /* accum A */
+ 1); /* num samples */
+
+ if (!visual) {
+ free(c);
+ return NULL;
+ }
+
+ /* Set up driver functions */
+ _mesa_init_driver_functions(&functions);
+ functions.GetString = wmesa_get_string;
+ functions.UpdateState = wmesa_update_state;
+ functions.GetBufferSize = wmesa_get_buffer_size;
+ functions.Flush = wmesa_flush;
+ functions.Clear = clear;
+ functions.ClearColor = clear_color;
+ functions.ResizeBuffers = wmesa_resize_buffers;
+ functions.Viewport = wmesa_viewport;
+
+ /* initialize the Mesa context data */
+ ctx = &c->gl_ctx;
+ _mesa_initialize_context(ctx, API_OPENGL, visual,
+ NULL, &functions, (void *)c);
+
+ /* visual no longer needed - it was copied by _mesa_initialize_context() */
+ _mesa_destroy_visual(visual);
+
+ _mesa_enable_sw_extensions(ctx);
+ _mesa_enable_1_3_extensions(ctx);
+ _mesa_enable_1_4_extensions(ctx);
+ _mesa_enable_1_5_extensions(ctx);
+ _mesa_enable_2_0_extensions(ctx);
+ _mesa_enable_2_1_extensions(ctx);
+
+ _mesa_meta_init(ctx);
+
+ /* Initialize the software rasterizer and helper modules. */
+ if (!_swrast_CreateContext(ctx) ||
+ !_vbo_CreateContext(ctx) ||
+ !_tnl_CreateContext(ctx) ||
+ !_swsetup_CreateContext(ctx)) {
+ _mesa_free_context_data(ctx);
+ free(c);
+ return NULL;
+ }
+ _swsetup_Wakeup(ctx);
+ TNL_CONTEXT(ctx)->Driver.RunPipeline = _tnl_run_pipeline;
+
+ return c;
+}
+
+
+void WMesaDestroyContext( WMesaContext pwc )
+{
+ struct gl_context *ctx = &pwc->gl_ctx;
+ WMesaFramebuffer pwfb;
+ GET_CURRENT_CONTEXT(cur_ctx);
+
+ if (cur_ctx == ctx) {
+ /* unbind current if deleting current context */
+ WMesaMakeCurrent(NULL, NULL);
+ }
+
+ /* clean up frame buffer resources */
+ pwfb = wmesa_lookup_framebuffer(pwc->hDC);
+ if (pwfb) {
+ if (ctx->Visual.doubleBufferMode == 1)
+ wmDeleteBackingStore(pwfb);
+ wmesa_free_framebuffer(pwc->hDC);
+ }
+
+ /* Release for device, not memory contexts */
+ if (WindowFromDC(pwc->hDC) != NULL)
+ {
+ ReleaseDC(WindowFromDC(pwc->hDC), pwc->hDC);
+ }
+ DeleteObject(pwc->clearPen);
+ DeleteObject(pwc->clearBrush);
+
+ _mesa_meta_free(ctx);
+
+ _swsetup_DestroyContext(ctx);
+ _tnl_DestroyContext(ctx);
+ _vbo_DestroyContext(ctx);
+ _swrast_DestroyContext(ctx);
+
+ _mesa_free_context_data(ctx);
+ free(pwc);
+}
+
+
+/**
+ * Create a new color renderbuffer.
+ */
+struct gl_renderbuffer *
+wmesa_new_renderbuffer(void)
+{
+ struct gl_renderbuffer *rb = CALLOC_STRUCT(gl_renderbuffer);
+ if (!rb)
+ return NULL;
+
+ _mesa_init_renderbuffer(rb, (GLuint)0);
+
+ rb->_BaseFormat = GL_RGBA;
+ rb->InternalFormat = GL_RGBA;
+ rb->DataType = CHAN_TYPE;
+ rb->Delete = wmesa_delete_renderbuffer;
+ rb->AllocStorage = wmesa_renderbuffer_storage;
+ return rb;
+}
+
+
+void WMesaMakeCurrent(WMesaContext c, HDC hdc)
+{
+ WMesaFramebuffer pwfb;
+
+ {
+ /* return if already current */
+ GET_CURRENT_CONTEXT(ctx);
+ WMesaContext pwc = wmesa_context(ctx);
+ if (pwc && c == pwc && pwc->hDC == hdc)
+ return;
+ }
+
+ pwfb = wmesa_lookup_framebuffer(hdc);
+
+ /* Lazy creation of framebuffers */
+ if (c && !pwfb && hdc) {
+ struct gl_renderbuffer *rb;
+ struct gl_config *visual = &c->gl_ctx.Visual;
+ GLuint width, height;
+
+ get_window_size(hdc, &width, &height);
+
+ c->clearPen = CreatePen(PS_SOLID, 1, 0);
+ c->clearBrush = CreateSolidBrush(0);
+
+ pwfb = wmesa_new_framebuffer(hdc, visual);
+
+ /* Create back buffer if double buffered */
+ if (visual->doubleBufferMode == 1) {
+ wmCreateBackingStore(pwfb, width, height);
+ }
+
+ /* make render buffers */
+ if (visual->doubleBufferMode == 1) {
+ rb = wmesa_new_renderbuffer();
+ _mesa_add_renderbuffer(&pwfb->Base, BUFFER_BACK_LEFT, rb);
+ wmesa_set_renderbuffer_funcs(rb, pwfb->pixelformat, pwfb->cColorBits, 1);
+ }
+ rb = wmesa_new_renderbuffer();
+ _mesa_add_renderbuffer(&pwfb->Base, BUFFER_FRONT_LEFT, rb);
+ wmesa_set_renderbuffer_funcs(rb, pwfb->pixelformat, pwfb->cColorBits, 0);
+
+ /* Let Mesa own the Depth, Stencil, and Accum buffers */
+ _mesa_add_soft_renderbuffers(&pwfb->Base,
+ GL_FALSE, /* color */
+ visual->depthBits > 0,
+ visual->stencilBits > 0,
+ visual->accumRedBits > 0,
+ visual->alphaBits >0,
+ GL_FALSE);
+ }
+
+ if (c && pwfb)
+ _mesa_make_current(&c->gl_ctx, &pwfb->Base, &pwfb->Base);
+ else
+ _mesa_make_current(NULL, NULL, NULL);
+}
+
+
+void WMesaSwapBuffers( HDC hdc )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ WMesaContext pwc = wmesa_context(ctx);
+ WMesaFramebuffer pwfb = wmesa_lookup_framebuffer(hdc);
+
+ if (!pwfb) {
+ _mesa_problem(NULL, "wmesa: swapbuffers on unknown hdc");
+ return;
+ }
+
+ /* If we're swapping the buffer associated with the current context
+ * we have to flush any pending rendering commands first.
+ */
+ if (pwc->hDC == hdc) {
+ _mesa_notifySwapBuffers(ctx);
+
+ BitBlt(pwfb->hDC, 0, 0, pwfb->Base.Width, pwfb->Base.Height,
+ pwfb->dib_hDC, 0, 0, SRCCOPY);
+ }
+ else {
+ /* XXX for now only allow swapping current window */
+ _mesa_problem(NULL, "wmesa: can't swap non-current window");
+ }
+}
+
+void WMesaShareLists(WMesaContext ctx_to_share, WMesaContext ctx)
+{
+ _mesa_share_state(&ctx->gl_ctx, &ctx_to_share->gl_ctx);
+}
+
diff --git a/mesalib/src/mesa/drivers/windows/gldirect/dglcontext.c b/mesalib/src/mesa/drivers/windows/gldirect/dglcontext.c
index 9aedd2e3c..bc4839cfe 100644
--- a/mesalib/src/mesa/drivers/windows/gldirect/dglcontext.c
+++ b/mesalib/src/mesa/drivers/windows/gldirect/dglcontext.c
@@ -1,2212 +1,2212 @@
-/****************************************************************************
-*
-* Mesa 3-D graphics library
-* Direct3D Driver Interface
-*
-* ========================================================================
-*
-* Copyright (C) 1991-2004 SciTech Software, Inc. 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
-* SCITECH SOFTWARE INC 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.
-*
-* ======================================================================
-*
-* Language: ANSI C
-* Environment: Windows 9x (Win32)
-*
-* Description: Context handling.
-*
-****************************************************************************/
-
-#include "dglcontext.h"
-
-// Get compile errors without this. KeithH
-//#include "scitech.h" // ibool, etc.
-
-#ifdef _USE_GLD3_WGL
-#include "gld_driver.h"
-
-extern void _gld_mesa_warning(struct gl_context *, char *);
-extern void _gld_mesa_fatal(struct gl_context *, char *);
-#endif // _USE_GLD3_WGL
-
-// TODO: Clean out old DX6-specific code from GLD 2.x CAD driver
-// if it is no longer being built as part of GLDirect. (DaveM)
-
-// ***********************************************************************
-
-#define GLDERR_NONE 0
-#define GLDERR_MEM 1
-#define GLDERR_DDRAW 2
-#define GLDERR_D3D 3
-#define GLDERR_BPP 4
-
-char szResourceWarning[] =
-"GLDirect does not have enough video memory resources\n"
-"to support the requested OpenGL rendering context.\n\n"
-"You may have to reduce the current display resolution\n"
-"to obtain satisfactory OpenGL performance.\n";
-
-char szDDrawWarning[] =
-"GLDirect is unable to initialize DirectDraw for the\n"
-"requested OpenGL rendering context.\n\n"
-"You will have to check the DirectX control panel\n"
-"for further information.\n";
-
-char szD3DWarning[] =
-"GLDirect is unable to initialize Direct3D for the\n"
-"requested OpenGL rendering context.\n\n"
-"You may have to change the display mode resolution\n"
-"color depth or check the DirectX control panel for\n"
-"further information.\n";
-
-char szBPPWarning[] =
-"GLDirect is unable to use the selected color depth for\n"
-"the requested OpenGL rendering context.\n\n"
-"You will have to change the display mode resolution\n"
-"color depth with the Display Settings control panel.\n";
-
-int nContextError = GLDERR_NONE;
-
-// ***********************************************************************
-
-#define VENDORID_ATI 0x1002
-
-static DWORD devATIRagePro[] = {
- 0x4742, // 3D RAGE PRO BGA AGP 1X/2X
- 0x4744, // 3D RAGE PRO BGA AGP 1X only
- 0x4749, // 3D RAGE PRO BGA PCI 33 MHz
- 0x4750, // 3D RAGE PRO PQFP PCI 33 MHz
- 0x4751, // 3D RAGE PRO PQFP PCI 33 MHz limited 3D
- 0x4C42, // 3D RAGE LT PRO BGA-312 AGP 133 MHz
- 0x4C44, // 3D RAGE LT PRO BGA-312 AGP 66 MHz
- 0x4C49, // 3D RAGE LT PRO BGA-312 PCI 33 MHz
- 0x4C50, // 3D RAGE LT PRO BGA-256 PCI 33 MHz
- 0x4C51, // 3D RAGE LT PRO BGA-256 PCI 33 MHz limited 3D
-};
-
-static DWORD devATIRageIIplus[] = {
- 0x4755, // 3D RAGE II+
- 0x4756, // 3D RAGE IIC PQFP PCI
- 0x4757, // 3D RAGE IIC BGA AGP
- 0x475A, // 3D RAGE IIC PQFP AGP
- 0x4C47, // 3D RAGE LT-G
-};
-
-// ***********************************************************************
-
-#ifndef _USE_GLD3_WGL
-extern DGL_mesaFuncs mesaFuncs;
-#endif
-
-extern DWORD dwLogging;
-
-#ifdef GLD_THREADS
-#pragma message("compiling DGLCONTEXT.C vars for multi-threaded support")
-CRITICAL_SECTION CriticalSection; // for serialized access
-DWORD dwTLSCurrentContext = 0xFFFFFFFF; // TLS index for current context
-DWORD dwTLSPixelFormat = 0xFFFFFFFF; // TLS index for current pixel format
-#endif
-HGLRC iCurrentContext = 0; // Index of current context (static)
-BOOL bContextReady = FALSE; // Context state ready ?
-
-DGL_ctx ctxlist[DGL_MAX_CONTEXTS]; // Context list
-
-// ***********************************************************************
-
-static BOOL bHaveWin95 = FALSE;
-static BOOL bHaveWinNT = FALSE;
-static BOOL bHaveWin2K = FALSE;
-
-/****************************************************************************
-REMARKS:
-Detect the installed OS type.
-****************************************************************************/
-static void DetectOS(void)
-{
- OSVERSIONINFO VersionInformation;
- LPOSVERSIONINFO lpVersionInformation = &VersionInformation;
-
- VersionInformation.dwOSVersionInfoSize = sizeof(VersionInformation);
-
- GetVersionEx(lpVersionInformation);
-
- switch (VersionInformation.dwPlatformId) {
- case VER_PLATFORM_WIN32_WINDOWS:
- bHaveWin95 = TRUE;
- bHaveWinNT = FALSE;
- bHaveWin2K = FALSE;
- break;
- case VER_PLATFORM_WIN32_NT:
- bHaveWin95 = FALSE;
- if (VersionInformation.dwMajorVersion <= 4) {
- bHaveWinNT = TRUE;
- bHaveWin2K = FALSE;
- }
- else {
- bHaveWinNT = FALSE;
- bHaveWin2K = TRUE;
- }
- break;
- case VER_PLATFORM_WIN32s:
- bHaveWin95 = FALSE;
- bHaveWinNT = FALSE;
- bHaveWin2K = FALSE;
- break;
- }
-}
-
-// ***********************************************************************
-
-HWND hWndEvent = NULL; // event monitor window
-HWND hWndLastActive = NULL; // last active client window
-LONG __stdcall GLD_EventWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
-
-// ***********************************************************************
-
-// Checks if the HGLRC is valid in range of context list.
-BOOL dglIsValidContext(
- HGLRC a)
-{
- return ((int)a > 0 && (int)a <= DGL_MAX_CONTEXTS);
-}
-
-// ***********************************************************************
-
-// Convert a HGLRC to a pointer into the context list.
-DGL_ctx* dglGetContextAddress(
- const HGLRC a)
-{
- if (dglIsValidContext(a))
- return &ctxlist[(int)a-1];
- return NULL;
-}
-
-// ***********************************************************************
-
-// Return the current HGLRC (however it may be stored for multi-threading).
-HGLRC dglGetCurrentContext(void)
-{
-#ifdef GLD_THREADS
- HGLRC hGLRC;
- // load from thread-specific instance
- if (glb.bMultiThreaded) {
- // protect against calls from arbitrary threads
- __try {
- hGLRC = (HGLRC)TlsGetValue(dwTLSCurrentContext);
- }
- __except(EXCEPTION_EXECUTE_HANDLER) {
- hGLRC = iCurrentContext;
- }
- }
- // load from global static var
- else {
- hGLRC = iCurrentContext;
- }
- return hGLRC;
-#else
- return iCurrentContext;
-#endif
-}
-
-// ***********************************************************************
-
-// Set the current HGLRC (however it may be stored for multi-threading).
-void dglSetCurrentContext(HGLRC hGLRC)
-{
-#ifdef GLD_THREADS
- // store in thread-specific instance
- if (glb.bMultiThreaded) {
- // protect against calls from arbitrary threads
- __try {
- TlsSetValue(dwTLSCurrentContext, (LPVOID)hGLRC);
- }
- __except(EXCEPTION_EXECUTE_HANDLER) {
- iCurrentContext = hGLRC;
- }
- }
- // store in global static var
- else {
- iCurrentContext = hGLRC;
- }
-#else
- iCurrentContext = hGLRC;
-#endif
-}
-
-// ***********************************************************************
-
-// Return the current HDC only for a currently active HGLRC.
-HDC dglGetCurrentDC(void)
-{
- HGLRC hGLRC;
- DGL_ctx* lpCtx;
-
- hGLRC = dglGetCurrentContext();
- if (hGLRC) {
- lpCtx = dglGetContextAddress(hGLRC);
- return lpCtx->hDC;
- }
- return 0;
-}
-
-// ***********************************************************************
-
-void dglInitContextState()
-{
- int i;
- WNDCLASS wc;
-
-#ifdef GLD_THREADS
- // Allocate thread local storage indexes for current context and pixel format
- dwTLSCurrentContext = TlsAlloc();
- dwTLSPixelFormat = TlsAlloc();
-#endif
-
- dglSetCurrentContext(NULL); // No current rendering context
-
- // Clear all context data
- ZeroMemory(ctxlist, sizeof(ctxlist[0]) * DGL_MAX_CONTEXTS);
-
- for (i=0; i<DGL_MAX_CONTEXTS; i++)
- ctxlist[i].bAllocated = FALSE; // Flag context as unused
-
- // This section of code crashes the dll in circumstances where the app
- // creates and destroys contexts.
-/*
- // Register the class for our event monitor window
- wc.style = 0;
- wc.lpfnWndProc = GLD_EventWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = GetModuleHandle(NULL);
- wc.hIcon = LoadIcon(GetModuleHandle(NULL), IDI_APPLICATION);
- wc.hCursor = LoadCursor(NULL, IDC_ARROW);
- wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
- wc.lpszMenuName = NULL;
- wc.lpszClassName = "GLDIRECT";
- RegisterClass(&wc);
-
- // Create the non-visible window to monitor all broadcast messages
- hWndEvent = CreateWindowEx(
- WS_EX_TOOLWINDOW,"GLDIRECT","GLDIRECT",WS_POPUP,
- 0,0,0,0,
- NULL,NULL,GetModuleHandle(NULL),NULL);
-*/
-
-#ifdef GLD_THREADS
- // Create a critical section object for serializing access to
- // DirectDraw and DDStereo create/destroy functions in multiple threads
- if (glb.bMultiThreaded)
- InitializeCriticalSection(&CriticalSection);
-#endif
-
- // Context state is now initialized and ready
- bContextReady = TRUE;
-}
-
-// ***********************************************************************
-
-void dglDeleteContextState()
-{
- int i;
- static BOOL bOnceIsEnough = FALSE;
-
- // Only call once, from either DGL_exitDriver(), or DLL_PROCESS_DETACH
- if (bOnceIsEnough)
- return;
- bOnceIsEnough = TRUE;
-
- for (i=0; i<DGL_MAX_CONTEXTS; i++) {
- if (ctxlist[i].bAllocated == TRUE) {
- ddlogPrintf(DDLOG_WARN, "** Context %i not deleted - cleaning up.", (i+1));
- dglDeleteContext((HGLRC)(i+1));
- }
- }
-
- // Context state is no longer ready
- bContextReady = FALSE;
-
- // If executed when DLL unloads, DDraw objects may be invalid.
- // So catch any page faults with this exception handler.
-__try {
-
- // Release final DirectDraw interfaces
- if (glb.bDirectDrawPersistant) {
-// RELEASE(glb.lpGlobalPalette);
-// RELEASE(glb.lpDepth4);
-// RELEASE(glb.lpBack4);
-// RELEASE(glb.lpPrimary4);
-// RELEASE(glb.lpDD4);
- }
-}
-__except(EXCEPTION_EXECUTE_HANDLER) {
- ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContextState.");
-}
-
- // Destroy our event monitor window
- if (hWndEvent) {
- DestroyWindow(hWndEvent);
- hWndEvent = hWndLastActive = NULL;
- }
-
-#ifdef GLD_THREADS
- // Destroy the critical section object
- if (glb.bMultiThreaded)
- DeleteCriticalSection(&CriticalSection);
-
- // Release thread local storage indexes for current HGLRC and pixel format
- TlsFree(dwTLSPixelFormat);
- TlsFree(dwTLSCurrentContext);
-#endif
-}
-
-// ***********************************************************************
-
-// Application Window message handler interception
-static LONG __stdcall dglWndProc(
- HWND hwnd,
- UINT msg,
- WPARAM wParam,
- LPARAM lParam)
-{
- DGL_ctx* lpCtx = NULL;
- LONG lpfnWndProc = 0L;
- int i;
- HGLRC hGLRC;
- RECT rect;
- PAINTSTRUCT ps;
- BOOL bQuit = FALSE;
- BOOL bMain = FALSE;
- LONG rc;
-
- // Get the window's message handler *before* it is unhooked in WM_DESTROY
-
- // Is this the main window?
- if (hwnd == glb.hWndActive) {
- bMain = TRUE;
- lpfnWndProc = glb.lpfnWndProc;
- }
- // Search for DGL context matching window handle
- for (i=0; i<DGL_MAX_CONTEXTS; i++) {
- if (ctxlist[i].hWnd == hwnd) {
- lpCtx = &ctxlist[i];
- lpfnWndProc = lpCtx->lpfnWndProc;
- break;
- }
- }
- // Not one of ours...
- if (!lpfnWndProc)
- return DefWindowProc(hwnd, msg, wParam, lParam);
-
- // Intercept messages amd process *before* passing on to window
- switch (msg) {
-#ifdef _USE_GLD3_WGL
- case WM_DISPLAYCHANGE:
- glb.bPixelformatsDirty = TRUE;
- break;
-#endif
- case WM_ACTIVATEAPP:
- glb.bAppActive = (BOOL)wParam;
- ddlogPrintf(DDLOG_INFO, "Calling app has been %s", glb.bAppActive ? "activated" : "de-activated");
- break;
- case WM_ERASEBKGND:
- // Eat the GDI erase event for the GL window
- if (!lpCtx || !lpCtx->bHasBeenCurrent)
- break;
- lpCtx->bGDIEraseBkgnd = TRUE;
- return TRUE;
- case WM_PAINT:
- // Eat the invalidated update region if render scene is in progress
- if (!lpCtx || !lpCtx->bHasBeenCurrent)
- break;
- if (lpCtx->bFrameStarted) {
- if (GetUpdateRect(hwnd, &rect, FALSE)) {
- BeginPaint(hwnd, &ps);
- EndPaint(hwnd, &ps);
- ValidateRect(hwnd, &rect);
- return TRUE;
- }
- }
- break;
- }
- // Call the appropriate window message handler
- rc = CallWindowProc((WNDPROC)lpfnWndProc, hwnd, msg, wParam, lParam);
-
- // Intercept messages and process *after* passing on to window
- switch (msg) {
- case WM_QUIT:
- case WM_DESTROY:
- bQuit = TRUE;
- if (lpCtx && lpCtx->bAllocated) {
- ddlogPrintf(DDLOG_WARN, "WM_DESTROY detected for HWND=%X, HDC=%X, HGLRC=%d", hwnd, lpCtx->hDC, i+1);
- dglDeleteContext((HGLRC)(i+1));
- }
- break;
-#if 0
- case WM_SIZE:
- // Resize surfaces to fit window but not viewport (in case app did not bother)
- if (!lpCtx || !lpCtx->bHasBeenCurrent)
- break;
- w = LOWORD(lParam);
- h = HIWORD(lParam);
- if (lpCtx->dwWidth < w || lpCtx->dwHeight < h) {
- if (!dglWglResizeBuffers(lpCtx->glCtx, TRUE))
- dglWglResizeBuffers(lpCtx->glCtx, FALSE);
- }
- break;
-#endif
- }
-
- // If the main window is quitting, then so should we...
- if (bMain && bQuit) {
- ddlogPrintf(DDLOG_SYSTEM, "shutting down after WM_DESTROY detected for main HWND=%X", hwnd);
- dglDeleteContextState();
- dglExitDriver();
- }
-
- return rc;
-}
-
-// ***********************************************************************
-
-// Driver Window message handler
-static LONG __stdcall GLD_EventWndProc(
- HWND hwnd,
- UINT msg,
- WPARAM wParam,
- LPARAM lParam)
-{
- switch (msg) {
- // May be sent by splash screen dialog on exit
- case WM_ACTIVATE:
- if (LOWORD(wParam) == WA_ACTIVE && glb.hWndActive) {
- SetForegroundWindow(glb.hWndActive);
- return 0;
- }
- break;
- }
- return DefWindowProc(hwnd, msg, wParam, lParam);
-}
-
-// ***********************************************************************
-
-// Intercepted Keyboard handler for detecting hot keys.
-LRESULT CALLBACK dglKeyProc(
- int code,
- WPARAM wParam,
- LPARAM lParam)
-{
- HWND hWnd, hWndFrame;
- HGLRC hGLRC = NULL;
- DGL_ctx* lpCtx = NULL;
- int cmd = 0, dx1 = 0, dx2 = 0, i;
- static BOOL bAltPressed = FALSE;
- static BOOL bCtrlPressed = FALSE;
- static BOOL bShiftPressed = FALSE;
- RECT r, rf, rc;
- POINT pt;
- BOOL bForceReshape = FALSE;
-
- return CallNextHookEx(hKeyHook, code, wParam, lParam);
-}
-
-// ***********************************************************************
-
-HWND hWndMatch;
-
-// Window handle enumeration procedure.
-BOOL CALLBACK dglEnumChildProc(
- HWND hWnd,
- LPARAM lParam)
-{
- RECT rect;
-
- // Find window handle with matching client rect.
- GetClientRect(hWnd, &rect);
- if (EqualRect(&rect, (RECT*)lParam)) {
- hWndMatch = hWnd;
- return FALSE;
- }
- // Continue with next child window.
- return TRUE;
-}
-
-// ***********************************************************************
-
-// Find window handle with matching client rect.
-HWND dglFindWindowRect(
- RECT* pRect)
-{
- hWndMatch = NULL;
- EnumChildWindows(GetForegroundWindow(), dglEnumChildProc, (LPARAM)pRect);
- return hWndMatch;
-}
-
-// ***********************************************************************
-#ifndef _USE_GLD3_WGL
-void dglChooseDisplayMode(
- DGL_ctx *lpCtx)
-{
- // Note: Choose an exact match if possible.
-
- int i;
- DWORD area;
- DWORD bestarea;
- DDSURFACEDESC2 *lpDDSD = NULL; // Mode list pointer
- DDSURFACEDESC2 *lpBestDDSD = NULL; // Pointer to best
-
- lpDDSD = glb.lpDisplayModes;
- for (i=0; i<glb.nDisplayModeCount; i++, lpDDSD++) {
- if ((lpDDSD->dwWidth == lpCtx->dwWidth) &&
- (lpDDSD->dwHeight == lpCtx->dwHeight))
- goto matched; // Mode has been exactly matched
- // Choose modes that are larger in both dimensions than
- // the window, but smaller in area than the current best.
- if ( (lpDDSD->dwWidth >= lpCtx->dwWidth) &&
- (lpDDSD->dwHeight >= lpCtx->dwHeight))
- {
- if (lpBestDDSD == NULL) {
- lpBestDDSD = lpDDSD;
- bestarea = lpDDSD->dwWidth * lpDDSD->dwHeight;
- continue;
- }
- area = lpDDSD->dwWidth * lpDDSD->dwHeight;
- if (area < bestarea) {
- lpBestDDSD = lpDDSD;
- bestarea = area;
- }
- }
- }
-
- // Safety check
- if (lpBestDDSD == NULL) {
- ddlogMessage(DDLOG_CRITICAL, "dglChooseDisplayMode");
- return;
- }
-
- lpCtx->dwModeWidth = lpBestDDSD->dwWidth;
- lpCtx->dwModeHeight = lpBestDDSD->dwHeight;
-matched:
- ddlogPrintf(DDLOG_INFO, "Matched (%ldx%ld) to (%ldx%ld)",
- lpCtx->dwWidth, lpCtx->dwHeight, lpCtx->dwModeWidth, lpCtx->dwModeHeight);
-}
-#endif // _USE_GLD3_WGL
-// ***********************************************************************
-
-static BOOL IsDevice(
- DWORD *lpDeviceIdList,
- DWORD dwDeviceId,
- int count)
-{
- int i;
-
- for (i=0; i<count; i++)
- if (dwDeviceId == lpDeviceIdList[i])
- return TRUE;
-
- return FALSE;
-}
-
-// ***********************************************************************
-
-void dglTestForBrokenCards(
- DGL_ctx *lpCtx)
-{
-#ifndef _GLD3
- DDDEVICEIDENTIFIER dddi; // DX6 device identifier
-
- // Sanity check.
- if (lpCtx == NULL) {
- // Testing for broken cards is sensitive area, so we don't want
- // anything saying "broken cards" in the error message. ;)
- ddlogMessage(DDLOG_ERROR, "Null context passed to TFBC\n");
- return;
- }
-
- if (lpCtx->lpDD4 == NULL) {
- // Testing for broken cards is sensitive area, so we don't want
- // anything saying "broken cards" in the error message. ;)
- ddlogMessage(DDLOG_ERROR, "Null DD4 passed to TFBC\n");
- return;
- }
-
- // Microsoft really fucked up with the GetDeviceIdentifier function
- // on Windows 2000, since it locks up on stock driers on the CD. Updated
- // drivers from vendors appear to work, but we can't identify the drivers
- // without this function!!! For now we skip these tests on Windows 2000.
- if ((GetVersion() & 0x80000000UL) == 0)
- return;
-
- // Obtain device info
- if (FAILED(IDirectDraw4_GetDeviceIdentifier(lpCtx->lpDD4, &dddi, 0)))
- return;
-
- // Useful info. Log it.
- ddlogPrintf(DDLOG_INFO, "DirectDraw: VendorId=0x%x, DeviceId=0x%x", dddi.dwVendorId, dddi.dwDeviceId);
-
- // Vendor 1: ATI
- if (dddi.dwVendorId == VENDORID_ATI) {
- // Test A: ATI Rage PRO
- if (IsDevice(devATIRagePro, dddi.dwDeviceId, sizeof(devATIRagePro)))
- glb.bUseMipmaps = FALSE;
- // Test B: ATI Rage II+
- if (IsDevice(devATIRageIIplus, dddi.dwDeviceId, sizeof(devATIRageIIplus)))
- glb.bEmulateAlphaTest = TRUE;
- }
-
- // Vendor 2: Matrox
- if (dddi.dwVendorId == 0x102B) {
- // Test: Matrox G400 stencil buffer support does not work for AutoCAD
- if (dddi.dwDeviceId == 0x0525) {
- lpCtx->lpPF->pfd.cStencilBits = 0;
- if (lpCtx->lpPF->iZBufferPF != -1) {
- glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitDepth = 0;
- glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitMask = 0;
- glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags &= ~DDPF_STENCILBUFFER;
- }
- }
- }
-#endif // _GLD3
-}
-
-// ***********************************************************************
-
-BOOL dglCreateContextBuffers(
- HDC a,
- DGL_ctx *lpCtx,
- BOOL bFallback)
-{
- HRESULT hResult;
-
- int i;
-// HGLRC hGLRC;
-// DGL_ctx* lpCtx;
-
-#ifndef _USE_GLD3_WGL
- DWORD dwFlags;
- DDSURFACEDESC2 ddsd2;
- DDSCAPS2 ddscaps2;
- LPDIRECTDRAWCLIPPER lpddClipper;
- D3DDEVICEDESC D3DHWDevDesc; // Direct3D Hardware description
- D3DDEVICEDESC D3DHELDevDesc; // Direct3D Hardware Emulation Layer
-#endif // _USE_GLD3_WGL
-
- float inv_aspect;
-
- GLenum bDoubleBuffer; // TRUE if double buffer required
- GLenum bDepthBuffer; // TRUE if depth buffer required
-
- const PIXELFORMATDESCRIPTOR *lpPFD = &lpCtx->lpPF->pfd;
-
- // Vars for Mesa visual
- DWORD dwDepthBits = 0;
- DWORD dwStencilBits = 0;
- DWORD dwAlphaBits = 0;
- DWORD bAlphaSW = GL_FALSE;
- DWORD bDouble = GL_FALSE;
-
- DDSURFACEDESC2 ddsd2DisplayMode;
- BOOL bFullScrnWin = FALSE; // fullscreen-size window ?
- DDBLTFX ddbltfx;
- DWORD dwMemoryType = (bFallback) ? DDSCAPS_SYSTEMMEMORY : glb.dwMemoryType;
- BOOL bBogusWindow = FALSE; // non-drawable window ?
- DWORD dwColorRef = 0; // GDI background color
- RECT rcDst; // GDI window rect
- POINT pt; // GDI window point
-
- // Palette used for creating default global palette
- PALETTEENTRY ppe[256];
-
-#ifndef _USE_GLD3_WGL
- // Vertex buffer description. Used for creation of vertex buffers
- D3DVERTEXBUFFERDESC vbufdesc;
-#endif // _USE_GLD3_WGL
-
-#define DDLOG_CRITICAL_OR_WARN (bFallback ? DDLOG_CRITICAL : DDLOG_WARN)
-
- ddlogPrintf(DDLOG_SYSTEM, "dglCreateContextBuffers for HDC=%X", a);
- nContextError = GLDERR_NONE;
-
-#ifdef GLD_THREADS
- // Serialize access to DirectDraw object creation or DDS start
- if (glb.bMultiThreaded)
- EnterCriticalSection(&CriticalSection);
-#endif
-
- // Check for back buffer
- bDoubleBuffer = GL_TRUE; //(lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? GL_TRUE : GL_FALSE;
- // Since we always do back buffering, check if we emulate front buffering
- lpCtx->EmulateSingle =
- (lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;
-#if 0 // Don't have to mimic MS OpenGL behavior for front-buffering (DaveM)
- lpCtx->EmulateSingle |=
- (lpPFD->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
-#endif
-
- // Check for depth buffer
- bDepthBuffer = (lpPFD->cDepthBits) ? GL_TRUE : GL_FALSE;
-
- lpCtx->bDoubleBuffer = bDoubleBuffer;
- lpCtx->bDepthBuffer = bDepthBuffer;
-
- // Set the Fullscreen flag for the context.
-// lpCtx->bFullscreen = glb.bFullscreen;
-
- // Obtain the dimensions of the rendering window
- lpCtx->hDC = a; // Cache DC
- lpCtx->hWnd = WindowFromDC(lpCtx->hDC);
- // Check for non-window DC = memory DC ?
- if (lpCtx->hWnd == NULL) {
- // bitmap memory contexts are always single-buffered
- lpCtx->EmulateSingle = TRUE;
- bBogusWindow = TRUE;
- ddlogPrintf(DDLOG_INFO, "Non-Window Memory Device Context");
- if (GetClipBox(lpCtx->hDC, &lpCtx->rcScreenRect) == ERROR) {
- ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglCreateContext\n");
- SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
- }
- }
- else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
- bBogusWindow = TRUE;
- ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglCreateContext\n");
- SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
- }
- lpCtx->dwWidth = lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left;
- lpCtx->dwHeight = lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top;
-
- ddlogPrintf(DDLOG_INFO, "Input window %X: w=%i, h=%i",
- lpCtx->hWnd, lpCtx->dwWidth, lpCtx->dwHeight);
-
- // What if app only zeroes one dimension instead of both? (DaveM)
- if ( (lpCtx->dwWidth == 0) || (lpCtx->dwHeight == 0) ) {
- // Make the buffer size something sensible
- lpCtx->dwWidth = 8;
- lpCtx->dwHeight = 8;
- }
-
- // Set defaults
- lpCtx->dwModeWidth = lpCtx->dwWidth;
- lpCtx->dwModeHeight = lpCtx->dwHeight;
-/*
- // Find best display mode for fullscreen
- if (glb.bFullscreen || !glb.bPrimary) {
- dglChooseDisplayMode(lpCtx);
- }
-*/
- // Misc initialisation
- lpCtx->bCanRender = FALSE; // No rendering allowed yet
- lpCtx->bSceneStarted = FALSE;
- lpCtx->bFrameStarted = FALSE;
-
- // Detect OS (specifically 'Windows 2000' or 'Windows XP')
- DetectOS();
-
- // NOTE: WinNT not supported
- ddlogPrintf(DDLOG_INFO, "OS: %s", bHaveWin95 ? "Win9x" : (bHaveWin2K ? "Win2000/XP" : "Unsupported") );
-
- // Test for Fullscreen
- if (bHaveWin95) { // Problems with fullscreen on Win2K/XP
- if ((GetSystemMetrics(SM_CXSCREEN) == lpCtx->dwWidth) &&
- (GetSystemMetrics(SM_CYSCREEN) == lpCtx->dwHeight))
- {
- // Workaround for some apps that crash when going fullscreen.
- //lpCtx->bFullscreen = TRUE;
- }
-
- }
-
-#ifdef _USE_GLD3_WGL
- _gldDriver.CreateDrawable(lpCtx, glb.bDirectDrawPersistant, glb.bPersistantBuffers);
-#else
- // Check if DirectDraw has already been created by original GLRC (DaveM)
- if (glb.bDirectDrawPersistant && glb.bDirectDraw) {
- lpCtx->lpDD4 = glb.lpDD4;
- IDirectDraw4_AddRef(lpCtx->lpDD4);
- goto SkipDirectDrawCreate;
- }
-
- // Create DirectDraw object
- if (glb.bPrimary)
- hResult = DirectDrawCreate(NULL, &lpCtx->lpDD1, NULL);
- else {
- // A non-primary device is to be used.
- // Force context to be Fullscreen, secondary adaptors can not
- // be used in a window.
- hResult = DirectDrawCreate(&glb.ddGuid, &lpCtx->lpDD1, NULL);
- lpCtx->bFullscreen = TRUE;
- }
- if (FAILED(hResult)) {
- MessageBox(NULL, "Unable to initialize DirectDraw", "GLDirect", MB_OK);
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw interface", hResult);
- nContextError = GLDERR_DDRAW;
- goto return_with_error;
- }
-
- // Query for DX6 IDirectDraw4.
- hResult = IDirectDraw_QueryInterface(lpCtx->lpDD1,
- &IID_IDirectDraw4,
- (void**)&lpCtx->lpDD4);
- if (FAILED(hResult)) {
- MessageBox(NULL, "GLDirect requires DirectX 6.0 or above", "GLDirect", MB_OK);
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw4 interface", hResult);
- nContextError = GLDERR_DDRAW;
- goto return_with_error;
- }
-
- // Cache DirectDraw interface for subsequent GLRCs
- if (glb.bDirectDrawPersistant && !glb.bDirectDraw) {
- glb.lpDD4 = lpCtx->lpDD4;
- IDirectDraw4_AddRef(glb.lpDD4);
- glb.bDirectDraw = TRUE;
- }
-SkipDirectDrawCreate:
-
- // Now we have a DD4 interface we can check for broken cards
- dglTestForBrokenCards(lpCtx);
-
- // Test if primary device can use flipping instead of blitting
- ZeroMemory(&ddsd2DisplayMode, sizeof(ddsd2DisplayMode));
- ddsd2DisplayMode.dwSize = sizeof(ddsd2DisplayMode);
- hResult = IDirectDraw4_GetDisplayMode(
- lpCtx->lpDD4,
- &ddsd2DisplayMode);
- if (SUCCEEDED(hResult)) {
- if ( (lpCtx->dwWidth == ddsd2DisplayMode.dwWidth) &&
- (lpCtx->dwHeight == ddsd2DisplayMode.dwHeight) ) {
- // We have a fullscreen-size window
- bFullScrnWin = TRUE;
- // OK to use DirectDraw fullscreen mode ?
- if (glb.bPrimary && !glb.bFullscreenBlit && !lpCtx->EmulateSingle && !glb.bDirectDrawPersistant) {
- lpCtx->bFullscreen = TRUE;
- ddlogMessage(DDLOG_INFO, "Primary upgraded to page flipping.\n");
- }
- }
- // Cache the display mode dimensions
- lpCtx->dwModeWidth = ddsd2DisplayMode.dwWidth;
- lpCtx->dwModeHeight = ddsd2DisplayMode.dwHeight;
- }
-
- // Clamp the effective window dimensions to primary surface.
- // We need to do this for D3D viewport dimensions even if wide
- // surfaces are supported. This also is a good idea for handling
- // whacked-out window dimensions passed for non-drawable windows
- // like Solid Edge. (DaveM)
- if (lpCtx->dwWidth > ddsd2DisplayMode.dwWidth)
- lpCtx->dwWidth = ddsd2DisplayMode.dwWidth;
- if (lpCtx->dwHeight > ddsd2DisplayMode.dwHeight)
- lpCtx->dwHeight = ddsd2DisplayMode.dwHeight;
-
- // Check for non-RGB desktop resolution
- if (!lpCtx->bFullscreen && ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount <= 8) {
- ddlogPrintf(DDLOG_CRITICAL_OR_WARN, "Desktop color depth %d bpp not supported",
- ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount);
- nContextError = GLDERR_BPP;
- goto return_with_error;
- }
-#endif // _USE_GLD3_WGL
-
- ddlogPrintf(DDLOG_INFO, "Window: w=%i, h=%i (%s)",
- lpCtx->dwWidth,
- lpCtx->dwHeight,
- lpCtx->bFullscreen ? "fullscreen" : "windowed");
-
-#ifndef _USE_GLD3_WGL
- // Obtain ddraw caps
- ZeroMemory(&lpCtx->ddCaps, sizeof(DDCAPS));
- lpCtx->ddCaps.dwSize = sizeof(DDCAPS);
- if (glb.bHardware) {
- // Get HAL caps
- IDirectDraw4_GetCaps(lpCtx->lpDD4, &lpCtx->ddCaps, NULL);
- } else {
- // Get HEL caps
- IDirectDraw4_GetCaps(lpCtx->lpDD4, NULL, &lpCtx->ddCaps);
- }
-
- // If this flag is present then we can't default to Mesa
- // SW rendering between BeginScene() and EndScene().
- if (lpCtx->ddCaps.dwCaps2 & DDCAPS2_NO2DDURING3DSCENE) {
- ddlogMessage(DDLOG_INFO,
- "Warning : No 2D allowed during 3D scene.\n");
- }
-
- // Query for DX6 Direct3D3 interface
- hResult = IDirectDraw4_QueryInterface(lpCtx->lpDD4,
- &IID_IDirect3D3,
- (void**)&lpCtx->lpD3D3);
- if (FAILED(hResult)) {
- MessageBox(NULL, "Unable to initialize Direct3D", "GLDirect", MB_OK);
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D interface", hResult);
- nContextError = GLDERR_D3D;
- goto return_with_error;
- }
-
- // Context creation
- if (lpCtx->bFullscreen) {
- // FULLSCREEN
-
- // Disable warning popups when in fullscreen mode
- ddlogWarnOption(FALSE);
-
- // Have to release persistant primary surface if fullscreen mode
- if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
- RELEASE(glb.lpPrimary4);
- glb.bDirectDrawPrimary = FALSE;
- }
-
- dwFlags = DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT;
- if (glb.bFastFPU)
- dwFlags |= DDSCL_FPUSETUP; // fast FPU setup optional (DaveM)
- hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, lpCtx->hWnd, dwFlags);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Exclusive Fullscreen mode", hResult);
- goto return_with_error;
- }
-
- hResult = IDirectDraw4_SetDisplayMode(lpCtx->lpDD4,
- lpCtx->dwModeWidth,
- lpCtx->dwModeHeight,
- lpPFD->cColorBits,
- 0,
- 0);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "SetDisplayMode failed", hResult);
- goto return_with_error;
- }
-
- // ** The display mode has changed, so dont use MessageBox! **
-
- ZeroMemory(&ddsd2, sizeof(ddsd2));
- ddsd2.dwSize = sizeof(ddsd2);
-
- if (bDoubleBuffer) {
- // Double buffered
- // Primary surface
- ddsd2.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
- ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
- DDSCAPS_FLIP |
- DDSCAPS_COMPLEX |
- DDSCAPS_3DDEVICE |
- dwMemoryType;
- ddsd2.dwBackBufferCount = 1;
-
- hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
-
- // Render target surface
- ZeroMemory(&ddscaps2, sizeof(ddscaps2)); // Clear the entire struct.
- ddscaps2.dwCaps = DDSCAPS_BACKBUFFER;
- hResult = IDirectDrawSurface4_GetAttachedSurface(lpCtx->lpFront4, &ddscaps2, &lpCtx->lpBack4);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "GetAttachedSurface failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
- } else {
- // Single buffered
- // Primary surface
- ddsd2.dwFlags = DDSD_CAPS;
- ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
- //DDSCAPS_3DDEVICE |
- dwMemoryType;
-
- hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
-
- lpCtx->lpBack4 = NULL;
- }
- } else {
- // WINDOWED
-
- // OK to enable warning popups in windowed mode
- ddlogWarnOption(glb.bMessageBoxWarnings);
-
- dwFlags = DDSCL_NORMAL;
- if (glb.bMultiThreaded)
- dwFlags |= DDSCL_MULTITHREADED;
- if (glb.bFastFPU)
- dwFlags |= DDSCL_FPUSETUP; // fast FPU setup optional (DaveM)
- hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4,
- lpCtx->hWnd,
- dwFlags);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Normal coop level", hResult);
- goto return_with_error;
- }
- // Has Primary surface already been created for original GLRC ?
- // Note this can only be applicable for windowed modes
- if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
- lpCtx->lpFront4 = glb.lpPrimary4;
- IDirectDrawSurface4_AddRef(lpCtx->lpFront4);
- // Update the window on the default clipper
- IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
- IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
- IDirectDrawClipper_Release(lpddClipper);
- goto SkipPrimaryCreate;
- }
-
- // Primary surface
- ZeroMemory(&ddsd2, sizeof(ddsd2));
- ddsd2.dwSize = sizeof(ddsd2);
- ddsd2.dwFlags = DDSD_CAPS;
- ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
- hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
-
- // Cache Primary surface for subsequent GLRCs
- // Note this can only be applicable to subsequent windowed modes
- if (glb.bDirectDrawPersistant && !glb.bDirectDrawPrimary) {
- glb.lpPrimary4 = lpCtx->lpFront4;
- IDirectDrawSurface4_AddRef(glb.lpPrimary4);
- glb.bDirectDrawPrimary = TRUE;
- }
-
- // Clipper object
- hResult = DirectDrawCreateClipper(0, &lpddClipper, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateClipper failed", hResult);
- goto return_with_error;
- }
- hResult = IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
- if (FAILED(hResult)) {
- RELEASE(lpddClipper);
- ddlogError(DDLOG_CRITICAL_OR_WARN, "SetHWnd failed", hResult);
- goto return_with_error;
- }
- hResult = IDirectDrawSurface4_SetClipper(lpCtx->lpFront4, lpddClipper);
- RELEASE(lpddClipper); // We have finished with it.
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "SetClipper failed", hResult);
- goto return_with_error;
- }
-SkipPrimaryCreate:
-
- if (bDoubleBuffer) {
- // Render target surface
- ZeroMemory(&ddsd2, sizeof(ddsd2));
- ddsd2.dwSize = sizeof(ddsd2);
- ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
- ddsd2.dwWidth = lpCtx->dwWidth;
- ddsd2.dwHeight = lpCtx->dwHeight;
- ddsd2.ddsCaps.dwCaps = DDSCAPS_3DDEVICE |
- DDSCAPS_OFFSCREENPLAIN |
- dwMemoryType;
-
- // Reserve the entire desktop size for persistant buffers option
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
- ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
- ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
- }
- // Re-use original back buffer if persistant buffers exist
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpBack4)
- hResult = IDirectDrawSurface4_AddRef(lpCtx->lpBack4 = glb.lpBack4);
- else
- hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpBack4, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Create Backbuffer failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpBack4)
- IDirectDrawSurface4_AddRef(glb.lpBack4 = lpCtx->lpBack4);
- } else {
- lpCtx->lpBack4 = NULL;
- }
- }
-
- //
- // Now create the Z-buffer
- //
- lpCtx->bStencil = FALSE; // Default to no stencil buffer
- if (bDepthBuffer && (lpCtx->lpPF->iZBufferPF != -1)) {
- // Get z-buffer dimensions from the render target
- // Setup the surface desc for the z-buffer.
- ZeroMemory(&ddsd2, sizeof(ddsd2));
- ddsd2.dwSize = sizeof(ddsd2);
- ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
- ddsd2.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | dwMemoryType;
- ddsd2.dwWidth = lpCtx->dwWidth;
- ddsd2.dwHeight = lpCtx->dwHeight;
- memcpy(&ddsd2.ddpfPixelFormat,
- &glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF],
- sizeof(DDPIXELFORMAT) );
-
- // Reserve the entire desktop size for persistant buffers option
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
- ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
- ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
- }
-
- // Create a z-buffer
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4)
- hResult = IDirectDrawSurface4_AddRef(lpCtx->lpDepth4 = glb.lpDepth4);
- else
- hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpDepth4, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (ZBuffer) failed", hResult);
- nContextError = GLDERR_MEM;
- goto return_with_error;
- }
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpDepth4)
- IDirectDrawSurface4_AddRef(glb.lpDepth4 = lpCtx->lpDepth4);
- else if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4 && glb.lpBack4)
- IDirectDrawSurface4_DeleteAttachedSurface(glb.lpBack4, 0, glb.lpDepth4);
-
- // Attach Zbuffer to render target
- TRY(IDirectDrawSurface4_AddAttachedSurface(
- bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
- lpCtx->lpDepth4),
- "dglCreateContext: Attach Zbuffer");
- if (glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags & DDPF_STENCILBUFFER) {
- lpCtx->bStencil = TRUE;
- ddlogMessage(DDLOG_INFO, "Depth buffer has stencil\n");
- }
- }
-
- // Clear all back buffers and Z-buffers in case of memory recycling.
- ZeroMemory(&ddbltfx, sizeof(ddbltfx));
- ddbltfx.dwSize = sizeof(ddbltfx);
- IDirectDrawSurface4_Blt(lpCtx->lpBack4, NULL, NULL, NULL,
- DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);
- if (lpCtx->lpDepth4)
- IDirectDrawSurface4_Blt(lpCtx->lpDepth4, NULL, NULL, NULL,
- DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);
-
- // Now that we have a Z-buffer we can create the 3D device
- hResult = IDirect3D3_CreateDevice(lpCtx->lpD3D3,
- &glb.d3dGuid,
- bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
- &lpCtx->lpDev3,
- NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D device", hResult);
- nContextError = GLDERR_D3D;
- goto return_with_error;
- }
-
- // We must do this as soon as the device is created
- dglInitStateCaches(lpCtx);
-
- // Obtain the D3D Device Description
- D3DHWDevDesc.dwSize = D3DHELDevDesc.dwSize = sizeof(D3DDEVICEDESC);
- TRY(IDirect3DDevice3_GetCaps(lpCtx->lpDev3,
- &D3DHWDevDesc,
- &D3DHELDevDesc),
- "dglCreateContext: GetCaps failed");
-
- // Choose the relevant description and cache it in the context.
- // We will use this description later for caps checking
- memcpy( &lpCtx->D3DDevDesc,
- glb.bHardware ? &D3DHWDevDesc : &D3DHELDevDesc,
- sizeof(D3DDEVICEDESC));
-
- // Now we can examine the texture formats
- if (!dglBuildTextureFormatList(lpCtx->lpDev3)) {
- ddlogMessage(DDLOG_CRITICAL_OR_WARN, "dglBuildTextureFormatList failed\n");
- goto return_with_error;
- }
-
- // Get the pixel format of the back buffer
- lpCtx->ddpfRender.dwSize = sizeof(lpCtx->ddpfRender);
- if (bDoubleBuffer)
- hResult = IDirectDrawSurface4_GetPixelFormat(
- lpCtx->lpBack4,
- &lpCtx->ddpfRender);
- else
- hResult = IDirectDrawSurface4_GetPixelFormat(
- lpCtx->lpFront4,
- &lpCtx->ddpfRender);
-
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "GetPixelFormat failed", hResult);
- goto return_with_error;
- }
- // Find a pixel packing function suitable for this surface
- pxClassifyPixelFormat(&lpCtx->ddpfRender,
- &lpCtx->fnPackFunc,
- &lpCtx->fnUnpackFunc,
- &lpCtx->fnPackSpanFunc);
-
- // Viewport
- hResult = IDirect3D3_CreateViewport(lpCtx->lpD3D3, &lpCtx->lpViewport3, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateViewport failed", hResult);
- goto return_with_error;
- }
-
- hResult = IDirect3DDevice3_AddViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "AddViewport failed", hResult);
- goto return_with_error;
- }
-
- // Initialise the viewport
- // Note screen coordinates are used for viewport clipping since D3D
- // transform operations are not used in the GLD CAD driver. (DaveM)
- inv_aspect = (float)lpCtx->dwHeight/(float)lpCtx->dwWidth;
-
- lpCtx->d3dViewport.dwSize = sizeof(lpCtx->d3dViewport);
- lpCtx->d3dViewport.dwX = 0;
- lpCtx->d3dViewport.dwY = 0;
- lpCtx->d3dViewport.dwWidth = lpCtx->dwWidth;
- lpCtx->d3dViewport.dwHeight = lpCtx->dwHeight;
- lpCtx->d3dViewport.dvClipX = 0; // -1.0f;
- lpCtx->d3dViewport.dvClipY = 0; // inv_aspect;
- lpCtx->d3dViewport.dvClipWidth = lpCtx->dwWidth; // 2.0f;
- lpCtx->d3dViewport.dvClipHeight = lpCtx->dwHeight; // 2.0f * inv_aspect;
- lpCtx->d3dViewport.dvMinZ = 0.0f;
- lpCtx->d3dViewport.dvMaxZ = 1.0f;
- TRY(IDirect3DViewport3_SetViewport2(lpCtx->lpViewport3, &lpCtx->d3dViewport), "dglCreateContext: SetViewport2");
-
- hResult = IDirect3DDevice3_SetCurrentViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "SetCurrentViewport failed", hResult);
- goto return_with_error;
- }
-
- lpCtx->dwBPP = lpPFD->cColorBits;
- lpCtx->iZBufferPF = lpCtx->lpPF->iZBufferPF;
-
- // Set last texture to NULL
- for (i=0; i<MAX_TEXTURE_UNITS; i++) {
- lpCtx->ColorOp[i] = D3DTOP_DISABLE;
- lpCtx->AlphaOp[i] = D3DTOP_DISABLE;
- lpCtx->tObj[i] = NULL;
- }
-
- // Default to perspective correct texture mapping
- dglSetRenderState(lpCtx, D3DRENDERSTATE_TEXTUREPERSPECTIVE, TRUE, "TexturePersp");
-
- // Set the default culling mode
- lpCtx->cullmode = D3DCULL_NONE;
- dglSetRenderState(lpCtx, D3DRENDERSTATE_CULLMODE, D3DCULL_NONE, "CullMode");
-
- // Disable specular
- dglSetRenderState(lpCtx, D3DRENDERSTATE_SPECULARENABLE, FALSE, "SpecularEnable");
- // Disable subpixel correction
-// dglSetRenderState(lpCtx, D3DRENDERSTATE_SUBPIXEL, FALSE, "SubpixelEnable");
- // Disable dithering
- dglSetRenderState(lpCtx, D3DRENDERSTATE_DITHERENABLE, FALSE, "DitherEnable");
-
- // Initialise the primitive caches
-// lpCtx->dwNextLineVert = 0;
-// lpCtx->dwNextTriVert = 0;
-
- // Init the global texture palette
- lpCtx->lpGlobalPalette = NULL;
-
- // Init the HW/SW usage counters
-// lpCtx->dwHWUsageCount = lpCtx->dwSWUsageCount = 0L;
-
- //
- // Create two D3D vertex buffers.
- // One will hold the pre-transformed data with the other one
- // being used to hold the post-transformed & clipped verts.
- //
-#if 0 // never used (DaveM)
- vbufdesc.dwSize = sizeof(D3DVERTEXBUFFERDESC);
- vbufdesc.dwCaps = D3DVBCAPS_WRITEONLY;
- if (glb.bHardware == FALSE)
- vbufdesc.dwCaps = D3DVBCAPS_SYSTEMMEMORY;
- vbufdesc.dwNumVertices = 32768; // For the time being
-
- // Source vertex buffer
- vbufdesc.dwFVF = DGL_LVERTEX;
- hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_vbuf, 0, NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(src) failed", hResult);
- goto return_with_error;
- }
-
- // Destination vertex buffer
- vbufdesc.dwFVF = (glb.bMultitexture == FALSE) ? D3DFVF_TLVERTEX : (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX2);
- hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_pvbuf, 0, NULL);
- if(FAILED(hResult)) {
- ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(dst) failed", hResult);
- goto return_with_error;
- }
-#endif
-
-#endif _USE_GLD3_WGL
-
- //
- // Now create the Mesa context
- //
-
- // Create the Mesa visual
- if (lpPFD->cDepthBits)
- dwDepthBits = 16;
- if (lpPFD->cStencilBits)
- dwStencilBits = 8;
- if (lpPFD->cAlphaBits) {
- dwAlphaBits = 8;
- bAlphaSW = GL_TRUE;
- }
- if (lpPFD->dwFlags & PFD_DOUBLEBUFFER)
- bDouble = GL_TRUE;
-// lpCtx->EmulateSingle =
-// (lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;
-
-#ifdef _USE_GLD3_WGL
- lpCtx->glVis = _mesa_create_visual(
- bDouble, /* double buffer */
- GL_FALSE, // stereo
- lpPFD->cRedBits,
- lpPFD->cGreenBits,
- lpPFD->cBlueBits,
- dwAlphaBits,
- dwDepthBits,
- dwStencilBits,
- lpPFD->cAccumRedBits, // accum bits
- lpPFD->cAccumGreenBits, // accum bits
- lpPFD->cAccumBlueBits, // accum bits
- lpPFD->cAccumAlphaBits, // accum alpha bits
- 1 // num samples
- );
-#else // _USE_GLD3_WGL
- lpCtx->glVis = (*mesaFuncs.gl_create_visual)(
- GL_TRUE, // RGB mode
- bAlphaSW, // Is an alpha buffer required?
- bDouble, // Is an double-buffering required?
- GL_FALSE, // stereo
- dwDepthBits, // depth_size
- dwStencilBits, // stencil_size
- lpPFD->cAccumBits, // accum_size
- 0, // colour-index bits
- lpPFD->cRedBits, // Red bit count
- lpPFD->cGreenBits, // Green bit count
- lpPFD->cBlueBits, // Blue bit count
- dwAlphaBits // Alpha bit count
- );
-#endif // _USE_GLD3_WGL
-
- if (lpCtx->glVis == NULL) {
- ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_visual failed\n");
- goto return_with_error;
- }
-
-#ifdef _USE_GLD3_WGL
- lpCtx->glCtx = _mesa_create_context(API_OPENGL, lpCtx->glVis, NULL, (void *)lpCtx, GL_TRUE);
-#else
- // Create the Mesa context
- lpCtx->glCtx = (*mesaFuncs.gl_create_context)(
- lpCtx->glVis, // Mesa visual
- NULL, // share list context
- (void *)lpCtx, // Pointer to our driver context
- GL_TRUE // Direct context flag
- );
-#endif // _USE_GLD3_WGL
-
- if (lpCtx->glCtx == NULL) {
- ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_context failed\n");
- goto return_with_error;
- }
-
- // Create the Mesa framebuffer
-#ifdef _USE_GLD3_WGL
- lpCtx->glBuffer = _mesa_create_framebuffer(
- lpCtx->glVis,
- lpCtx->glVis->depthBits > 0,
- lpCtx->glVis->stencilBits > 0,
- lpCtx->glVis->accumRedBits > 0,
- GL_FALSE //swalpha
- );
-#else
- lpCtx->glBuffer = (*mesaFuncs.gl_create_framebuffer)(lpCtx->glVis);
-#endif // _USE_GLD3_WGL
-
- if (lpCtx->glBuffer == NULL) {
- ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_framebuffer failed\n");
- goto return_with_error;
- }
-
-#ifdef _USE_GLD3_WGL
- // Init Mesa internals
- _swrast_CreateContext( lpCtx->glCtx );
- _vbo_CreateContext( lpCtx->glCtx );
- _tnl_CreateContext( lpCtx->glCtx );
- _swsetup_CreateContext( lpCtx->glCtx );
-
- _gldDriver.InitialiseMesa(lpCtx);
-
- lpCtx->glCtx->imports.warning = _gld_mesa_warning;
- lpCtx->glCtx->imports.fatal = _gld_mesa_fatal;
-
-#else
- // Tell Mesa how many texture stages we have
- glb.wMaxSimultaneousTextures = lpCtx->D3DDevDesc.wMaxSimultaneousTextures;
- // Only use as many Units as the spec requires
- if (glb.wMaxSimultaneousTextures > MAX_TEXTURE_UNITS)
- glb.wMaxSimultaneousTextures = MAX_TEXTURE_UNITS;
- lpCtx->glCtx->Const.MaxTextureUnits = glb.wMaxSimultaneousTextures;
- ddlogPrintf(DDLOG_INFO, "Texture stages : %d", glb.wMaxSimultaneousTextures);
-
- // Set the max texture size.
- // NOTE: clamped to a max of 1024 for extra performance!
- lpCtx->dwMaxTextureSize = (lpCtx->D3DDevDesc.dwMaxTextureWidth <= 1024) ? lpCtx->D3DDevDesc.dwMaxTextureWidth : 1024;
-
-// Texture resize takes place elsewhere. KH
-// NOTE: This was added to workaround an issue with the Intel app.
-#if 0
- lpCtx->glCtx->Const.MaxTextureSize = lpCtx->dwMaxTextureSize;
-#else
- lpCtx->glCtx->Const.MaxTextureSize = 1024;
-#endif
- lpCtx->glCtx->Const.MaxDrawBuffers = 1;
-
- // Setup the Display Driver pointers
- dglSetupDDPointers(lpCtx->glCtx);
-
- // Initialise all the Direct3D renderstates
- dglInitStateD3D(lpCtx->glCtx);
-
-#if 0
- // Signal a reload of texture state on next glBegin
- lpCtx->m_texHandleValid = FALSE;
- lpCtx->m_mtex = FALSE;
- lpCtx->m_texturing = FALSE;
-#else
- // Set default texture unit state
-// dglSetTexture(lpCtx, 0, NULL);
-// dglSetTexture(lpCtx, 1, NULL);
-#endif
-
- //
- // Set the global texture palette to default values.
- //
-
- // Clear the entire palette
- ZeroMemory(ppe, sizeof(PALETTEENTRY) * 256);
-
- // Fill the palette with a default colour.
- // A garish colour is used to catch bugs. Here Magenta is used.
- for (i=0; i < 256; i++) {
- ppe[i].peRed = 255;
- ppe[i].peGreen = 0;
- ppe[i].peBlue = 255;
- }
-
- RELEASE(lpCtx->lpGlobalPalette);
-
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpGlobalPalette)
- hResult = IDirectDrawPalette_AddRef(lpCtx->lpGlobalPalette = glb.lpGlobalPalette);
- else
- hResult = IDirectDraw4_CreatePalette(
- lpCtx->lpDD4,
- DDPCAPS_INITIALIZE | DDPCAPS_8BIT | DDPCAPS_ALLOW256,
- ppe,
- &(lpCtx->lpGlobalPalette),
- NULL);
- if (FAILED(hResult)) {
- ddlogError(DDLOG_ERROR, "Default CreatePalette failed\n", hResult);
- lpCtx->lpGlobalPalette = NULL;
- goto return_with_error;
- }
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpGlobalPalette)
- IDirectDrawPalette_AddRef(glb.lpGlobalPalette = lpCtx->lpGlobalPalette);
-
-#endif // _USE_GLD3_WGL
-
- // ** If we have made it to here then we can enable rendering **
- lpCtx->bCanRender = TRUE;
-
-// ddlogMessage(DDLOG_SYSTEM, "dglCreateContextBuffers succeded\n");
-
-#ifdef GLD_THREADS
- // Release serialized access
- if (glb.bMultiThreaded)
- LeaveCriticalSection(&CriticalSection);
-#endif
-
- return TRUE;
-
-return_with_error:
- // Clean up before returning.
- // This is critical for secondary devices.
-
- lpCtx->bCanRender = FALSE;
-
-#ifdef _USE_GLD3_WGL
- // Destroy the Mesa context
- if (lpCtx->glBuffer)
- _mesa_destroy_framebuffer(lpCtx->glBuffer);
- if (lpCtx->glCtx)
- _mesa_destroy_context(lpCtx->glCtx);
- if (lpCtx->glVis)
- _mesa_destroy_visual(lpCtx->glVis);
-
- // Destroy driver data
- _gldDriver.DestroyDrawable(lpCtx);
-#else
- // Destroy the Mesa context
- if (lpCtx->glBuffer)
- (*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
- if (lpCtx->glCtx)
- (*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
- if (lpCtx->glVis)
- (*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);
-
- RELEASE(lpCtx->m_pvbuf); // Release D3D vertex buffer
- RELEASE(lpCtx->m_vbuf); // Release D3D vertex buffer
-
- if (lpCtx->lpViewport3) {
- if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
- RELEASE(lpCtx->lpViewport3);
- lpCtx->lpViewport3 = NULL;
- }
-
- RELEASE(lpCtx->lpDev3);
- if (lpCtx->lpDepth4) {
- if (lpCtx->lpBack4)
- IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
- else
- IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
- RELEASE(lpCtx->lpDepth4);
- lpCtx->lpDepth4 = NULL;
- }
- RELEASE(lpCtx->lpBack4);
- RELEASE(lpCtx->lpFront4);
- else
- if (lpCtx->bFullscreen) {
- IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
- IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
- }
- RELEASE(lpCtx->lpD3D3);
- RELEASE(lpCtx->lpDD4);
- RELEASE(lpCtx->lpDD1);
-#endif // _USE_GLD3_WGL
-
- lpCtx->bAllocated = FALSE;
-
-#ifdef GLD_THREADS
- // Release serialized access
- if (glb.bMultiThreaded)
- LeaveCriticalSection(&CriticalSection);
-#endif
-
- return FALSE;
-
-#undef DDLOG_CRITICAL_OR_WARN
-}
-
-// ***********************************************************************
-
-HGLRC dglCreateContext(
- HDC a,
- const DGL_pixelFormat *lpPF)
-{
- int i;
- HGLRC hGLRC;
- DGL_ctx* lpCtx;
- static BOOL bWarnOnce = TRUE;
- DWORD dwThreadId = GetCurrentThreadId();
- char szMsg[256];
- HWND hWnd;
- LONG lpfnWndProc;
-
- // Validate license
- if (!dglValidate())
- return NULL;
-
- // Is context state ready ?
- if (!bContextReady)
- return NULL;
-
- ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext for HDC=%X, ThreadId=%X", a, dwThreadId);
-
- // Find next free context.
- // Also ensure that only one Fullscreen context is created at any one time.
- hGLRC = 0; // Default to Not Found
- for (i=0; i<DGL_MAX_CONTEXTS; i++) {
- if (ctxlist[i].bAllocated) {
- if (/*glb.bFullscreen && */ctxlist[i].bFullscreen)
- break;
- } else {
- hGLRC = (HGLRC)(i+1);
- break;
- }
- }
-
- // Bail if no GLRC was found
- if (!hGLRC)
- return NULL;
-
- // Set the context pointer
- lpCtx = dglGetContextAddress(hGLRC);
- // Make sure that context is zeroed before we do anything.
- // MFC and C++ apps call wglCreateContext() and wglDeleteContext() multiple times,
- // even though only one context is ever used by the app, so keep it clean. (DaveM)
- ZeroMemory(lpCtx, sizeof(DGL_ctx));
- lpCtx->bAllocated = TRUE;
- // Flag that buffers need creating on next wglMakeCurrent call.
- lpCtx->bHasBeenCurrent = FALSE;
- lpCtx->lpPF = (DGL_pixelFormat *)lpPF; // cache pixel format
- lpCtx->bCanRender = FALSE;
-
- // Create all the internal resources here, not in dglMakeCurrent().
- // We do a re-size check in dglMakeCurrent in case of re-allocations. (DaveM)
- // We now try context allocations twice, first with video memory,
- // then again with system memory. This is similar to technique
- // used for dglWglResizeBuffers(). (DaveM)
- if (lpCtx->bHasBeenCurrent == FALSE) {
- if (!dglCreateContextBuffers(a, lpCtx, FALSE)) {
- if (glb.bMessageBoxWarnings && bWarnOnce && dwLogging) {
- bWarnOnce = FALSE;
- switch (nContextError) {
- case GLDERR_DDRAW: strcpy(szMsg, szDDrawWarning); break;
- case GLDERR_D3D: strcpy(szMsg, szD3DWarning); break;
- case GLDERR_MEM: strcpy(szMsg, szResourceWarning); break;
- case GLDERR_BPP: strcpy(szMsg, szBPPWarning); break;
- default: strcpy(szMsg, "");
- }
- if (strlen(szMsg))
- MessageBox(NULL, szMsg, "GLDirect", MB_OK | MB_ICONWARNING);
- }
- // Only need to try again if memory error
- if (nContextError == GLDERR_MEM) {
- ddlogPrintf(DDLOG_WARN, "dglCreateContext failed 1st time with video memory");
- }
- else {
- ddlogPrintf(DDLOG_ERROR, "dglCreateContext failed");
- return NULL;
- }
- }
- }
-
- // Now that we have a hWnd, we can intercept the WindowProc.
- hWnd = lpCtx->hWnd;
- if (hWnd) {
- // Only hook individual window handler once if not hooked before.
- lpfnWndProc = GetWindowLong(hWnd, GWL_WNDPROC);
- if (lpfnWndProc != (LONG)dglWndProc) {
- lpCtx->lpfnWndProc = lpfnWndProc;
- SetWindowLong(hWnd, GWL_WNDPROC, (LONG)dglWndProc);
- }
- // Find the parent window of the app too.
- if (glb.hWndActive == NULL) {
- while (hWnd != NULL) {
- glb.hWndActive = hWnd;
- hWnd = GetParent(hWnd);
- }
- // Hook the parent window too.
- lpfnWndProc = GetWindowLong(glb.hWndActive, GWL_WNDPROC);
- if (glb.hWndActive == lpCtx->hWnd)
- glb.lpfnWndProc = lpCtx->lpfnWndProc;
- else if (lpfnWndProc != (LONG)dglWndProc)
- glb.lpfnWndProc = lpfnWndProc;
- if (glb.lpfnWndProc)
- SetWindowLong(glb.hWndActive, GWL_WNDPROC, (LONG)dglWndProc);
- }
- }
-
- ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext succeeded for HGLRC=%d", (int)hGLRC);
-
- return hGLRC;
-}
-
-// ***********************************************************************
-// Make a DirectGL context current
-// Used by wgl functions and dgl functions
-BOOL dglMakeCurrent(
- HDC a,
- HGLRC b)
-{
- int context;
- DGL_ctx* lpCtx;
- HWND hWnd;
- BOOL bNeedResize = FALSE;
- BOOL bWindowChanged, bContextChanged;
- LPDIRECTDRAWCLIPPER lpddClipper;
- DWORD dwThreadId = GetCurrentThreadId();
- LONG lpfnWndProc;
-
- // Validate license
- if (!dglValidate())
- return FALSE;
-
- // Is context state ready ?
- if (!bContextReady)
- return FALSE;
-
- context = (int)b; // This is as a result of STRICT!
- ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: HDC=%X, HGLRC=%d, ThreadId=%X", a, context, dwThreadId);
-
- // If the HGLRC is NULL then make no context current;
- // Ditto if the HDC is NULL either. (DaveM)
- if (context == 0 || a == 0) {
- // Corresponding Mesa operation
-#ifdef _USE_GLD3_WGL
- _mesa_make_current(NULL, NULL);
-#else
- (*mesaFuncs.gl_make_current)(NULL, NULL);
-#endif
- dglSetCurrentContext(0);
- return TRUE;
- }
-
- // Make sure the HGLRC is in range
- if ((context > DGL_MAX_CONTEXTS) || (context < 0)) {
- ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: HGLRC out of range\n");
- return FALSE;
- }
-
- // Find address of context and make sure that it has been allocated
- lpCtx = dglGetContextAddress(b);
- if (!lpCtx->bAllocated) {
- ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: Context not allocated\n");
-// return FALSE;
- return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
- }
-
-#ifdef GLD_THREADS
- // Serialize access to DirectDraw or DDS operations
- if (glb.bMultiThreaded)
- EnterCriticalSection(&CriticalSection);
-#endif
-
- // Check if window has changed
- hWnd = (a != lpCtx->hDC) ? WindowFromDC(a) : lpCtx->hWnd;
- bWindowChanged = (hWnd != lpCtx->hWnd) ? TRUE : FALSE;
- bContextChanged = (b != dglGetCurrentContext()) ? TRUE : FALSE;
-
- // If the window has changed, make sure the clipper is updated. (DaveM)
- if (glb.bDirectDrawPersistant && !lpCtx->bFullscreen && (bWindowChanged || bContextChanged)) {
- lpCtx->hWnd = hWnd;
-#ifndef _USE_GLD3_WGL
- IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
- IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
- IDirectDrawClipper_Release(lpddClipper);
-#endif // _USE_GLD3_WGL
- }
-
- // Make sure hDC and hWnd is current. (DaveM)
- // Obtain the dimensions of the rendering window
- lpCtx->hDC = a; // Cache DC
- lpCtx->hWnd = hWnd;
- hWndLastActive = hWnd;
-
- // Check for non-window DC = memory DC ?
- if (hWnd == NULL) {
- if (GetClipBox(a, &lpCtx->rcScreenRect) == ERROR) {
- ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglMakeCurrent\n");
- SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
- }
- }
- else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
- ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglMakeCurrent\n");
- SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
- }
- // Check if buffers need to be re-sized;
- // If so, wait until Mesa GL stuff is setup before re-sizing;
- if (lpCtx->dwWidth != lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left ||
- lpCtx->dwHeight != lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top)
- bNeedResize = TRUE;
-
- // Now we can update our globals
- dglSetCurrentContext(b);
-
- // Corresponding Mesa operation
-#ifdef _USE_GLD3_WGL
- _mesa_make_current(lpCtx->glCtx, lpCtx->glBuffer);
- lpCtx->glCtx->Driver.UpdateState(lpCtx->glCtx, _NEW_ALL);
- if (bNeedResize) {
- // Resize buffers (Note Mesa GL needs to be setup beforehand);
- // Resize Mesa internal buffer too via glViewport() command,
- // which subsequently calls dglWglResizeBuffers() too.
- lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
- lpCtx->bHasBeenCurrent = TRUE;
- }
-#else
- (*mesaFuncs.gl_make_current)(lpCtx->glCtx, lpCtx->glBuffer);
-
- dglSetupDDPointers(lpCtx->glCtx);
-
- // Insure DirectDraw surfaces fit current window DC
- if (bNeedResize) {
- // Resize buffers (Note Mesa GL needs to be setup beforehand);
- // Resize Mesa internal buffer too via glViewport() command,
- // which subsequently calls dglWglResizeBuffers() too.
- (*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
- lpCtx->bHasBeenCurrent = TRUE;
- }
-#endif // _USE_GLD3_WGL
- ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: width = %d, height = %d", lpCtx->dwWidth, lpCtx->dwHeight);
-
- // We have to clear D3D back buffer and render state if emulated front buffering
- // for different window (but not context) like in Solid Edge.
- if (glb.bDirectDrawPersistant && glb.bPersistantBuffers
- && (bWindowChanged /* || bContextChanged */) && lpCtx->EmulateSingle) {
-#ifdef _USE_GLD3_WGL
-// IDirect3DDevice8_EndScene(lpCtx->pDev);
-// lpCtx->bSceneStarted = FALSE;
- lpCtx->glCtx->Driver.Clear(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
- GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
-#else
- IDirect3DDevice3_EndScene(lpCtx->lpDev3);
- lpCtx->bSceneStarted = FALSE;
- dglClearD3D(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
- GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
-#endif // _USE_GLD3_WGL
- }
-
- // The first time we call MakeCurrent we set the initial viewport size
- if (lpCtx->bHasBeenCurrent == FALSE)
-#ifdef _USE_GLD3_WGL
- lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
-#else
- (*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
-#endif // _USE_GLD3_WGL
- lpCtx->bHasBeenCurrent = TRUE;
-
-#ifdef GLD_THREADS
- // Release serialized access
- if (glb.bMultiThreaded)
- LeaveCriticalSection(&CriticalSection);
-#endif
-
- return TRUE;
-}
-
-// ***********************************************************************
-
-BOOL dglDeleteContext(
- HGLRC a)
-{
- DGL_ctx* lpCtx;
- DWORD dwThreadId = GetCurrentThreadId();
- char argstr[256];
-
-#if 0 // We have enough trouble throwing exceptions as it is... (DaveM)
- // Validate license
- if (!dglValidate())
- return FALSE;
-#endif
-
- // Is context state ready ?
- if (!bContextReady)
- return FALSE;
-
- ddlogPrintf(DDLOG_SYSTEM, "dglDeleteContext: Deleting context HGLRC=%d, ThreadId=%X", (int)a, dwThreadId);
-
- // Make sure the HGLRC is in range
- if (((int) a> DGL_MAX_CONTEXTS) || ((int)a < 0)) {
- ddlogMessage(DDLOG_ERROR, "dglDeleteCurrent: HGLRC out of range\n");
- return FALSE;
- }
-
- // Make sure context is valid
- lpCtx = dglGetContextAddress(a);
- if (!lpCtx->bAllocated) {
- ddlogPrintf(DDLOG_WARN, "Tried to delete unallocated context HGLRC=%d", (int)a);
-// return FALSE;
- return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
- }
-
- // Make sure context is de-activated
- if (a == dglGetCurrentContext()) {
- ddlogPrintf(DDLOG_WARN, "dglDeleteContext: context HGLRC=%d still active", (int)a);
- dglMakeCurrent(NULL, NULL);
- }
-
-#ifdef GLD_THREADS
- // Serialize access to DirectDraw or DDS operations
- if (glb.bMultiThreaded)
- EnterCriticalSection(&CriticalSection);
-#endif
-
- // We are about to destroy all Direct3D objects.
- // Therefore we must disable rendering
- lpCtx->bCanRender = FALSE;
-
- // This exception handler was installed to catch some
- // particularly nasty apps. Console apps that call exit()
- // fall into this catagory (i.e. Win32 Glut).
-
- // VC cannot successfully implement multiple exception handlers
- // if more than one exception occurs. Therefore reverting back to
- // single exception handler as Keith originally had it. (DaveM)
-
-#define WARN_MESSAGE(p) strcpy(argstr, (#p));
-#define SAFE_RELEASE(p) WARN_MESSAGE(p); RELEASE(p);
-
-__try {
-#ifdef _USE_GLD3_WGL
- WARN_MESSAGE(gl_destroy_framebuffer);
- if (lpCtx->glBuffer)
- _mesa_destroy_framebuffer(lpCtx->glBuffer);
- WARN_MESSAGE(gl_destroy_context);
- if (lpCtx->glCtx)
- _mesa_destroy_context(lpCtx->glCtx);
- WARN_MESSAGE(gl_destroy_visual);
- if (lpCtx->glVis)
- _mesa_destroy_visual(lpCtx->glVis);
-
- _gldDriver.DestroyDrawable(lpCtx);
-#else
- // Destroy the Mesa context
- WARN_MESSAGE(gl_destroy_framebuffer);
- if (lpCtx->glBuffer)
- (*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
- WARN_MESSAGE(gl_destroy_context);
- if (lpCtx->glCtx)
- (*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
- WARN_MESSAGE(gl_destroy_visual);
- if (lpCtx->glVis)
- (*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);
-
- SAFE_RELEASE(lpCtx->m_pvbuf); // release D3D vertex buffer
- SAFE_RELEASE(lpCtx->m_vbuf); // release D3D vertex buffer
-
- // Delete the global palette
- SAFE_RELEASE(lpCtx->lpGlobalPalette);
-
- // Clean up.
- if (lpCtx->lpViewport3) {
- if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
- SAFE_RELEASE(lpCtx->lpViewport3);
- lpCtx->lpViewport3 = NULL;
- }
-
- SAFE_RELEASE(lpCtx->lpDev3);
- if (lpCtx->lpDepth4) {
- if (lpCtx->lpBack4)
- IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
- else
- IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
- SAFE_RELEASE(lpCtx->lpDepth4);
- lpCtx->lpDepth4 = NULL;
- }
- SAFE_RELEASE(lpCtx->lpBack4);
- SAFE_RELEASE(lpCtx->lpFront4);
- if (lpCtx->bFullscreen) {
- IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
- IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
- }
- SAFE_RELEASE(lpCtx->lpD3D3);
- SAFE_RELEASE(lpCtx->lpDD4);
- SAFE_RELEASE(lpCtx->lpDD1);
-#endif // _ULSE_GLD3_WGL
-
-}
-__except(EXCEPTION_EXECUTE_HANDLER) {
- ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContext: %s", argstr);
-}
-
- // Restore the window message handler because this context may be used
- // again by another window with a *different* message handler. (DaveM)
- if (lpCtx->lpfnWndProc) {
- SetWindowLong(lpCtx->hWnd, GWL_WNDPROC, (LONG)lpCtx->lpfnWndProc);
- lpCtx->lpfnWndProc = (LONG)NULL;
- }
-
- lpCtx->bAllocated = FALSE; // This context is now free for use
-
-#ifdef GLD_THREADS
- // Release serialized access
- if (glb.bMultiThreaded)
- LeaveCriticalSection(&CriticalSection);
-#endif
-
- return TRUE;
-}
-
-// ***********************************************************************
-
-BOOL dglSwapBuffers(
- HDC hDC)
-{
- RECT rSrcRect; // Source rectangle
- RECT rDstRect; // Destination rectangle
- POINT pt;
- HRESULT hResult;
-
- DDBLTFX bltFX;
- DWORD dwBlitFlags;
- DDBLTFX *lpBltFX;
-
-// DWORD dwThreadId = GetCurrentThreadId();
- HGLRC hGLRC = dglGetCurrentContext();
- DGL_ctx *lpCtx = dglGetContextAddress(hGLRC);
- HWND hWnd;
-
- HDC hDCAux; // for memory DC
- int x,y,w,h; // for memory DC BitBlt
-
-#if 0 // Perhaps not a good idea. Called too often. KH
- // Validate license
- if (!dglValidate())
- return FALSE;
-#endif
-
- if (!lpCtx) {
- return TRUE; //FALSE; // No current context
- }
-
- if (!lpCtx->bCanRender) {
- // Don't return false else some apps will bail.
- return TRUE;
- }
-
- hWnd = lpCtx->hWnd;
- if (hDC != lpCtx->hDC) {
- ddlogPrintf(DDLOG_WARN, "dglSwapBuffers: HDC=%X does not match HDC=%X for HGLRC=%d", hDC, lpCtx->hDC, hGLRC);
- hWnd = WindowFromDC(hDC);
- }
-
-#ifndef _USE_GLD3_WGL
- // Ensure that the surfaces exist before we tell
- // the device to render to them.
- IDirectDraw4_RestoreAllSurfaces(lpCtx->lpDD4);
-
- // Make sure that the vertex caches have been emptied
-// dglStateChange(lpCtx);
-
- // Some OpenGL programs don't issue a glFinish - check for it here.
- if (lpCtx->bSceneStarted) {
- IDirect3DDevice3_EndScene(lpCtx->lpDev3);
- lpCtx->bSceneStarted = FALSE;
- }
-#endif
-
-#if 0
- // If the calling app is not active then we don't need to Blit/Flip.
- // We can therefore simply return TRUE.
- if (!glb.bAppActive)
- return TRUE;
- // Addendum: This is WRONG! We should bail if the app is *minimized*,
- // not merely if the app is just plain 'not active'.
- // KeithH, 27/May/2000.
-#endif
-
- // Check for non-window DC = memory DC ?
- if (hWnd == NULL) {
- if (GetClipBox(hDC, &rSrcRect) == ERROR)
- return TRUE;
- // Use GDI BitBlt instead from compatible DirectDraw DC
- x = rSrcRect.left;
- y = rSrcRect.top;
- w = rSrcRect.right - rSrcRect.left;
- h = rSrcRect.bottom - rSrcRect.top;
-
- // Ack. DX8 does not have a GetDC() function...
- // TODO: Defer to DX7 or DX9 drivers... (DaveM)
- return TRUE;
- }
-
- // Bail if window client region is not drawable, like in Solid Edge
- if (!IsWindow(hWnd) /* || !IsWindowVisible(hWnd) */ || !GetClientRect(hWnd, &rSrcRect))
- return TRUE;
-
-#ifdef GLD_THREADS
- // Serialize access to DirectDraw or DDS operations
- if (glb.bMultiThreaded)
- EnterCriticalSection(&CriticalSection);
-#endif
-
-#ifdef _USE_GLD3_WGL
- // Notify Mesa of impending swap, so Mesa can flush internal buffers.
- _mesa_notifySwapBuffers(lpCtx->glCtx);
- // Now perform driver buffer swap
- _gldDriver.SwapBuffers(lpCtx, hDC, hWnd);
-#else
- if (lpCtx->bFullscreen) {
- // Sync with retrace if required
- if (glb.bWaitForRetrace) {
- IDirectDraw4_WaitForVerticalBlank(
- lpCtx->lpDD4,
- DDWAITVB_BLOCKBEGIN,
- 0);
- }
-
- // Perform the fullscreen flip
- TRY(IDirectDrawSurface4_Flip(
- lpCtx->lpFront4,
- NULL,
- DDFLIP_WAIT),
- "dglSwapBuffers: Flip");
- } else {
- // Calculate current window position and size
- pt.x = pt.y = 0;
- ClientToScreen(hWnd, &pt);
- GetClientRect(hWnd, &rDstRect);
- if (rDstRect.right > lpCtx->dwModeWidth)
- rDstRect.right = lpCtx->dwModeWidth;
- if (rDstRect.bottom > lpCtx->dwModeHeight)
- rDstRect.bottom = lpCtx->dwModeHeight;
- OffsetRect(&rDstRect, pt.x, pt.y);
- rSrcRect.left = rSrcRect.top = 0;
- rSrcRect.right = lpCtx->dwWidth;
- rSrcRect.bottom = lpCtx->dwHeight;
- if (rSrcRect.right > lpCtx->dwModeWidth)
- rSrcRect.right = lpCtx->dwModeWidth;
- if (rSrcRect.bottom > lpCtx->dwModeHeight)
- rSrcRect.bottom = lpCtx->dwModeHeight;
-
- if (glb.bWaitForRetrace) {
- // Sync the blit to the vertical retrace
- ZeroMemory(&bltFX, sizeof(bltFX));
- bltFX.dwSize = sizeof(bltFX);
- bltFX.dwDDFX = DDBLTFX_NOTEARING;
- dwBlitFlags = DDBLT_WAIT | DDBLT_DDFX;
- lpBltFX = &bltFX;
- } else {
- dwBlitFlags = DDBLT_WAIT;
- lpBltFX = NULL;
- }
-
- // Perform the actual blit
- TRY(IDirectDrawSurface4_Blt(
- lpCtx->lpFront4,
- &rDstRect,
- lpCtx->lpBack4, // Blit source
- &rSrcRect,
- dwBlitFlags,
- lpBltFX),
- "dglSwapBuffers: Blt");
- }
-#endif // _USE_GLD3_WGL
-
-#ifdef GLD_THREADS
- // Release serialized access
- if (glb.bMultiThreaded)
- LeaveCriticalSection(&CriticalSection);
-#endif
-
- // TODO: Re-instate rendering bitmap snapshot feature??? (DaveM)
-
- // Render frame is completed
- ValidateRect(hWnd, NULL);
- lpCtx->bFrameStarted = FALSE;
-
- return TRUE;
-}
-
-// ***********************************************************************
+/****************************************************************************
+*
+* Mesa 3-D graphics library
+* Direct3D Driver Interface
+*
+* ========================================================================
+*
+* Copyright (C) 1991-2004 SciTech Software, Inc. 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
+* SCITECH SOFTWARE INC 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.
+*
+* ======================================================================
+*
+* Language: ANSI C
+* Environment: Windows 9x (Win32)
+*
+* Description: Context handling.
+*
+****************************************************************************/
+
+#include "dglcontext.h"
+
+// Get compile errors without this. KeithH
+//#include "scitech.h" // ibool, etc.
+
+#ifdef _USE_GLD3_WGL
+#include "gld_driver.h"
+
+extern void _gld_mesa_warning(struct gl_context *, char *);
+extern void _gld_mesa_fatal(struct gl_context *, char *);
+#endif // _USE_GLD3_WGL
+
+// TODO: Clean out old DX6-specific code from GLD 2.x CAD driver
+// if it is no longer being built as part of GLDirect. (DaveM)
+
+// ***********************************************************************
+
+#define GLDERR_NONE 0
+#define GLDERR_MEM 1
+#define GLDERR_DDRAW 2
+#define GLDERR_D3D 3
+#define GLDERR_BPP 4
+
+char szResourceWarning[] =
+"GLDirect does not have enough video memory resources\n"
+"to support the requested OpenGL rendering context.\n\n"
+"You may have to reduce the current display resolution\n"
+"to obtain satisfactory OpenGL performance.\n";
+
+char szDDrawWarning[] =
+"GLDirect is unable to initialize DirectDraw for the\n"
+"requested OpenGL rendering context.\n\n"
+"You will have to check the DirectX control panel\n"
+"for further information.\n";
+
+char szD3DWarning[] =
+"GLDirect is unable to initialize Direct3D for the\n"
+"requested OpenGL rendering context.\n\n"
+"You may have to change the display mode resolution\n"
+"color depth or check the DirectX control panel for\n"
+"further information.\n";
+
+char szBPPWarning[] =
+"GLDirect is unable to use the selected color depth for\n"
+"the requested OpenGL rendering context.\n\n"
+"You will have to change the display mode resolution\n"
+"color depth with the Display Settings control panel.\n";
+
+int nContextError = GLDERR_NONE;
+
+// ***********************************************************************
+
+#define VENDORID_ATI 0x1002
+
+static DWORD devATIRagePro[] = {
+ 0x4742, // 3D RAGE PRO BGA AGP 1X/2X
+ 0x4744, // 3D RAGE PRO BGA AGP 1X only
+ 0x4749, // 3D RAGE PRO BGA PCI 33 MHz
+ 0x4750, // 3D RAGE PRO PQFP PCI 33 MHz
+ 0x4751, // 3D RAGE PRO PQFP PCI 33 MHz limited 3D
+ 0x4C42, // 3D RAGE LT PRO BGA-312 AGP 133 MHz
+ 0x4C44, // 3D RAGE LT PRO BGA-312 AGP 66 MHz
+ 0x4C49, // 3D RAGE LT PRO BGA-312 PCI 33 MHz
+ 0x4C50, // 3D RAGE LT PRO BGA-256 PCI 33 MHz
+ 0x4C51, // 3D RAGE LT PRO BGA-256 PCI 33 MHz limited 3D
+};
+
+static DWORD devATIRageIIplus[] = {
+ 0x4755, // 3D RAGE II+
+ 0x4756, // 3D RAGE IIC PQFP PCI
+ 0x4757, // 3D RAGE IIC BGA AGP
+ 0x475A, // 3D RAGE IIC PQFP AGP
+ 0x4C47, // 3D RAGE LT-G
+};
+
+// ***********************************************************************
+
+#ifndef _USE_GLD3_WGL
+extern DGL_mesaFuncs mesaFuncs;
+#endif
+
+extern DWORD dwLogging;
+
+#ifdef GLD_THREADS
+#pragma message("compiling DGLCONTEXT.C vars for multi-threaded support")
+CRITICAL_SECTION CriticalSection; // for serialized access
+DWORD dwTLSCurrentContext = 0xFFFFFFFF; // TLS index for current context
+DWORD dwTLSPixelFormat = 0xFFFFFFFF; // TLS index for current pixel format
+#endif
+HGLRC iCurrentContext = 0; // Index of current context (static)
+BOOL bContextReady = FALSE; // Context state ready ?
+
+DGL_ctx ctxlist[DGL_MAX_CONTEXTS]; // Context list
+
+// ***********************************************************************
+
+static BOOL bHaveWin95 = FALSE;
+static BOOL bHaveWinNT = FALSE;
+static BOOL bHaveWin2K = FALSE;
+
+/****************************************************************************
+REMARKS:
+Detect the installed OS type.
+****************************************************************************/
+static void DetectOS(void)
+{
+ OSVERSIONINFO VersionInformation;
+ LPOSVERSIONINFO lpVersionInformation = &VersionInformation;
+
+ VersionInformation.dwOSVersionInfoSize = sizeof(VersionInformation);
+
+ GetVersionEx(lpVersionInformation);
+
+ switch (VersionInformation.dwPlatformId) {
+ case VER_PLATFORM_WIN32_WINDOWS:
+ bHaveWin95 = TRUE;
+ bHaveWinNT = FALSE;
+ bHaveWin2K = FALSE;
+ break;
+ case VER_PLATFORM_WIN32_NT:
+ bHaveWin95 = FALSE;
+ if (VersionInformation.dwMajorVersion <= 4) {
+ bHaveWinNT = TRUE;
+ bHaveWin2K = FALSE;
+ }
+ else {
+ bHaveWinNT = FALSE;
+ bHaveWin2K = TRUE;
+ }
+ break;
+ case VER_PLATFORM_WIN32s:
+ bHaveWin95 = FALSE;
+ bHaveWinNT = FALSE;
+ bHaveWin2K = FALSE;
+ break;
+ }
+}
+
+// ***********************************************************************
+
+HWND hWndEvent = NULL; // event monitor window
+HWND hWndLastActive = NULL; // last active client window
+LONG __stdcall GLD_EventWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);
+
+// ***********************************************************************
+
+// Checks if the HGLRC is valid in range of context list.
+BOOL dglIsValidContext(
+ HGLRC a)
+{
+ return ((int)a > 0 && (int)a <= DGL_MAX_CONTEXTS);
+}
+
+// ***********************************************************************
+
+// Convert a HGLRC to a pointer into the context list.
+DGL_ctx* dglGetContextAddress(
+ const HGLRC a)
+{
+ if (dglIsValidContext(a))
+ return &ctxlist[(int)a-1];
+ return NULL;
+}
+
+// ***********************************************************************
+
+// Return the current HGLRC (however it may be stored for multi-threading).
+HGLRC dglGetCurrentContext(void)
+{
+#ifdef GLD_THREADS
+ HGLRC hGLRC;
+ // load from thread-specific instance
+ if (glb.bMultiThreaded) {
+ // protect against calls from arbitrary threads
+ __try {
+ hGLRC = (HGLRC)TlsGetValue(dwTLSCurrentContext);
+ }
+ __except(EXCEPTION_EXECUTE_HANDLER) {
+ hGLRC = iCurrentContext;
+ }
+ }
+ // load from global static var
+ else {
+ hGLRC = iCurrentContext;
+ }
+ return hGLRC;
+#else
+ return iCurrentContext;
+#endif
+}
+
+// ***********************************************************************
+
+// Set the current HGLRC (however it may be stored for multi-threading).
+void dglSetCurrentContext(HGLRC hGLRC)
+{
+#ifdef GLD_THREADS
+ // store in thread-specific instance
+ if (glb.bMultiThreaded) {
+ // protect against calls from arbitrary threads
+ __try {
+ TlsSetValue(dwTLSCurrentContext, (LPVOID)hGLRC);
+ }
+ __except(EXCEPTION_EXECUTE_HANDLER) {
+ iCurrentContext = hGLRC;
+ }
+ }
+ // store in global static var
+ else {
+ iCurrentContext = hGLRC;
+ }
+#else
+ iCurrentContext = hGLRC;
+#endif
+}
+
+// ***********************************************************************
+
+// Return the current HDC only for a currently active HGLRC.
+HDC dglGetCurrentDC(void)
+{
+ HGLRC hGLRC;
+ DGL_ctx* lpCtx;
+
+ hGLRC = dglGetCurrentContext();
+ if (hGLRC) {
+ lpCtx = dglGetContextAddress(hGLRC);
+ return lpCtx->hDC;
+ }
+ return 0;
+}
+
+// ***********************************************************************
+
+void dglInitContextState()
+{
+ int i;
+ WNDCLASS wc;
+
+#ifdef GLD_THREADS
+ // Allocate thread local storage indexes for current context and pixel format
+ dwTLSCurrentContext = TlsAlloc();
+ dwTLSPixelFormat = TlsAlloc();
+#endif
+
+ dglSetCurrentContext(NULL); // No current rendering context
+
+ // Clear all context data
+ ZeroMemory(ctxlist, sizeof(ctxlist[0]) * DGL_MAX_CONTEXTS);
+
+ for (i=0; i<DGL_MAX_CONTEXTS; i++)
+ ctxlist[i].bAllocated = FALSE; // Flag context as unused
+
+ // This section of code crashes the dll in circumstances where the app
+ // creates and destroys contexts.
+/*
+ // Register the class for our event monitor window
+ wc.style = 0;
+ wc.lpfnWndProc = GLD_EventWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = GetModuleHandle(NULL);
+ wc.hIcon = LoadIcon(GetModuleHandle(NULL), IDI_APPLICATION);
+ wc.hCursor = LoadCursor(NULL, IDC_ARROW);
+ wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = "GLDIRECT";
+ RegisterClass(&wc);
+
+ // Create the non-visible window to monitor all broadcast messages
+ hWndEvent = CreateWindowEx(
+ WS_EX_TOOLWINDOW,"GLDIRECT","GLDIRECT",WS_POPUP,
+ 0,0,0,0,
+ NULL,NULL,GetModuleHandle(NULL),NULL);
+*/
+
+#ifdef GLD_THREADS
+ // Create a critical section object for serializing access to
+ // DirectDraw and DDStereo create/destroy functions in multiple threads
+ if (glb.bMultiThreaded)
+ InitializeCriticalSection(&CriticalSection);
+#endif
+
+ // Context state is now initialized and ready
+ bContextReady = TRUE;
+}
+
+// ***********************************************************************
+
+void dglDeleteContextState()
+{
+ int i;
+ static BOOL bOnceIsEnough = FALSE;
+
+ // Only call once, from either DGL_exitDriver(), or DLL_PROCESS_DETACH
+ if (bOnceIsEnough)
+ return;
+ bOnceIsEnough = TRUE;
+
+ for (i=0; i<DGL_MAX_CONTEXTS; i++) {
+ if (ctxlist[i].bAllocated == TRUE) {
+ ddlogPrintf(DDLOG_WARN, "** Context %i not deleted - cleaning up.", (i+1));
+ dglDeleteContext((HGLRC)(i+1));
+ }
+ }
+
+ // Context state is no longer ready
+ bContextReady = FALSE;
+
+ // If executed when DLL unloads, DDraw objects may be invalid.
+ // So catch any page faults with this exception handler.
+__try {
+
+ // Release final DirectDraw interfaces
+ if (glb.bDirectDrawPersistant) {
+// RELEASE(glb.lpGlobalPalette);
+// RELEASE(glb.lpDepth4);
+// RELEASE(glb.lpBack4);
+// RELEASE(glb.lpPrimary4);
+// RELEASE(glb.lpDD4);
+ }
+}
+__except(EXCEPTION_EXECUTE_HANDLER) {
+ ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContextState.");
+}
+
+ // Destroy our event monitor window
+ if (hWndEvent) {
+ DestroyWindow(hWndEvent);
+ hWndEvent = hWndLastActive = NULL;
+ }
+
+#ifdef GLD_THREADS
+ // Destroy the critical section object
+ if (glb.bMultiThreaded)
+ DeleteCriticalSection(&CriticalSection);
+
+ // Release thread local storage indexes for current HGLRC and pixel format
+ TlsFree(dwTLSPixelFormat);
+ TlsFree(dwTLSCurrentContext);
+#endif
+}
+
+// ***********************************************************************
+
+// Application Window message handler interception
+static LONG __stdcall dglWndProc(
+ HWND hwnd,
+ UINT msg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ DGL_ctx* lpCtx = NULL;
+ LONG lpfnWndProc = 0L;
+ int i;
+ HGLRC hGLRC;
+ RECT rect;
+ PAINTSTRUCT ps;
+ BOOL bQuit = FALSE;
+ BOOL bMain = FALSE;
+ LONG rc;
+
+ // Get the window's message handler *before* it is unhooked in WM_DESTROY
+
+ // Is this the main window?
+ if (hwnd == glb.hWndActive) {
+ bMain = TRUE;
+ lpfnWndProc = glb.lpfnWndProc;
+ }
+ // Search for DGL context matching window handle
+ for (i=0; i<DGL_MAX_CONTEXTS; i++) {
+ if (ctxlist[i].hWnd == hwnd) {
+ lpCtx = &ctxlist[i];
+ lpfnWndProc = lpCtx->lpfnWndProc;
+ break;
+ }
+ }
+ // Not one of ours...
+ if (!lpfnWndProc)
+ return DefWindowProc(hwnd, msg, wParam, lParam);
+
+ // Intercept messages amd process *before* passing on to window
+ switch (msg) {
+#ifdef _USE_GLD3_WGL
+ case WM_DISPLAYCHANGE:
+ glb.bPixelformatsDirty = TRUE;
+ break;
+#endif
+ case WM_ACTIVATEAPP:
+ glb.bAppActive = (BOOL)wParam;
+ ddlogPrintf(DDLOG_INFO, "Calling app has been %s", glb.bAppActive ? "activated" : "de-activated");
+ break;
+ case WM_ERASEBKGND:
+ // Eat the GDI erase event for the GL window
+ if (!lpCtx || !lpCtx->bHasBeenCurrent)
+ break;
+ lpCtx->bGDIEraseBkgnd = TRUE;
+ return TRUE;
+ case WM_PAINT:
+ // Eat the invalidated update region if render scene is in progress
+ if (!lpCtx || !lpCtx->bHasBeenCurrent)
+ break;
+ if (lpCtx->bFrameStarted) {
+ if (GetUpdateRect(hwnd, &rect, FALSE)) {
+ BeginPaint(hwnd, &ps);
+ EndPaint(hwnd, &ps);
+ ValidateRect(hwnd, &rect);
+ return TRUE;
+ }
+ }
+ break;
+ }
+ // Call the appropriate window message handler
+ rc = CallWindowProc((WNDPROC)lpfnWndProc, hwnd, msg, wParam, lParam);
+
+ // Intercept messages and process *after* passing on to window
+ switch (msg) {
+ case WM_QUIT:
+ case WM_DESTROY:
+ bQuit = TRUE;
+ if (lpCtx && lpCtx->bAllocated) {
+ ddlogPrintf(DDLOG_WARN, "WM_DESTROY detected for HWND=%X, HDC=%X, HGLRC=%d", hwnd, lpCtx->hDC, i+1);
+ dglDeleteContext((HGLRC)(i+1));
+ }
+ break;
+#if 0
+ case WM_SIZE:
+ // Resize surfaces to fit window but not viewport (in case app did not bother)
+ if (!lpCtx || !lpCtx->bHasBeenCurrent)
+ break;
+ w = LOWORD(lParam);
+ h = HIWORD(lParam);
+ if (lpCtx->dwWidth < w || lpCtx->dwHeight < h) {
+ if (!dglWglResizeBuffers(lpCtx->glCtx, TRUE))
+ dglWglResizeBuffers(lpCtx->glCtx, FALSE);
+ }
+ break;
+#endif
+ }
+
+ // If the main window is quitting, then so should we...
+ if (bMain && bQuit) {
+ ddlogPrintf(DDLOG_SYSTEM, "shutting down after WM_DESTROY detected for main HWND=%X", hwnd);
+ dglDeleteContextState();
+ dglExitDriver();
+ }
+
+ return rc;
+}
+
+// ***********************************************************************
+
+// Driver Window message handler
+static LONG __stdcall GLD_EventWndProc(
+ HWND hwnd,
+ UINT msg,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ switch (msg) {
+ // May be sent by splash screen dialog on exit
+ case WM_ACTIVATE:
+ if (LOWORD(wParam) == WA_ACTIVE && glb.hWndActive) {
+ SetForegroundWindow(glb.hWndActive);
+ return 0;
+ }
+ break;
+ }
+ return DefWindowProc(hwnd, msg, wParam, lParam);
+}
+
+// ***********************************************************************
+
+// Intercepted Keyboard handler for detecting hot keys.
+LRESULT CALLBACK dglKeyProc(
+ int code,
+ WPARAM wParam,
+ LPARAM lParam)
+{
+ HWND hWnd, hWndFrame;
+ HGLRC hGLRC = NULL;
+ DGL_ctx* lpCtx = NULL;
+ int cmd = 0, dx1 = 0, dx2 = 0, i;
+ static BOOL bAltPressed = FALSE;
+ static BOOL bCtrlPressed = FALSE;
+ static BOOL bShiftPressed = FALSE;
+ RECT r, rf, rc;
+ POINT pt;
+ BOOL bForceReshape = FALSE;
+
+ return CallNextHookEx(hKeyHook, code, wParam, lParam);
+}
+
+// ***********************************************************************
+
+HWND hWndMatch;
+
+// Window handle enumeration procedure.
+BOOL CALLBACK dglEnumChildProc(
+ HWND hWnd,
+ LPARAM lParam)
+{
+ RECT rect;
+
+ // Find window handle with matching client rect.
+ GetClientRect(hWnd, &rect);
+ if (EqualRect(&rect, (RECT*)lParam)) {
+ hWndMatch = hWnd;
+ return FALSE;
+ }
+ // Continue with next child window.
+ return TRUE;
+}
+
+// ***********************************************************************
+
+// Find window handle with matching client rect.
+HWND dglFindWindowRect(
+ RECT* pRect)
+{
+ hWndMatch = NULL;
+ EnumChildWindows(GetForegroundWindow(), dglEnumChildProc, (LPARAM)pRect);
+ return hWndMatch;
+}
+
+// ***********************************************************************
+#ifndef _USE_GLD3_WGL
+void dglChooseDisplayMode(
+ DGL_ctx *lpCtx)
+{
+ // Note: Choose an exact match if possible.
+
+ int i;
+ DWORD area;
+ DWORD bestarea;
+ DDSURFACEDESC2 *lpDDSD = NULL; // Mode list pointer
+ DDSURFACEDESC2 *lpBestDDSD = NULL; // Pointer to best
+
+ lpDDSD = glb.lpDisplayModes;
+ for (i=0; i<glb.nDisplayModeCount; i++, lpDDSD++) {
+ if ((lpDDSD->dwWidth == lpCtx->dwWidth) &&
+ (lpDDSD->dwHeight == lpCtx->dwHeight))
+ goto matched; // Mode has been exactly matched
+ // Choose modes that are larger in both dimensions than
+ // the window, but smaller in area than the current best.
+ if ( (lpDDSD->dwWidth >= lpCtx->dwWidth) &&
+ (lpDDSD->dwHeight >= lpCtx->dwHeight))
+ {
+ if (lpBestDDSD == NULL) {
+ lpBestDDSD = lpDDSD;
+ bestarea = lpDDSD->dwWidth * lpDDSD->dwHeight;
+ continue;
+ }
+ area = lpDDSD->dwWidth * lpDDSD->dwHeight;
+ if (area < bestarea) {
+ lpBestDDSD = lpDDSD;
+ bestarea = area;
+ }
+ }
+ }
+
+ // Safety check
+ if (lpBestDDSD == NULL) {
+ ddlogMessage(DDLOG_CRITICAL, "dglChooseDisplayMode");
+ return;
+ }
+
+ lpCtx->dwModeWidth = lpBestDDSD->dwWidth;
+ lpCtx->dwModeHeight = lpBestDDSD->dwHeight;
+matched:
+ ddlogPrintf(DDLOG_INFO, "Matched (%ldx%ld) to (%ldx%ld)",
+ lpCtx->dwWidth, lpCtx->dwHeight, lpCtx->dwModeWidth, lpCtx->dwModeHeight);
+}
+#endif // _USE_GLD3_WGL
+// ***********************************************************************
+
+static BOOL IsDevice(
+ DWORD *lpDeviceIdList,
+ DWORD dwDeviceId,
+ int count)
+{
+ int i;
+
+ for (i=0; i<count; i++)
+ if (dwDeviceId == lpDeviceIdList[i])
+ return TRUE;
+
+ return FALSE;
+}
+
+// ***********************************************************************
+
+void dglTestForBrokenCards(
+ DGL_ctx *lpCtx)
+{
+#ifndef _GLD3
+ DDDEVICEIDENTIFIER dddi; // DX6 device identifier
+
+ // Sanity check.
+ if (lpCtx == NULL) {
+ // Testing for broken cards is sensitive area, so we don't want
+ // anything saying "broken cards" in the error message. ;)
+ ddlogMessage(DDLOG_ERROR, "Null context passed to TFBC\n");
+ return;
+ }
+
+ if (lpCtx->lpDD4 == NULL) {
+ // Testing for broken cards is sensitive area, so we don't want
+ // anything saying "broken cards" in the error message. ;)
+ ddlogMessage(DDLOG_ERROR, "Null DD4 passed to TFBC\n");
+ return;
+ }
+
+ // Microsoft really fucked up with the GetDeviceIdentifier function
+ // on Windows 2000, since it locks up on stock driers on the CD. Updated
+ // drivers from vendors appear to work, but we can't identify the drivers
+ // without this function!!! For now we skip these tests on Windows 2000.
+ if ((GetVersion() & 0x80000000UL) == 0)
+ return;
+
+ // Obtain device info
+ if (FAILED(IDirectDraw4_GetDeviceIdentifier(lpCtx->lpDD4, &dddi, 0)))
+ return;
+
+ // Useful info. Log it.
+ ddlogPrintf(DDLOG_INFO, "DirectDraw: VendorId=0x%x, DeviceId=0x%x", dddi.dwVendorId, dddi.dwDeviceId);
+
+ // Vendor 1: ATI
+ if (dddi.dwVendorId == VENDORID_ATI) {
+ // Test A: ATI Rage PRO
+ if (IsDevice(devATIRagePro, dddi.dwDeviceId, sizeof(devATIRagePro)))
+ glb.bUseMipmaps = FALSE;
+ // Test B: ATI Rage II+
+ if (IsDevice(devATIRageIIplus, dddi.dwDeviceId, sizeof(devATIRageIIplus)))
+ glb.bEmulateAlphaTest = TRUE;
+ }
+
+ // Vendor 2: Matrox
+ if (dddi.dwVendorId == 0x102B) {
+ // Test: Matrox G400 stencil buffer support does not work for AutoCAD
+ if (dddi.dwDeviceId == 0x0525) {
+ lpCtx->lpPF->pfd.cStencilBits = 0;
+ if (lpCtx->lpPF->iZBufferPF != -1) {
+ glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitDepth = 0;
+ glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwStencilBitMask = 0;
+ glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags &= ~DDPF_STENCILBUFFER;
+ }
+ }
+ }
+#endif // _GLD3
+}
+
+// ***********************************************************************
+
+BOOL dglCreateContextBuffers(
+ HDC a,
+ DGL_ctx *lpCtx,
+ BOOL bFallback)
+{
+ HRESULT hResult;
+
+ int i;
+// HGLRC hGLRC;
+// DGL_ctx* lpCtx;
+
+#ifndef _USE_GLD3_WGL
+ DWORD dwFlags;
+ DDSURFACEDESC2 ddsd2;
+ DDSCAPS2 ddscaps2;
+ LPDIRECTDRAWCLIPPER lpddClipper;
+ D3DDEVICEDESC D3DHWDevDesc; // Direct3D Hardware description
+ D3DDEVICEDESC D3DHELDevDesc; // Direct3D Hardware Emulation Layer
+#endif // _USE_GLD3_WGL
+
+ float inv_aspect;
+
+ GLenum bDoubleBuffer; // TRUE if double buffer required
+ GLenum bDepthBuffer; // TRUE if depth buffer required
+
+ const PIXELFORMATDESCRIPTOR *lpPFD = &lpCtx->lpPF->pfd;
+
+ // Vars for Mesa visual
+ DWORD dwDepthBits = 0;
+ DWORD dwStencilBits = 0;
+ DWORD dwAlphaBits = 0;
+ DWORD bAlphaSW = GL_FALSE;
+ DWORD bDouble = GL_FALSE;
+
+ DDSURFACEDESC2 ddsd2DisplayMode;
+ BOOL bFullScrnWin = FALSE; // fullscreen-size window ?
+ DDBLTFX ddbltfx;
+ DWORD dwMemoryType = (bFallback) ? DDSCAPS_SYSTEMMEMORY : glb.dwMemoryType;
+ BOOL bBogusWindow = FALSE; // non-drawable window ?
+ DWORD dwColorRef = 0; // GDI background color
+ RECT rcDst; // GDI window rect
+ POINT pt; // GDI window point
+
+ // Palette used for creating default global palette
+ PALETTEENTRY ppe[256];
+
+#ifndef _USE_GLD3_WGL
+ // Vertex buffer description. Used for creation of vertex buffers
+ D3DVERTEXBUFFERDESC vbufdesc;
+#endif // _USE_GLD3_WGL
+
+#define DDLOG_CRITICAL_OR_WARN (bFallback ? DDLOG_CRITICAL : DDLOG_WARN)
+
+ ddlogPrintf(DDLOG_SYSTEM, "dglCreateContextBuffers for HDC=%X", a);
+ nContextError = GLDERR_NONE;
+
+#ifdef GLD_THREADS
+ // Serialize access to DirectDraw object creation or DDS start
+ if (glb.bMultiThreaded)
+ EnterCriticalSection(&CriticalSection);
+#endif
+
+ // Check for back buffer
+ bDoubleBuffer = GL_TRUE; //(lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? GL_TRUE : GL_FALSE;
+ // Since we always do back buffering, check if we emulate front buffering
+ lpCtx->EmulateSingle =
+ (lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;
+#if 0 // Don't have to mimic MS OpenGL behavior for front-buffering (DaveM)
+ lpCtx->EmulateSingle |=
+ (lpPFD->dwFlags & PFD_SUPPORT_GDI) ? TRUE : FALSE;
+#endif
+
+ // Check for depth buffer
+ bDepthBuffer = (lpPFD->cDepthBits) ? GL_TRUE : GL_FALSE;
+
+ lpCtx->bDoubleBuffer = bDoubleBuffer;
+ lpCtx->bDepthBuffer = bDepthBuffer;
+
+ // Set the Fullscreen flag for the context.
+// lpCtx->bFullscreen = glb.bFullscreen;
+
+ // Obtain the dimensions of the rendering window
+ lpCtx->hDC = a; // Cache DC
+ lpCtx->hWnd = WindowFromDC(lpCtx->hDC);
+ // Check for non-window DC = memory DC ?
+ if (lpCtx->hWnd == NULL) {
+ // bitmap memory contexts are always single-buffered
+ lpCtx->EmulateSingle = TRUE;
+ bBogusWindow = TRUE;
+ ddlogPrintf(DDLOG_INFO, "Non-Window Memory Device Context");
+ if (GetClipBox(lpCtx->hDC, &lpCtx->rcScreenRect) == ERROR) {
+ ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglCreateContext\n");
+ SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
+ }
+ }
+ else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
+ bBogusWindow = TRUE;
+ ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglCreateContext\n");
+ SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
+ }
+ lpCtx->dwWidth = lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left;
+ lpCtx->dwHeight = lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top;
+
+ ddlogPrintf(DDLOG_INFO, "Input window %X: w=%i, h=%i",
+ lpCtx->hWnd, lpCtx->dwWidth, lpCtx->dwHeight);
+
+ // What if app only zeroes one dimension instead of both? (DaveM)
+ if ( (lpCtx->dwWidth == 0) || (lpCtx->dwHeight == 0) ) {
+ // Make the buffer size something sensible
+ lpCtx->dwWidth = 8;
+ lpCtx->dwHeight = 8;
+ }
+
+ // Set defaults
+ lpCtx->dwModeWidth = lpCtx->dwWidth;
+ lpCtx->dwModeHeight = lpCtx->dwHeight;
+/*
+ // Find best display mode for fullscreen
+ if (glb.bFullscreen || !glb.bPrimary) {
+ dglChooseDisplayMode(lpCtx);
+ }
+*/
+ // Misc initialisation
+ lpCtx->bCanRender = FALSE; // No rendering allowed yet
+ lpCtx->bSceneStarted = FALSE;
+ lpCtx->bFrameStarted = FALSE;
+
+ // Detect OS (specifically 'Windows 2000' or 'Windows XP')
+ DetectOS();
+
+ // NOTE: WinNT not supported
+ ddlogPrintf(DDLOG_INFO, "OS: %s", bHaveWin95 ? "Win9x" : (bHaveWin2K ? "Win2000/XP" : "Unsupported") );
+
+ // Test for Fullscreen
+ if (bHaveWin95) { // Problems with fullscreen on Win2K/XP
+ if ((GetSystemMetrics(SM_CXSCREEN) == lpCtx->dwWidth) &&
+ (GetSystemMetrics(SM_CYSCREEN) == lpCtx->dwHeight))
+ {
+ // Workaround for some apps that crash when going fullscreen.
+ //lpCtx->bFullscreen = TRUE;
+ }
+
+ }
+
+#ifdef _USE_GLD3_WGL
+ _gldDriver.CreateDrawable(lpCtx, glb.bDirectDrawPersistant, glb.bPersistantBuffers);
+#else
+ // Check if DirectDraw has already been created by original GLRC (DaveM)
+ if (glb.bDirectDrawPersistant && glb.bDirectDraw) {
+ lpCtx->lpDD4 = glb.lpDD4;
+ IDirectDraw4_AddRef(lpCtx->lpDD4);
+ goto SkipDirectDrawCreate;
+ }
+
+ // Create DirectDraw object
+ if (glb.bPrimary)
+ hResult = DirectDrawCreate(NULL, &lpCtx->lpDD1, NULL);
+ else {
+ // A non-primary device is to be used.
+ // Force context to be Fullscreen, secondary adaptors can not
+ // be used in a window.
+ hResult = DirectDrawCreate(&glb.ddGuid, &lpCtx->lpDD1, NULL);
+ lpCtx->bFullscreen = TRUE;
+ }
+ if (FAILED(hResult)) {
+ MessageBox(NULL, "Unable to initialize DirectDraw", "GLDirect", MB_OK);
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw interface", hResult);
+ nContextError = GLDERR_DDRAW;
+ goto return_with_error;
+ }
+
+ // Query for DX6 IDirectDraw4.
+ hResult = IDirectDraw_QueryInterface(lpCtx->lpDD1,
+ &IID_IDirectDraw4,
+ (void**)&lpCtx->lpDD4);
+ if (FAILED(hResult)) {
+ MessageBox(NULL, "GLDirect requires DirectX 6.0 or above", "GLDirect", MB_OK);
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create DirectDraw4 interface", hResult);
+ nContextError = GLDERR_DDRAW;
+ goto return_with_error;
+ }
+
+ // Cache DirectDraw interface for subsequent GLRCs
+ if (glb.bDirectDrawPersistant && !glb.bDirectDraw) {
+ glb.lpDD4 = lpCtx->lpDD4;
+ IDirectDraw4_AddRef(glb.lpDD4);
+ glb.bDirectDraw = TRUE;
+ }
+SkipDirectDrawCreate:
+
+ // Now we have a DD4 interface we can check for broken cards
+ dglTestForBrokenCards(lpCtx);
+
+ // Test if primary device can use flipping instead of blitting
+ ZeroMemory(&ddsd2DisplayMode, sizeof(ddsd2DisplayMode));
+ ddsd2DisplayMode.dwSize = sizeof(ddsd2DisplayMode);
+ hResult = IDirectDraw4_GetDisplayMode(
+ lpCtx->lpDD4,
+ &ddsd2DisplayMode);
+ if (SUCCEEDED(hResult)) {
+ if ( (lpCtx->dwWidth == ddsd2DisplayMode.dwWidth) &&
+ (lpCtx->dwHeight == ddsd2DisplayMode.dwHeight) ) {
+ // We have a fullscreen-size window
+ bFullScrnWin = TRUE;
+ // OK to use DirectDraw fullscreen mode ?
+ if (glb.bPrimary && !glb.bFullscreenBlit && !lpCtx->EmulateSingle && !glb.bDirectDrawPersistant) {
+ lpCtx->bFullscreen = TRUE;
+ ddlogMessage(DDLOG_INFO, "Primary upgraded to page flipping.\n");
+ }
+ }
+ // Cache the display mode dimensions
+ lpCtx->dwModeWidth = ddsd2DisplayMode.dwWidth;
+ lpCtx->dwModeHeight = ddsd2DisplayMode.dwHeight;
+ }
+
+ // Clamp the effective window dimensions to primary surface.
+ // We need to do this for D3D viewport dimensions even if wide
+ // surfaces are supported. This also is a good idea for handling
+ // whacked-out window dimensions passed for non-drawable windows
+ // like Solid Edge. (DaveM)
+ if (lpCtx->dwWidth > ddsd2DisplayMode.dwWidth)
+ lpCtx->dwWidth = ddsd2DisplayMode.dwWidth;
+ if (lpCtx->dwHeight > ddsd2DisplayMode.dwHeight)
+ lpCtx->dwHeight = ddsd2DisplayMode.dwHeight;
+
+ // Check for non-RGB desktop resolution
+ if (!lpCtx->bFullscreen && ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount <= 8) {
+ ddlogPrintf(DDLOG_CRITICAL_OR_WARN, "Desktop color depth %d bpp not supported",
+ ddsd2DisplayMode.ddpfPixelFormat.dwRGBBitCount);
+ nContextError = GLDERR_BPP;
+ goto return_with_error;
+ }
+#endif // _USE_GLD3_WGL
+
+ ddlogPrintf(DDLOG_INFO, "Window: w=%i, h=%i (%s)",
+ lpCtx->dwWidth,
+ lpCtx->dwHeight,
+ lpCtx->bFullscreen ? "fullscreen" : "windowed");
+
+#ifndef _USE_GLD3_WGL
+ // Obtain ddraw caps
+ ZeroMemory(&lpCtx->ddCaps, sizeof(DDCAPS));
+ lpCtx->ddCaps.dwSize = sizeof(DDCAPS);
+ if (glb.bHardware) {
+ // Get HAL caps
+ IDirectDraw4_GetCaps(lpCtx->lpDD4, &lpCtx->ddCaps, NULL);
+ } else {
+ // Get HEL caps
+ IDirectDraw4_GetCaps(lpCtx->lpDD4, NULL, &lpCtx->ddCaps);
+ }
+
+ // If this flag is present then we can't default to Mesa
+ // SW rendering between BeginScene() and EndScene().
+ if (lpCtx->ddCaps.dwCaps2 & DDCAPS2_NO2DDURING3DSCENE) {
+ ddlogMessage(DDLOG_INFO,
+ "Warning : No 2D allowed during 3D scene.\n");
+ }
+
+ // Query for DX6 Direct3D3 interface
+ hResult = IDirectDraw4_QueryInterface(lpCtx->lpDD4,
+ &IID_IDirect3D3,
+ (void**)&lpCtx->lpD3D3);
+ if (FAILED(hResult)) {
+ MessageBox(NULL, "Unable to initialize Direct3D", "GLDirect", MB_OK);
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D interface", hResult);
+ nContextError = GLDERR_D3D;
+ goto return_with_error;
+ }
+
+ // Context creation
+ if (lpCtx->bFullscreen) {
+ // FULLSCREEN
+
+ // Disable warning popups when in fullscreen mode
+ ddlogWarnOption(FALSE);
+
+ // Have to release persistant primary surface if fullscreen mode
+ if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
+ RELEASE(glb.lpPrimary4);
+ glb.bDirectDrawPrimary = FALSE;
+ }
+
+ dwFlags = DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN | DDSCL_ALLOWREBOOT;
+ if (glb.bFastFPU)
+ dwFlags |= DDSCL_FPUSETUP; // fast FPU setup optional (DaveM)
+ hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, lpCtx->hWnd, dwFlags);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Exclusive Fullscreen mode", hResult);
+ goto return_with_error;
+ }
+
+ hResult = IDirectDraw4_SetDisplayMode(lpCtx->lpDD4,
+ lpCtx->dwModeWidth,
+ lpCtx->dwModeHeight,
+ lpPFD->cColorBits,
+ 0,
+ 0);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "SetDisplayMode failed", hResult);
+ goto return_with_error;
+ }
+
+ // ** The display mode has changed, so dont use MessageBox! **
+
+ ZeroMemory(&ddsd2, sizeof(ddsd2));
+ ddsd2.dwSize = sizeof(ddsd2);
+
+ if (bDoubleBuffer) {
+ // Double buffered
+ // Primary surface
+ ddsd2.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT;
+ ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
+ DDSCAPS_FLIP |
+ DDSCAPS_COMPLEX |
+ DDSCAPS_3DDEVICE |
+ dwMemoryType;
+ ddsd2.dwBackBufferCount = 1;
+
+ hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+
+ // Render target surface
+ ZeroMemory(&ddscaps2, sizeof(ddscaps2)); // Clear the entire struct.
+ ddscaps2.dwCaps = DDSCAPS_BACKBUFFER;
+ hResult = IDirectDrawSurface4_GetAttachedSurface(lpCtx->lpFront4, &ddscaps2, &lpCtx->lpBack4);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "GetAttachedSurface failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+ } else {
+ // Single buffered
+ // Primary surface
+ ddsd2.dwFlags = DDSD_CAPS;
+ ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE |
+ //DDSCAPS_3DDEVICE |
+ dwMemoryType;
+
+ hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+
+ lpCtx->lpBack4 = NULL;
+ }
+ } else {
+ // WINDOWED
+
+ // OK to enable warning popups in windowed mode
+ ddlogWarnOption(glb.bMessageBoxWarnings);
+
+ dwFlags = DDSCL_NORMAL;
+ if (glb.bMultiThreaded)
+ dwFlags |= DDSCL_MULTITHREADED;
+ if (glb.bFastFPU)
+ dwFlags |= DDSCL_FPUSETUP; // fast FPU setup optional (DaveM)
+ hResult = IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4,
+ lpCtx->hWnd,
+ dwFlags);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to set Normal coop level", hResult);
+ goto return_with_error;
+ }
+ // Has Primary surface already been created for original GLRC ?
+ // Note this can only be applicable for windowed modes
+ if (glb.bDirectDrawPersistant && glb.bDirectDrawPrimary) {
+ lpCtx->lpFront4 = glb.lpPrimary4;
+ IDirectDrawSurface4_AddRef(lpCtx->lpFront4);
+ // Update the window on the default clipper
+ IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
+ IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
+ IDirectDrawClipper_Release(lpddClipper);
+ goto SkipPrimaryCreate;
+ }
+
+ // Primary surface
+ ZeroMemory(&ddsd2, sizeof(ddsd2));
+ ddsd2.dwSize = sizeof(ddsd2);
+ ddsd2.dwFlags = DDSD_CAPS;
+ ddsd2.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
+ hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpFront4, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (primary) failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+
+ // Cache Primary surface for subsequent GLRCs
+ // Note this can only be applicable to subsequent windowed modes
+ if (glb.bDirectDrawPersistant && !glb.bDirectDrawPrimary) {
+ glb.lpPrimary4 = lpCtx->lpFront4;
+ IDirectDrawSurface4_AddRef(glb.lpPrimary4);
+ glb.bDirectDrawPrimary = TRUE;
+ }
+
+ // Clipper object
+ hResult = DirectDrawCreateClipper(0, &lpddClipper, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateClipper failed", hResult);
+ goto return_with_error;
+ }
+ hResult = IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
+ if (FAILED(hResult)) {
+ RELEASE(lpddClipper);
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "SetHWnd failed", hResult);
+ goto return_with_error;
+ }
+ hResult = IDirectDrawSurface4_SetClipper(lpCtx->lpFront4, lpddClipper);
+ RELEASE(lpddClipper); // We have finished with it.
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "SetClipper failed", hResult);
+ goto return_with_error;
+ }
+SkipPrimaryCreate:
+
+ if (bDoubleBuffer) {
+ // Render target surface
+ ZeroMemory(&ddsd2, sizeof(ddsd2));
+ ddsd2.dwSize = sizeof(ddsd2);
+ ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
+ ddsd2.dwWidth = lpCtx->dwWidth;
+ ddsd2.dwHeight = lpCtx->dwHeight;
+ ddsd2.ddsCaps.dwCaps = DDSCAPS_3DDEVICE |
+ DDSCAPS_OFFSCREENPLAIN |
+ dwMemoryType;
+
+ // Reserve the entire desktop size for persistant buffers option
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
+ ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
+ ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
+ }
+ // Re-use original back buffer if persistant buffers exist
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpBack4)
+ hResult = IDirectDrawSurface4_AddRef(lpCtx->lpBack4 = glb.lpBack4);
+ else
+ hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpBack4, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Create Backbuffer failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpBack4)
+ IDirectDrawSurface4_AddRef(glb.lpBack4 = lpCtx->lpBack4);
+ } else {
+ lpCtx->lpBack4 = NULL;
+ }
+ }
+
+ //
+ // Now create the Z-buffer
+ //
+ lpCtx->bStencil = FALSE; // Default to no stencil buffer
+ if (bDepthBuffer && (lpCtx->lpPF->iZBufferPF != -1)) {
+ // Get z-buffer dimensions from the render target
+ // Setup the surface desc for the z-buffer.
+ ZeroMemory(&ddsd2, sizeof(ddsd2));
+ ddsd2.dwSize = sizeof(ddsd2);
+ ddsd2.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
+ ddsd2.ddsCaps.dwCaps = DDSCAPS_ZBUFFER | dwMemoryType;
+ ddsd2.dwWidth = lpCtx->dwWidth;
+ ddsd2.dwHeight = lpCtx->dwHeight;
+ memcpy(&ddsd2.ddpfPixelFormat,
+ &glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF],
+ sizeof(DDPIXELFORMAT) );
+
+ // Reserve the entire desktop size for persistant buffers option
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers) {
+ ddsd2.dwWidth = ddsd2DisplayMode.dwWidth;
+ ddsd2.dwHeight = ddsd2DisplayMode.dwHeight;
+ }
+
+ // Create a z-buffer
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4)
+ hResult = IDirectDrawSurface4_AddRef(lpCtx->lpDepth4 = glb.lpDepth4);
+ else
+ hResult = IDirectDraw4_CreateSurface(lpCtx->lpDD4, &ddsd2, &lpCtx->lpDepth4, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateSurface (ZBuffer) failed", hResult);
+ nContextError = GLDERR_MEM;
+ goto return_with_error;
+ }
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpDepth4)
+ IDirectDrawSurface4_AddRef(glb.lpDepth4 = lpCtx->lpDepth4);
+ else if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpDepth4 && glb.lpBack4)
+ IDirectDrawSurface4_DeleteAttachedSurface(glb.lpBack4, 0, glb.lpDepth4);
+
+ // Attach Zbuffer to render target
+ TRY(IDirectDrawSurface4_AddAttachedSurface(
+ bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
+ lpCtx->lpDepth4),
+ "dglCreateContext: Attach Zbuffer");
+ if (glb.lpZBufferPF[lpCtx->lpPF->iZBufferPF].dwFlags & DDPF_STENCILBUFFER) {
+ lpCtx->bStencil = TRUE;
+ ddlogMessage(DDLOG_INFO, "Depth buffer has stencil\n");
+ }
+ }
+
+ // Clear all back buffers and Z-buffers in case of memory recycling.
+ ZeroMemory(&ddbltfx, sizeof(ddbltfx));
+ ddbltfx.dwSize = sizeof(ddbltfx);
+ IDirectDrawSurface4_Blt(lpCtx->lpBack4, NULL, NULL, NULL,
+ DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);
+ if (lpCtx->lpDepth4)
+ IDirectDrawSurface4_Blt(lpCtx->lpDepth4, NULL, NULL, NULL,
+ DDBLT_COLORFILL | DDBLT_WAIT, &ddbltfx);
+
+ // Now that we have a Z-buffer we can create the 3D device
+ hResult = IDirect3D3_CreateDevice(lpCtx->lpD3D3,
+ &glb.d3dGuid,
+ bDoubleBuffer ? lpCtx->lpBack4 : lpCtx->lpFront4,
+ &lpCtx->lpDev3,
+ NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "Unable to create Direct3D device", hResult);
+ nContextError = GLDERR_D3D;
+ goto return_with_error;
+ }
+
+ // We must do this as soon as the device is created
+ dglInitStateCaches(lpCtx);
+
+ // Obtain the D3D Device Description
+ D3DHWDevDesc.dwSize = D3DHELDevDesc.dwSize = sizeof(D3DDEVICEDESC);
+ TRY(IDirect3DDevice3_GetCaps(lpCtx->lpDev3,
+ &D3DHWDevDesc,
+ &D3DHELDevDesc),
+ "dglCreateContext: GetCaps failed");
+
+ // Choose the relevant description and cache it in the context.
+ // We will use this description later for caps checking
+ memcpy( &lpCtx->D3DDevDesc,
+ glb.bHardware ? &D3DHWDevDesc : &D3DHELDevDesc,
+ sizeof(D3DDEVICEDESC));
+
+ // Now we can examine the texture formats
+ if (!dglBuildTextureFormatList(lpCtx->lpDev3)) {
+ ddlogMessage(DDLOG_CRITICAL_OR_WARN, "dglBuildTextureFormatList failed\n");
+ goto return_with_error;
+ }
+
+ // Get the pixel format of the back buffer
+ lpCtx->ddpfRender.dwSize = sizeof(lpCtx->ddpfRender);
+ if (bDoubleBuffer)
+ hResult = IDirectDrawSurface4_GetPixelFormat(
+ lpCtx->lpBack4,
+ &lpCtx->ddpfRender);
+ else
+ hResult = IDirectDrawSurface4_GetPixelFormat(
+ lpCtx->lpFront4,
+ &lpCtx->ddpfRender);
+
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "GetPixelFormat failed", hResult);
+ goto return_with_error;
+ }
+ // Find a pixel packing function suitable for this surface
+ pxClassifyPixelFormat(&lpCtx->ddpfRender,
+ &lpCtx->fnPackFunc,
+ &lpCtx->fnUnpackFunc,
+ &lpCtx->fnPackSpanFunc);
+
+ // Viewport
+ hResult = IDirect3D3_CreateViewport(lpCtx->lpD3D3, &lpCtx->lpViewport3, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateViewport failed", hResult);
+ goto return_with_error;
+ }
+
+ hResult = IDirect3DDevice3_AddViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "AddViewport failed", hResult);
+ goto return_with_error;
+ }
+
+ // Initialise the viewport
+ // Note screen coordinates are used for viewport clipping since D3D
+ // transform operations are not used in the GLD CAD driver. (DaveM)
+ inv_aspect = (float)lpCtx->dwHeight/(float)lpCtx->dwWidth;
+
+ lpCtx->d3dViewport.dwSize = sizeof(lpCtx->d3dViewport);
+ lpCtx->d3dViewport.dwX = 0;
+ lpCtx->d3dViewport.dwY = 0;
+ lpCtx->d3dViewport.dwWidth = lpCtx->dwWidth;
+ lpCtx->d3dViewport.dwHeight = lpCtx->dwHeight;
+ lpCtx->d3dViewport.dvClipX = 0; // -1.0f;
+ lpCtx->d3dViewport.dvClipY = 0; // inv_aspect;
+ lpCtx->d3dViewport.dvClipWidth = lpCtx->dwWidth; // 2.0f;
+ lpCtx->d3dViewport.dvClipHeight = lpCtx->dwHeight; // 2.0f * inv_aspect;
+ lpCtx->d3dViewport.dvMinZ = 0.0f;
+ lpCtx->d3dViewport.dvMaxZ = 1.0f;
+ TRY(IDirect3DViewport3_SetViewport2(lpCtx->lpViewport3, &lpCtx->d3dViewport), "dglCreateContext: SetViewport2");
+
+ hResult = IDirect3DDevice3_SetCurrentViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "SetCurrentViewport failed", hResult);
+ goto return_with_error;
+ }
+
+ lpCtx->dwBPP = lpPFD->cColorBits;
+ lpCtx->iZBufferPF = lpCtx->lpPF->iZBufferPF;
+
+ // Set last texture to NULL
+ for (i=0; i<MAX_TEXTURE_UNITS; i++) {
+ lpCtx->ColorOp[i] = D3DTOP_DISABLE;
+ lpCtx->AlphaOp[i] = D3DTOP_DISABLE;
+ lpCtx->tObj[i] = NULL;
+ }
+
+ // Default to perspective correct texture mapping
+ dglSetRenderState(lpCtx, D3DRENDERSTATE_TEXTUREPERSPECTIVE, TRUE, "TexturePersp");
+
+ // Set the default culling mode
+ lpCtx->cullmode = D3DCULL_NONE;
+ dglSetRenderState(lpCtx, D3DRENDERSTATE_CULLMODE, D3DCULL_NONE, "CullMode");
+
+ // Disable specular
+ dglSetRenderState(lpCtx, D3DRENDERSTATE_SPECULARENABLE, FALSE, "SpecularEnable");
+ // Disable subpixel correction
+// dglSetRenderState(lpCtx, D3DRENDERSTATE_SUBPIXEL, FALSE, "SubpixelEnable");
+ // Disable dithering
+ dglSetRenderState(lpCtx, D3DRENDERSTATE_DITHERENABLE, FALSE, "DitherEnable");
+
+ // Initialise the primitive caches
+// lpCtx->dwNextLineVert = 0;
+// lpCtx->dwNextTriVert = 0;
+
+ // Init the global texture palette
+ lpCtx->lpGlobalPalette = NULL;
+
+ // Init the HW/SW usage counters
+// lpCtx->dwHWUsageCount = lpCtx->dwSWUsageCount = 0L;
+
+ //
+ // Create two D3D vertex buffers.
+ // One will hold the pre-transformed data with the other one
+ // being used to hold the post-transformed & clipped verts.
+ //
+#if 0 // never used (DaveM)
+ vbufdesc.dwSize = sizeof(D3DVERTEXBUFFERDESC);
+ vbufdesc.dwCaps = D3DVBCAPS_WRITEONLY;
+ if (glb.bHardware == FALSE)
+ vbufdesc.dwCaps = D3DVBCAPS_SYSTEMMEMORY;
+ vbufdesc.dwNumVertices = 32768; // For the time being
+
+ // Source vertex buffer
+ vbufdesc.dwFVF = DGL_LVERTEX;
+ hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_vbuf, 0, NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(src) failed", hResult);
+ goto return_with_error;
+ }
+
+ // Destination vertex buffer
+ vbufdesc.dwFVF = (glb.bMultitexture == FALSE) ? D3DFVF_TLVERTEX : (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX2);
+ hResult = IDirect3D3_CreateVertexBuffer(lpCtx->lpD3D3, &vbufdesc, &lpCtx->m_pvbuf, 0, NULL);
+ if(FAILED(hResult)) {
+ ddlogError(DDLOG_CRITICAL_OR_WARN, "CreateVertexBuffer(dst) failed", hResult);
+ goto return_with_error;
+ }
+#endif
+
+#endif _USE_GLD3_WGL
+
+ //
+ // Now create the Mesa context
+ //
+
+ // Create the Mesa visual
+ if (lpPFD->cDepthBits)
+ dwDepthBits = 16;
+ if (lpPFD->cStencilBits)
+ dwStencilBits = 8;
+ if (lpPFD->cAlphaBits) {
+ dwAlphaBits = 8;
+ bAlphaSW = GL_TRUE;
+ }
+ if (lpPFD->dwFlags & PFD_DOUBLEBUFFER)
+ bDouble = GL_TRUE;
+// lpCtx->EmulateSingle =
+// (lpPFD->dwFlags & PFD_DOUBLEBUFFER) ? FALSE : TRUE;
+
+#ifdef _USE_GLD3_WGL
+ lpCtx->glVis = _mesa_create_visual(
+ bDouble, /* double buffer */
+ GL_FALSE, // stereo
+ lpPFD->cRedBits,
+ lpPFD->cGreenBits,
+ lpPFD->cBlueBits,
+ dwAlphaBits,
+ dwDepthBits,
+ dwStencilBits,
+ lpPFD->cAccumRedBits, // accum bits
+ lpPFD->cAccumGreenBits, // accum bits
+ lpPFD->cAccumBlueBits, // accum bits
+ lpPFD->cAccumAlphaBits, // accum alpha bits
+ 1 // num samples
+ );
+#else // _USE_GLD3_WGL
+ lpCtx->glVis = (*mesaFuncs.gl_create_visual)(
+ GL_TRUE, // RGB mode
+ bAlphaSW, // Is an alpha buffer required?
+ bDouble, // Is an double-buffering required?
+ GL_FALSE, // stereo
+ dwDepthBits, // depth_size
+ dwStencilBits, // stencil_size
+ lpPFD->cAccumBits, // accum_size
+ 0, // colour-index bits
+ lpPFD->cRedBits, // Red bit count
+ lpPFD->cGreenBits, // Green bit count
+ lpPFD->cBlueBits, // Blue bit count
+ dwAlphaBits // Alpha bit count
+ );
+#endif // _USE_GLD3_WGL
+
+ if (lpCtx->glVis == NULL) {
+ ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_visual failed\n");
+ goto return_with_error;
+ }
+
+#ifdef _USE_GLD3_WGL
+ lpCtx->glCtx = _mesa_create_context(API_OPENGL, lpCtx->glVis, NULL, (void *)lpCtx, GL_TRUE);
+#else
+ // Create the Mesa context
+ lpCtx->glCtx = (*mesaFuncs.gl_create_context)(
+ lpCtx->glVis, // Mesa visual
+ NULL, // share list context
+ (void *)lpCtx, // Pointer to our driver context
+ GL_TRUE // Direct context flag
+ );
+#endif // _USE_GLD3_WGL
+
+ if (lpCtx->glCtx == NULL) {
+ ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_context failed\n");
+ goto return_with_error;
+ }
+
+ // Create the Mesa framebuffer
+#ifdef _USE_GLD3_WGL
+ lpCtx->glBuffer = _mesa_create_framebuffer(
+ lpCtx->glVis,
+ lpCtx->glVis->depthBits > 0,
+ lpCtx->glVis->stencilBits > 0,
+ lpCtx->glVis->accumRedBits > 0,
+ GL_FALSE //swalpha
+ );
+#else
+ lpCtx->glBuffer = (*mesaFuncs.gl_create_framebuffer)(lpCtx->glVis);
+#endif // _USE_GLD3_WGL
+
+ if (lpCtx->glBuffer == NULL) {
+ ddlogMessage(DDLOG_CRITICAL_OR_WARN, "gl_create_framebuffer failed\n");
+ goto return_with_error;
+ }
+
+#ifdef _USE_GLD3_WGL
+ // Init Mesa internals
+ _swrast_CreateContext( lpCtx->glCtx );
+ _vbo_CreateContext( lpCtx->glCtx );
+ _tnl_CreateContext( lpCtx->glCtx );
+ _swsetup_CreateContext( lpCtx->glCtx );
+
+ _gldDriver.InitialiseMesa(lpCtx);
+
+ lpCtx->glCtx->imports.warning = _gld_mesa_warning;
+ lpCtx->glCtx->imports.fatal = _gld_mesa_fatal;
+
+#else
+ // Tell Mesa how many texture stages we have
+ glb.wMaxSimultaneousTextures = lpCtx->D3DDevDesc.wMaxSimultaneousTextures;
+ // Only use as many Units as the spec requires
+ if (glb.wMaxSimultaneousTextures > MAX_TEXTURE_UNITS)
+ glb.wMaxSimultaneousTextures = MAX_TEXTURE_UNITS;
+ lpCtx->glCtx->Const.MaxTextureUnits = glb.wMaxSimultaneousTextures;
+ ddlogPrintf(DDLOG_INFO, "Texture stages : %d", glb.wMaxSimultaneousTextures);
+
+ // Set the max texture size.
+ // NOTE: clamped to a max of 1024 for extra performance!
+ lpCtx->dwMaxTextureSize = (lpCtx->D3DDevDesc.dwMaxTextureWidth <= 1024) ? lpCtx->D3DDevDesc.dwMaxTextureWidth : 1024;
+
+// Texture resize takes place elsewhere. KH
+// NOTE: This was added to workaround an issue with the Intel app.
+#if 0
+ lpCtx->glCtx->Const.MaxTextureSize = lpCtx->dwMaxTextureSize;
+#else
+ lpCtx->glCtx->Const.MaxTextureSize = 1024;
+#endif
+ lpCtx->glCtx->Const.MaxDrawBuffers = 1;
+
+ // Setup the Display Driver pointers
+ dglSetupDDPointers(lpCtx->glCtx);
+
+ // Initialise all the Direct3D renderstates
+ dglInitStateD3D(lpCtx->glCtx);
+
+#if 0
+ // Signal a reload of texture state on next glBegin
+ lpCtx->m_texHandleValid = FALSE;
+ lpCtx->m_mtex = FALSE;
+ lpCtx->m_texturing = FALSE;
+#else
+ // Set default texture unit state
+// dglSetTexture(lpCtx, 0, NULL);
+// dglSetTexture(lpCtx, 1, NULL);
+#endif
+
+ //
+ // Set the global texture palette to default values.
+ //
+
+ // Clear the entire palette
+ ZeroMemory(ppe, sizeof(PALETTEENTRY) * 256);
+
+ // Fill the palette with a default colour.
+ // A garish colour is used to catch bugs. Here Magenta is used.
+ for (i=0; i < 256; i++) {
+ ppe[i].peRed = 255;
+ ppe[i].peGreen = 0;
+ ppe[i].peBlue = 255;
+ }
+
+ RELEASE(lpCtx->lpGlobalPalette);
+
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && glb.lpGlobalPalette)
+ hResult = IDirectDrawPalette_AddRef(lpCtx->lpGlobalPalette = glb.lpGlobalPalette);
+ else
+ hResult = IDirectDraw4_CreatePalette(
+ lpCtx->lpDD4,
+ DDPCAPS_INITIALIZE | DDPCAPS_8BIT | DDPCAPS_ALLOW256,
+ ppe,
+ &(lpCtx->lpGlobalPalette),
+ NULL);
+ if (FAILED(hResult)) {
+ ddlogError(DDLOG_ERROR, "Default CreatePalette failed\n", hResult);
+ lpCtx->lpGlobalPalette = NULL;
+ goto return_with_error;
+ }
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers && !glb.lpGlobalPalette)
+ IDirectDrawPalette_AddRef(glb.lpGlobalPalette = lpCtx->lpGlobalPalette);
+
+#endif // _USE_GLD3_WGL
+
+ // ** If we have made it to here then we can enable rendering **
+ lpCtx->bCanRender = TRUE;
+
+// ddlogMessage(DDLOG_SYSTEM, "dglCreateContextBuffers succeded\n");
+
+#ifdef GLD_THREADS
+ // Release serialized access
+ if (glb.bMultiThreaded)
+ LeaveCriticalSection(&CriticalSection);
+#endif
+
+ return TRUE;
+
+return_with_error:
+ // Clean up before returning.
+ // This is critical for secondary devices.
+
+ lpCtx->bCanRender = FALSE;
+
+#ifdef _USE_GLD3_WGL
+ // Destroy the Mesa context
+ if (lpCtx->glBuffer)
+ _mesa_destroy_framebuffer(lpCtx->glBuffer);
+ if (lpCtx->glCtx)
+ _mesa_destroy_context(lpCtx->glCtx);
+ if (lpCtx->glVis)
+ _mesa_destroy_visual(lpCtx->glVis);
+
+ // Destroy driver data
+ _gldDriver.DestroyDrawable(lpCtx);
+#else
+ // Destroy the Mesa context
+ if (lpCtx->glBuffer)
+ (*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
+ if (lpCtx->glCtx)
+ (*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
+ if (lpCtx->glVis)
+ (*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);
+
+ RELEASE(lpCtx->m_pvbuf); // Release D3D vertex buffer
+ RELEASE(lpCtx->m_vbuf); // Release D3D vertex buffer
+
+ if (lpCtx->lpViewport3) {
+ if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
+ RELEASE(lpCtx->lpViewport3);
+ lpCtx->lpViewport3 = NULL;
+ }
+
+ RELEASE(lpCtx->lpDev3);
+ if (lpCtx->lpDepth4) {
+ if (lpCtx->lpBack4)
+ IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
+ else
+ IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
+ RELEASE(lpCtx->lpDepth4);
+ lpCtx->lpDepth4 = NULL;
+ }
+ RELEASE(lpCtx->lpBack4);
+ RELEASE(lpCtx->lpFront4);
+ else
+ if (lpCtx->bFullscreen) {
+ IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
+ IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
+ }
+ RELEASE(lpCtx->lpD3D3);
+ RELEASE(lpCtx->lpDD4);
+ RELEASE(lpCtx->lpDD1);
+#endif // _USE_GLD3_WGL
+
+ lpCtx->bAllocated = FALSE;
+
+#ifdef GLD_THREADS
+ // Release serialized access
+ if (glb.bMultiThreaded)
+ LeaveCriticalSection(&CriticalSection);
+#endif
+
+ return FALSE;
+
+#undef DDLOG_CRITICAL_OR_WARN
+}
+
+// ***********************************************************************
+
+HGLRC dglCreateContext(
+ HDC a,
+ const DGL_pixelFormat *lpPF)
+{
+ int i;
+ HGLRC hGLRC;
+ DGL_ctx* lpCtx;
+ static BOOL bWarnOnce = TRUE;
+ DWORD dwThreadId = GetCurrentThreadId();
+ char szMsg[256];
+ HWND hWnd;
+ LONG lpfnWndProc;
+
+ // Validate license
+ if (!dglValidate())
+ return NULL;
+
+ // Is context state ready ?
+ if (!bContextReady)
+ return NULL;
+
+ ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext for HDC=%X, ThreadId=%X", a, dwThreadId);
+
+ // Find next free context.
+ // Also ensure that only one Fullscreen context is created at any one time.
+ hGLRC = 0; // Default to Not Found
+ for (i=0; i<DGL_MAX_CONTEXTS; i++) {
+ if (ctxlist[i].bAllocated) {
+ if (/*glb.bFullscreen && */ctxlist[i].bFullscreen)
+ break;
+ } else {
+ hGLRC = (HGLRC)(i+1);
+ break;
+ }
+ }
+
+ // Bail if no GLRC was found
+ if (!hGLRC)
+ return NULL;
+
+ // Set the context pointer
+ lpCtx = dglGetContextAddress(hGLRC);
+ // Make sure that context is zeroed before we do anything.
+ // MFC and C++ apps call wglCreateContext() and wglDeleteContext() multiple times,
+ // even though only one context is ever used by the app, so keep it clean. (DaveM)
+ ZeroMemory(lpCtx, sizeof(DGL_ctx));
+ lpCtx->bAllocated = TRUE;
+ // Flag that buffers need creating on next wglMakeCurrent call.
+ lpCtx->bHasBeenCurrent = FALSE;
+ lpCtx->lpPF = (DGL_pixelFormat *)lpPF; // cache pixel format
+ lpCtx->bCanRender = FALSE;
+
+ // Create all the internal resources here, not in dglMakeCurrent().
+ // We do a re-size check in dglMakeCurrent in case of re-allocations. (DaveM)
+ // We now try context allocations twice, first with video memory,
+ // then again with system memory. This is similar to technique
+ // used for dglWglResizeBuffers(). (DaveM)
+ if (lpCtx->bHasBeenCurrent == FALSE) {
+ if (!dglCreateContextBuffers(a, lpCtx, FALSE)) {
+ if (glb.bMessageBoxWarnings && bWarnOnce && dwLogging) {
+ bWarnOnce = FALSE;
+ switch (nContextError) {
+ case GLDERR_DDRAW: strcpy(szMsg, szDDrawWarning); break;
+ case GLDERR_D3D: strcpy(szMsg, szD3DWarning); break;
+ case GLDERR_MEM: strcpy(szMsg, szResourceWarning); break;
+ case GLDERR_BPP: strcpy(szMsg, szBPPWarning); break;
+ default: strcpy(szMsg, "");
+ }
+ if (strlen(szMsg))
+ MessageBox(NULL, szMsg, "GLDirect", MB_OK | MB_ICONWARNING);
+ }
+ // Only need to try again if memory error
+ if (nContextError == GLDERR_MEM) {
+ ddlogPrintf(DDLOG_WARN, "dglCreateContext failed 1st time with video memory");
+ }
+ else {
+ ddlogPrintf(DDLOG_ERROR, "dglCreateContext failed");
+ return NULL;
+ }
+ }
+ }
+
+ // Now that we have a hWnd, we can intercept the WindowProc.
+ hWnd = lpCtx->hWnd;
+ if (hWnd) {
+ // Only hook individual window handler once if not hooked before.
+ lpfnWndProc = GetWindowLong(hWnd, GWL_WNDPROC);
+ if (lpfnWndProc != (LONG)dglWndProc) {
+ lpCtx->lpfnWndProc = lpfnWndProc;
+ SetWindowLong(hWnd, GWL_WNDPROC, (LONG)dglWndProc);
+ }
+ // Find the parent window of the app too.
+ if (glb.hWndActive == NULL) {
+ while (hWnd != NULL) {
+ glb.hWndActive = hWnd;
+ hWnd = GetParent(hWnd);
+ }
+ // Hook the parent window too.
+ lpfnWndProc = GetWindowLong(glb.hWndActive, GWL_WNDPROC);
+ if (glb.hWndActive == lpCtx->hWnd)
+ glb.lpfnWndProc = lpCtx->lpfnWndProc;
+ else if (lpfnWndProc != (LONG)dglWndProc)
+ glb.lpfnWndProc = lpfnWndProc;
+ if (glb.lpfnWndProc)
+ SetWindowLong(glb.hWndActive, GWL_WNDPROC, (LONG)dglWndProc);
+ }
+ }
+
+ ddlogPrintf(DDLOG_SYSTEM, "dglCreateContext succeeded for HGLRC=%d", (int)hGLRC);
+
+ return hGLRC;
+}
+
+// ***********************************************************************
+// Make a DirectGL context current
+// Used by wgl functions and dgl functions
+BOOL dglMakeCurrent(
+ HDC a,
+ HGLRC b)
+{
+ int context;
+ DGL_ctx* lpCtx;
+ HWND hWnd;
+ BOOL bNeedResize = FALSE;
+ BOOL bWindowChanged, bContextChanged;
+ LPDIRECTDRAWCLIPPER lpddClipper;
+ DWORD dwThreadId = GetCurrentThreadId();
+ LONG lpfnWndProc;
+
+ // Validate license
+ if (!dglValidate())
+ return FALSE;
+
+ // Is context state ready ?
+ if (!bContextReady)
+ return FALSE;
+
+ context = (int)b; // This is as a result of STRICT!
+ ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: HDC=%X, HGLRC=%d, ThreadId=%X", a, context, dwThreadId);
+
+ // If the HGLRC is NULL then make no context current;
+ // Ditto if the HDC is NULL either. (DaveM)
+ if (context == 0 || a == 0) {
+ // Corresponding Mesa operation
+#ifdef _USE_GLD3_WGL
+ _mesa_make_current(NULL, NULL);
+#else
+ (*mesaFuncs.gl_make_current)(NULL, NULL);
+#endif
+ dglSetCurrentContext(0);
+ return TRUE;
+ }
+
+ // Make sure the HGLRC is in range
+ if ((context > DGL_MAX_CONTEXTS) || (context < 0)) {
+ ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: HGLRC out of range\n");
+ return FALSE;
+ }
+
+ // Find address of context and make sure that it has been allocated
+ lpCtx = dglGetContextAddress(b);
+ if (!lpCtx->bAllocated) {
+ ddlogMessage(DDLOG_ERROR, "dglMakeCurrent: Context not allocated\n");
+// return FALSE;
+ return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
+ }
+
+#ifdef GLD_THREADS
+ // Serialize access to DirectDraw or DDS operations
+ if (glb.bMultiThreaded)
+ EnterCriticalSection(&CriticalSection);
+#endif
+
+ // Check if window has changed
+ hWnd = (a != lpCtx->hDC) ? WindowFromDC(a) : lpCtx->hWnd;
+ bWindowChanged = (hWnd != lpCtx->hWnd) ? TRUE : FALSE;
+ bContextChanged = (b != dglGetCurrentContext()) ? TRUE : FALSE;
+
+ // If the window has changed, make sure the clipper is updated. (DaveM)
+ if (glb.bDirectDrawPersistant && !lpCtx->bFullscreen && (bWindowChanged || bContextChanged)) {
+ lpCtx->hWnd = hWnd;
+#ifndef _USE_GLD3_WGL
+ IDirectDrawSurface4_GetClipper(lpCtx->lpFront4, &lpddClipper);
+ IDirectDrawClipper_SetHWnd(lpddClipper, 0, lpCtx->hWnd);
+ IDirectDrawClipper_Release(lpddClipper);
+#endif // _USE_GLD3_WGL
+ }
+
+ // Make sure hDC and hWnd is current. (DaveM)
+ // Obtain the dimensions of the rendering window
+ lpCtx->hDC = a; // Cache DC
+ lpCtx->hWnd = hWnd;
+ hWndLastActive = hWnd;
+
+ // Check for non-window DC = memory DC ?
+ if (hWnd == NULL) {
+ if (GetClipBox(a, &lpCtx->rcScreenRect) == ERROR) {
+ ddlogMessage(DDLOG_WARN, "GetClipBox failed in dglMakeCurrent\n");
+ SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
+ }
+ }
+ else if (!GetClientRect(lpCtx->hWnd, &lpCtx->rcScreenRect)) {
+ ddlogMessage(DDLOG_WARN, "GetClientRect failed in dglMakeCurrent\n");
+ SetRect(&lpCtx->rcScreenRect, 0, 0, 0, 0);
+ }
+ // Check if buffers need to be re-sized;
+ // If so, wait until Mesa GL stuff is setup before re-sizing;
+ if (lpCtx->dwWidth != lpCtx->rcScreenRect.right - lpCtx->rcScreenRect.left ||
+ lpCtx->dwHeight != lpCtx->rcScreenRect.bottom - lpCtx->rcScreenRect.top)
+ bNeedResize = TRUE;
+
+ // Now we can update our globals
+ dglSetCurrentContext(b);
+
+ // Corresponding Mesa operation
+#ifdef _USE_GLD3_WGL
+ _mesa_make_current(lpCtx->glCtx, lpCtx->glBuffer);
+ lpCtx->glCtx->Driver.UpdateState(lpCtx->glCtx, _NEW_ALL);
+ if (bNeedResize) {
+ // Resize buffers (Note Mesa GL needs to be setup beforehand);
+ // Resize Mesa internal buffer too via glViewport() command,
+ // which subsequently calls dglWglResizeBuffers() too.
+ lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+ lpCtx->bHasBeenCurrent = TRUE;
+ }
+#else
+ (*mesaFuncs.gl_make_current)(lpCtx->glCtx, lpCtx->glBuffer);
+
+ dglSetupDDPointers(lpCtx->glCtx);
+
+ // Insure DirectDraw surfaces fit current window DC
+ if (bNeedResize) {
+ // Resize buffers (Note Mesa GL needs to be setup beforehand);
+ // Resize Mesa internal buffer too via glViewport() command,
+ // which subsequently calls dglWglResizeBuffers() too.
+ (*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+ lpCtx->bHasBeenCurrent = TRUE;
+ }
+#endif // _USE_GLD3_WGL
+ ddlogPrintf(DDLOG_SYSTEM, "dglMakeCurrent: width = %d, height = %d", lpCtx->dwWidth, lpCtx->dwHeight);
+
+ // We have to clear D3D back buffer and render state if emulated front buffering
+ // for different window (but not context) like in Solid Edge.
+ if (glb.bDirectDrawPersistant && glb.bPersistantBuffers
+ && (bWindowChanged /* || bContextChanged */) && lpCtx->EmulateSingle) {
+#ifdef _USE_GLD3_WGL
+// IDirect3DDevice8_EndScene(lpCtx->pDev);
+// lpCtx->bSceneStarted = FALSE;
+ lpCtx->glCtx->Driver.Clear(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
+ GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+#else
+ IDirect3DDevice3_EndScene(lpCtx->lpDev3);
+ lpCtx->bSceneStarted = FALSE;
+ dglClearD3D(lpCtx->glCtx, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
+ GL_TRUE, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+#endif // _USE_GLD3_WGL
+ }
+
+ // The first time we call MakeCurrent we set the initial viewport size
+ if (lpCtx->bHasBeenCurrent == FALSE)
+#ifdef _USE_GLD3_WGL
+ lpCtx->glCtx->Driver.Viewport(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+#else
+ (*mesaFuncs.gl_Viewport)(lpCtx->glCtx, 0, 0, lpCtx->dwWidth, lpCtx->dwHeight);
+#endif // _USE_GLD3_WGL
+ lpCtx->bHasBeenCurrent = TRUE;
+
+#ifdef GLD_THREADS
+ // Release serialized access
+ if (glb.bMultiThreaded)
+ LeaveCriticalSection(&CriticalSection);
+#endif
+
+ return TRUE;
+}
+
+// ***********************************************************************
+
+BOOL dglDeleteContext(
+ HGLRC a)
+{
+ DGL_ctx* lpCtx;
+ DWORD dwThreadId = GetCurrentThreadId();
+ char argstr[256];
+
+#if 0 // We have enough trouble throwing exceptions as it is... (DaveM)
+ // Validate license
+ if (!dglValidate())
+ return FALSE;
+#endif
+
+ // Is context state ready ?
+ if (!bContextReady)
+ return FALSE;
+
+ ddlogPrintf(DDLOG_SYSTEM, "dglDeleteContext: Deleting context HGLRC=%d, ThreadId=%X", (int)a, dwThreadId);
+
+ // Make sure the HGLRC is in range
+ if (((int) a> DGL_MAX_CONTEXTS) || ((int)a < 0)) {
+ ddlogMessage(DDLOG_ERROR, "dglDeleteCurrent: HGLRC out of range\n");
+ return FALSE;
+ }
+
+ // Make sure context is valid
+ lpCtx = dglGetContextAddress(a);
+ if (!lpCtx->bAllocated) {
+ ddlogPrintf(DDLOG_WARN, "Tried to delete unallocated context HGLRC=%d", (int)a);
+// return FALSE;
+ return TRUE; // HACK: Shuts up "WebLab Viewer Pro". KeithH
+ }
+
+ // Make sure context is de-activated
+ if (a == dglGetCurrentContext()) {
+ ddlogPrintf(DDLOG_WARN, "dglDeleteContext: context HGLRC=%d still active", (int)a);
+ dglMakeCurrent(NULL, NULL);
+ }
+
+#ifdef GLD_THREADS
+ // Serialize access to DirectDraw or DDS operations
+ if (glb.bMultiThreaded)
+ EnterCriticalSection(&CriticalSection);
+#endif
+
+ // We are about to destroy all Direct3D objects.
+ // Therefore we must disable rendering
+ lpCtx->bCanRender = FALSE;
+
+ // This exception handler was installed to catch some
+ // particularly nasty apps. Console apps that call exit()
+ // fall into this catagory (i.e. Win32 Glut).
+
+ // VC cannot successfully implement multiple exception handlers
+ // if more than one exception occurs. Therefore reverting back to
+ // single exception handler as Keith originally had it. (DaveM)
+
+#define WARN_MESSAGE(p) strcpy(argstr, (#p));
+#define SAFE_RELEASE(p) WARN_MESSAGE(p); RELEASE(p);
+
+__try {
+#ifdef _USE_GLD3_WGL
+ WARN_MESSAGE(gl_destroy_framebuffer);
+ if (lpCtx->glBuffer)
+ _mesa_destroy_framebuffer(lpCtx->glBuffer);
+ WARN_MESSAGE(gl_destroy_context);
+ if (lpCtx->glCtx)
+ _mesa_destroy_context(lpCtx->glCtx);
+ WARN_MESSAGE(gl_destroy_visual);
+ if (lpCtx->glVis)
+ _mesa_destroy_visual(lpCtx->glVis);
+
+ _gldDriver.DestroyDrawable(lpCtx);
+#else
+ // Destroy the Mesa context
+ WARN_MESSAGE(gl_destroy_framebuffer);
+ if (lpCtx->glBuffer)
+ (*mesaFuncs.gl_destroy_framebuffer)(lpCtx->glBuffer);
+ WARN_MESSAGE(gl_destroy_context);
+ if (lpCtx->glCtx)
+ (*mesaFuncs.gl_destroy_context)(lpCtx->glCtx);
+ WARN_MESSAGE(gl_destroy_visual);
+ if (lpCtx->glVis)
+ (*mesaFuncs.gl_destroy_visual)(lpCtx->glVis);
+
+ SAFE_RELEASE(lpCtx->m_pvbuf); // release D3D vertex buffer
+ SAFE_RELEASE(lpCtx->m_vbuf); // release D3D vertex buffer
+
+ // Delete the global palette
+ SAFE_RELEASE(lpCtx->lpGlobalPalette);
+
+ // Clean up.
+ if (lpCtx->lpViewport3) {
+ if (lpCtx->lpDev3) IDirect3DDevice3_DeleteViewport(lpCtx->lpDev3, lpCtx->lpViewport3);
+ SAFE_RELEASE(lpCtx->lpViewport3);
+ lpCtx->lpViewport3 = NULL;
+ }
+
+ SAFE_RELEASE(lpCtx->lpDev3);
+ if (lpCtx->lpDepth4) {
+ if (lpCtx->lpBack4)
+ IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpBack4, 0L, lpCtx->lpDepth4);
+ else
+ IDirectDrawSurface4_DeleteAttachedSurface(lpCtx->lpFront4, 0L, lpCtx->lpDepth4);
+ SAFE_RELEASE(lpCtx->lpDepth4);
+ lpCtx->lpDepth4 = NULL;
+ }
+ SAFE_RELEASE(lpCtx->lpBack4);
+ SAFE_RELEASE(lpCtx->lpFront4);
+ if (lpCtx->bFullscreen) {
+ IDirectDraw4_RestoreDisplayMode(lpCtx->lpDD4);
+ IDirectDraw4_SetCooperativeLevel(lpCtx->lpDD4, NULL, DDSCL_NORMAL);
+ }
+ SAFE_RELEASE(lpCtx->lpD3D3);
+ SAFE_RELEASE(lpCtx->lpDD4);
+ SAFE_RELEASE(lpCtx->lpDD1);
+#endif // _ULSE_GLD3_WGL
+
+}
+__except(EXCEPTION_EXECUTE_HANDLER) {
+ ddlogPrintf(DDLOG_WARN, "Exception raised in dglDeleteContext: %s", argstr);
+}
+
+ // Restore the window message handler because this context may be used
+ // again by another window with a *different* message handler. (DaveM)
+ if (lpCtx->lpfnWndProc) {
+ SetWindowLong(lpCtx->hWnd, GWL_WNDPROC, (LONG)lpCtx->lpfnWndProc);
+ lpCtx->lpfnWndProc = (LONG)NULL;
+ }
+
+ lpCtx->bAllocated = FALSE; // This context is now free for use
+
+#ifdef GLD_THREADS
+ // Release serialized access
+ if (glb.bMultiThreaded)
+ LeaveCriticalSection(&CriticalSection);
+#endif
+
+ return TRUE;
+}
+
+// ***********************************************************************
+
+BOOL dglSwapBuffers(
+ HDC hDC)
+{
+ RECT rSrcRect; // Source rectangle
+ RECT rDstRect; // Destination rectangle
+ POINT pt;
+ HRESULT hResult;
+
+ DDBLTFX bltFX;
+ DWORD dwBlitFlags;
+ DDBLTFX *lpBltFX;
+
+// DWORD dwThreadId = GetCurrentThreadId();
+ HGLRC hGLRC = dglGetCurrentContext();
+ DGL_ctx *lpCtx = dglGetContextAddress(hGLRC);
+ HWND hWnd;
+
+ HDC hDCAux; // for memory DC
+ int x,y,w,h; // for memory DC BitBlt
+
+#if 0 // Perhaps not a good idea. Called too often. KH
+ // Validate license
+ if (!dglValidate())
+ return FALSE;
+#endif
+
+ if (!lpCtx) {
+ return TRUE; //FALSE; // No current context
+ }
+
+ if (!lpCtx->bCanRender) {
+ // Don't return false else some apps will bail.
+ return TRUE;
+ }
+
+ hWnd = lpCtx->hWnd;
+ if (hDC != lpCtx->hDC) {
+ ddlogPrintf(DDLOG_WARN, "dglSwapBuffers: HDC=%X does not match HDC=%X for HGLRC=%d", hDC, lpCtx->hDC, hGLRC);
+ hWnd = WindowFromDC(hDC);
+ }
+
+#ifndef _USE_GLD3_WGL
+ // Ensure that the surfaces exist before we tell
+ // the device to render to them.
+ IDirectDraw4_RestoreAllSurfaces(lpCtx->lpDD4);
+
+ // Make sure that the vertex caches have been emptied
+// dglStateChange(lpCtx);
+
+ // Some OpenGL programs don't issue a glFinish - check for it here.
+ if (lpCtx->bSceneStarted) {
+ IDirect3DDevice3_EndScene(lpCtx->lpDev3);
+ lpCtx->bSceneStarted = FALSE;
+ }
+#endif
+
+#if 0
+ // If the calling app is not active then we don't need to Blit/Flip.
+ // We can therefore simply return TRUE.
+ if (!glb.bAppActive)
+ return TRUE;
+ // Addendum: This is WRONG! We should bail if the app is *minimized*,
+ // not merely if the app is just plain 'not active'.
+ // KeithH, 27/May/2000.
+#endif
+
+ // Check for non-window DC = memory DC ?
+ if (hWnd == NULL) {
+ if (GetClipBox(hDC, &rSrcRect) == ERROR)
+ return TRUE;
+ // Use GDI BitBlt instead from compatible DirectDraw DC
+ x = rSrcRect.left;
+ y = rSrcRect.top;
+ w = rSrcRect.right - rSrcRect.left;
+ h = rSrcRect.bottom - rSrcRect.top;
+
+ // Ack. DX8 does not have a GetDC() function...
+ // TODO: Defer to DX7 or DX9 drivers... (DaveM)
+ return TRUE;
+ }
+
+ // Bail if window client region is not drawable, like in Solid Edge
+ if (!IsWindow(hWnd) /* || !IsWindowVisible(hWnd) */ || !GetClientRect(hWnd, &rSrcRect))
+ return TRUE;
+
+#ifdef GLD_THREADS
+ // Serialize access to DirectDraw or DDS operations
+ if (glb.bMultiThreaded)
+ EnterCriticalSection(&CriticalSection);
+#endif
+
+#ifdef _USE_GLD3_WGL
+ // Notify Mesa of impending swap, so Mesa can flush internal buffers.
+ _mesa_notifySwapBuffers(lpCtx->glCtx);
+ // Now perform driver buffer swap
+ _gldDriver.SwapBuffers(lpCtx, hDC, hWnd);
+#else
+ if (lpCtx->bFullscreen) {
+ // Sync with retrace if required
+ if (glb.bWaitForRetrace) {
+ IDirectDraw4_WaitForVerticalBlank(
+ lpCtx->lpDD4,
+ DDWAITVB_BLOCKBEGIN,
+ 0);
+ }
+
+ // Perform the fullscreen flip
+ TRY(IDirectDrawSurface4_Flip(
+ lpCtx->lpFront4,
+ NULL,
+ DDFLIP_WAIT),
+ "dglSwapBuffers: Flip");
+ } else {
+ // Calculate current window position and size
+ pt.x = pt.y = 0;
+ ClientToScreen(hWnd, &pt);
+ GetClientRect(hWnd, &rDstRect);
+ if (rDstRect.right > lpCtx->dwModeWidth)
+ rDstRect.right = lpCtx->dwModeWidth;
+ if (rDstRect.bottom > lpCtx->dwModeHeight)
+ rDstRect.bottom = lpCtx->dwModeHeight;
+ OffsetRect(&rDstRect, pt.x, pt.y);
+ rSrcRect.left = rSrcRect.top = 0;
+ rSrcRect.right = lpCtx->dwWidth;
+ rSrcRect.bottom = lpCtx->dwHeight;
+ if (rSrcRect.right > lpCtx->dwModeWidth)
+ rSrcRect.right = lpCtx->dwModeWidth;
+ if (rSrcRect.bottom > lpCtx->dwModeHeight)
+ rSrcRect.bottom = lpCtx->dwModeHeight;
+
+ if (glb.bWaitForRetrace) {
+ // Sync the blit to the vertical retrace
+ ZeroMemory(&bltFX, sizeof(bltFX));
+ bltFX.dwSize = sizeof(bltFX);
+ bltFX.dwDDFX = DDBLTFX_NOTEARING;
+ dwBlitFlags = DDBLT_WAIT | DDBLT_DDFX;
+ lpBltFX = &bltFX;
+ } else {
+ dwBlitFlags = DDBLT_WAIT;
+ lpBltFX = NULL;
+ }
+
+ // Perform the actual blit
+ TRY(IDirectDrawSurface4_Blt(
+ lpCtx->lpFront4,
+ &rDstRect,
+ lpCtx->lpBack4, // Blit source
+ &rSrcRect,
+ dwBlitFlags,
+ lpBltFX),
+ "dglSwapBuffers: Blt");
+ }
+#endif // _USE_GLD3_WGL
+
+#ifdef GLD_THREADS
+ // Release serialized access
+ if (glb.bMultiThreaded)
+ LeaveCriticalSection(&CriticalSection);
+#endif
+
+ // TODO: Re-instate rendering bitmap snapshot feature??? (DaveM)
+
+ // Render frame is completed
+ ValidateRect(hWnd, NULL);
+ lpCtx->bFrameStarted = FALSE;
+
+ return TRUE;
+}
+
+// ***********************************************************************
diff --git a/mesalib/src/mesa/main/api_arrayelt.c b/mesalib/src/mesa/main/api_arrayelt.c
index 080c20606..3c59e9be3 100644
--- a/mesalib/src/mesa/main/api_arrayelt.c
+++ b/mesalib/src/mesa/main/api_arrayelt.c
@@ -51,7 +51,7 @@ typedef struct {
int offset;
} AEarray;
-typedef void (GLAPIENTRY *attrib_func)( GLuint indx, const void *data );
+typedef void (*attrib_func)( GLuint indx, const void *data );
typedef struct {
const struct gl_client_array *array;
diff --git a/mesalib/src/mesa/main/api_exec.c b/mesalib/src/mesa/main/api_exec.c
index d7a4c90d7..02e39c189 100644
--- a/mesalib/src/mesa/main/api_exec.c
+++ b/mesalib/src/mesa/main/api_exec.c
@@ -104,7 +104,6 @@
#if FEATURE_GL
-
/**
* Initialize a dispatch table with pointers to Mesa's immediate-mode
* commands.
diff --git a/mesalib/src/mesa/main/blend.c b/mesalib/src/mesa/main/blend.c
index c74a16803..22031fd2a 100644
--- a/mesalib/src/mesa/main/blend.c
+++ b/mesalib/src/mesa/main/blend.c
@@ -1,822 +1,822 @@
-/**
- * \file blend.c
- * Blending operations.
- */
-
-/*
- * Mesa 3-D graphics library
- * Version: 6.5.1
- *
- * Copyright (C) 1999-2006 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.
- */
-
-
-
-#include "glheader.h"
-#include "blend.h"
-#include "context.h"
-#include "enums.h"
-#include "macros.h"
-#include "mtypes.h"
-
-
-
-/**
- * Check if given blend source factor is legal.
- * \return GL_TRUE if legal, GL_FALSE otherwise.
- */
-static GLboolean
-legal_src_factor(const struct gl_context *ctx, GLenum factor)
-{
- switch (factor) {
- case GL_SRC_COLOR:
- case GL_ONE_MINUS_SRC_COLOR:
- return ctx->Extensions.NV_blend_square;
- case GL_ZERO:
- case GL_ONE:
- case GL_DST_COLOR:
- case GL_ONE_MINUS_DST_COLOR:
- case GL_SRC_ALPHA:
- case GL_ONE_MINUS_SRC_ALPHA:
- case GL_DST_ALPHA:
- case GL_ONE_MINUS_DST_ALPHA:
- case GL_SRC_ALPHA_SATURATE:
- case GL_CONSTANT_COLOR:
- case GL_ONE_MINUS_CONSTANT_COLOR:
- case GL_CONSTANT_ALPHA:
- case GL_ONE_MINUS_CONSTANT_ALPHA:
- return GL_TRUE;
- default:
- return GL_FALSE;
- }
-}
-
-
-/**
- * Check if given blend destination factor is legal.
- * \return GL_TRUE if legal, GL_FALSE otherwise.
- */
-static GLboolean
-legal_dst_factor(const struct gl_context *ctx, GLenum factor)
-{
- switch (factor) {
- case GL_DST_COLOR:
- case GL_ONE_MINUS_DST_COLOR:
- return ctx->Extensions.NV_blend_square;
- case GL_ZERO:
- case GL_ONE:
- case GL_SRC_COLOR:
- case GL_ONE_MINUS_SRC_COLOR:
- case GL_SRC_ALPHA:
- case GL_ONE_MINUS_SRC_ALPHA:
- case GL_DST_ALPHA:
- case GL_ONE_MINUS_DST_ALPHA:
- case GL_CONSTANT_COLOR:
- case GL_ONE_MINUS_CONSTANT_COLOR:
- case GL_CONSTANT_ALPHA:
- case GL_ONE_MINUS_CONSTANT_ALPHA:
- return GL_TRUE;
- default:
- return GL_FALSE;
- }
-}
-
-
-/**
- * Check if src/dest RGB/A blend factors are legal. If not generate
- * a GL error.
- * \return GL_TRUE if factors are legal, GL_FALSE otherwise.
- */
-static GLboolean
-validate_blend_factors(struct gl_context *ctx, const char *func,
- GLenum sfactorRGB, GLenum dfactorRGB,
- GLenum sfactorA, GLenum dfactorA)
-{
- if (!legal_src_factor(ctx, sfactorRGB)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "%s(sfactorRGB = %s)", func,
- _mesa_lookup_enum_by_nr(sfactorRGB));
- return GL_FALSE;
- }
-
- if (!legal_dst_factor(ctx, dfactorRGB)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "%s(dfactorRGB = %s)", func,
- _mesa_lookup_enum_by_nr(dfactorRGB));
- return GL_FALSE;
- }
-
- if (sfactorA != sfactorRGB && !legal_src_factor(ctx, sfactorA)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "%s(sfactorA = %s)", func,
- _mesa_lookup_enum_by_nr(sfactorA));
- return GL_FALSE;
- }
-
- if (dfactorA != dfactorRGB && !legal_dst_factor(ctx, dfactorA)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "%s(dfactorA = %s)", func,
- _mesa_lookup_enum_by_nr(dfactorA));
- return GL_FALSE;
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Specify the blending operation.
- *
- * \param sfactor source factor operator.
- * \param dfactor destination factor operator.
- *
- * \sa glBlendFunc, glBlendFuncSeparateEXT
- */
-void GLAPIENTRY
-_mesa_BlendFunc( GLenum sfactor, GLenum dfactor )
-{
- _mesa_BlendFuncSeparateEXT(sfactor, dfactor, sfactor, dfactor);
-}
-
-
-/**
- * Set the separate blend source/dest factors for all draw buffers.
- *
- * \param sfactorRGB RGB source factor operator.
- * \param dfactorRGB RGB destination factor operator.
- * \param sfactorA alpha source factor operator.
- * \param dfactorA alpha destination factor operator.
- */
-void GLAPIENTRY
-_mesa_BlendFuncSeparateEXT( GLenum sfactorRGB, GLenum dfactorRGB,
- GLenum sfactorA, GLenum dfactorA )
-{
- GLuint buf, numBuffers;
- GLboolean changed;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBlendFuncSeparate %s %s %s %s\n",
- _mesa_lookup_enum_by_nr(sfactorRGB),
- _mesa_lookup_enum_by_nr(dfactorRGB),
- _mesa_lookup_enum_by_nr(sfactorA),
- _mesa_lookup_enum_by_nr(dfactorA));
-
- if (!validate_blend_factors(ctx, "glBlendFuncSeparate",
- sfactorRGB, dfactorRGB,
- sfactorA, dfactorA)) {
- return;
- }
-
- numBuffers = ctx->Extensions.ARB_draw_buffers_blend
- ? ctx->Const.MaxDrawBuffers : 1;
-
- changed = GL_FALSE;
- for (buf = 0; buf < numBuffers; buf++) {
- if (ctx->Color.Blend[buf].SrcRGB != sfactorRGB ||
- ctx->Color.Blend[buf].DstRGB != dfactorRGB ||
- ctx->Color.Blend[buf].SrcA != sfactorA ||
- ctx->Color.Blend[buf].DstA != dfactorA) {
- changed = GL_TRUE;
- break;
- }
- }
- if (!changed)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
-
- for (buf = 0; buf < numBuffers; buf++) {
- ctx->Color.Blend[buf].SrcRGB = sfactorRGB;
- ctx->Color.Blend[buf].DstRGB = dfactorRGB;
- ctx->Color.Blend[buf].SrcA = sfactorA;
- ctx->Color.Blend[buf].DstA = dfactorA;
- }
- ctx->Color._BlendFuncPerBuffer = GL_FALSE;
-
- if (ctx->Driver.BlendFuncSeparate) {
- ctx->Driver.BlendFuncSeparate(ctx, sfactorRGB, dfactorRGB,
- sfactorA, dfactorA);
- }
-}
-
-
-#if _HAVE_FULL_GL
-
-
-/**
- * Set blend source/dest factors for one color buffer/target.
- */
-void GLAPIENTRY
-_mesa_BlendFunci(GLuint buf, GLenum sfactor, GLenum dfactor)
-{
- _mesa_BlendFuncSeparatei(buf, sfactor, dfactor, sfactor, dfactor);
-}
-
-
-/**
- * Set separate blend source/dest factors for one color buffer/target.
- */
-void GLAPIENTRY
-_mesa_BlendFuncSeparatei(GLuint buf, GLenum sfactorRGB, GLenum dfactorRGB,
- GLenum sfactorA, GLenum dfactorA)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (!ctx->Extensions.ARB_draw_buffers_blend) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glBlendFunc[Separate]i()");
- return;
- }
-
- if (buf >= ctx->Const.MaxDrawBuffers) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glBlendFuncSeparatei(buffer=%u)",
- buf);
- return;
- }
-
- if (!validate_blend_factors(ctx, "glBlendFuncSeparatei",
- sfactorRGB, dfactorRGB,
- sfactorA, dfactorA)) {
- return;
- }
-
- if (ctx->Color.Blend[buf].SrcRGB == sfactorRGB &&
- ctx->Color.Blend[buf].DstRGB == dfactorRGB &&
- ctx->Color.Blend[buf].SrcA == sfactorA &&
- ctx->Color.Blend[buf].DstA == dfactorA)
- return; /* no change */
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
-
- ctx->Color.Blend[buf].SrcRGB = sfactorRGB;
- ctx->Color.Blend[buf].DstRGB = dfactorRGB;
- ctx->Color.Blend[buf].SrcA = sfactorA;
- ctx->Color.Blend[buf].DstA = dfactorA;
- ctx->Color._BlendFuncPerBuffer = GL_TRUE;
-
- if (ctx->Driver.BlendFuncSeparatei) {
- ctx->Driver.BlendFuncSeparatei(ctx, buf, sfactorRGB, dfactorRGB,
- sfactorA, dfactorA);
- }
-}
-
-
-/**
- * Check if given blend equation is legal.
- * \return GL_TRUE if legal, GL_FALSE otherwise.
- */
-static GLboolean
-legal_blend_equation(const struct gl_context *ctx,
- GLenum mode, GLboolean is_separate)
-{
- switch (mode) {
- case GL_FUNC_ADD:
- return GL_TRUE;
- case GL_MIN:
- case GL_MAX:
- return ctx->Extensions.EXT_blend_minmax;
- case GL_LOGIC_OP:
- /* glBlendEquationSeparate cannot take GL_LOGIC_OP as a parameter.
- */
- return ctx->Extensions.EXT_blend_logic_op && !is_separate;
- case GL_FUNC_SUBTRACT:
- case GL_FUNC_REVERSE_SUBTRACT:
- return ctx->Extensions.EXT_blend_subtract;
- default:
- return GL_FALSE;
- }
-}
-
-
-/* This is really an extension function! */
-void GLAPIENTRY
-_mesa_BlendEquation( GLenum mode )
-{
- GLuint buf, numBuffers;
- GLboolean changed;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBlendEquation(%s)\n",
- _mesa_lookup_enum_by_nr(mode));
-
- if (!legal_blend_equation(ctx, mode, GL_FALSE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquation");
- return;
- }
-
- numBuffers = ctx->Extensions.ARB_draw_buffers_blend
- ? ctx->Const.MaxDrawBuffers : 1;
-
- changed = GL_FALSE;
- for (buf = 0; buf < numBuffers; buf++) {
- if (ctx->Color.Blend[buf].EquationRGB != mode ||
- ctx->Color.Blend[buf].EquationA != mode) {
- changed = GL_TRUE;
- break;
- }
- }
- if (!changed)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- for (buf = 0; buf < numBuffers; buf++) {
- ctx->Color.Blend[buf].EquationRGB = mode;
- ctx->Color.Blend[buf].EquationA = mode;
- }
- ctx->Color._BlendEquationPerBuffer = GL_FALSE;
-
- if (ctx->Driver.BlendEquationSeparate)
- (*ctx->Driver.BlendEquationSeparate)( ctx, mode, mode );
-}
-
-
-/**
- * Set blend equation for one color buffer/target.
- */
-void GLAPIENTRY
-_mesa_BlendEquationi(GLuint buf, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBlendEquationi(%u, %s)\n",
- buf, _mesa_lookup_enum_by_nr(mode));
-
- if (buf >= ctx->Const.MaxDrawBuffers) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glBlendFuncSeparatei(buffer=%u)",
- buf);
- return;
- }
-
- if (!legal_blend_equation(ctx, mode, GL_FALSE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationi");
- return;
- }
-
- if (ctx->Color.Blend[buf].EquationRGB == mode &&
- ctx->Color.Blend[buf].EquationA == mode)
- return; /* no change */
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- ctx->Color.Blend[buf].EquationRGB = mode;
- ctx->Color.Blend[buf].EquationA = mode;
- ctx->Color._BlendEquationPerBuffer = GL_TRUE;
-
- if (ctx->Driver.BlendEquationSeparatei)
- ctx->Driver.BlendEquationSeparatei(ctx, buf, mode, mode);
-}
-
-
-void GLAPIENTRY
-_mesa_BlendEquationSeparateEXT( GLenum modeRGB, GLenum modeA )
-{
- GLuint buf, numBuffers;
- GLboolean changed;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBlendEquationSeparateEXT(%s %s)\n",
- _mesa_lookup_enum_by_nr(modeRGB),
- _mesa_lookup_enum_by_nr(modeA));
-
- if ( (modeRGB != modeA) && !ctx->Extensions.EXT_blend_equation_separate ) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glBlendEquationSeparateEXT not supported by driver");
- return;
- }
-
- if (!legal_blend_equation(ctx, modeRGB, GL_TRUE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparateEXT(modeRGB)");
- return;
- }
-
- if (!legal_blend_equation(ctx, modeA, GL_TRUE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparateEXT(modeA)");
- return;
- }
-
- numBuffers = ctx->Extensions.ARB_draw_buffers_blend
- ? ctx->Const.MaxDrawBuffers : 1;
-
- changed = GL_FALSE;
- for (buf = 0; buf < numBuffers; buf++) {
- if (ctx->Color.Blend[buf].EquationRGB != modeRGB ||
- ctx->Color.Blend[buf].EquationA != modeA) {
- changed = GL_TRUE;
- break;
- }
- }
- if (!changed)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- for (buf = 0; buf < numBuffers; buf++) {
- ctx->Color.Blend[buf].EquationRGB = modeRGB;
- ctx->Color.Blend[buf].EquationA = modeA;
- }
- ctx->Color._BlendEquationPerBuffer = GL_FALSE;
-
- if (ctx->Driver.BlendEquationSeparate)
- ctx->Driver.BlendEquationSeparate(ctx, modeRGB, modeA);
-}
-
-
-/**
- * Set separate blend equations for one color buffer/target.
- */
-void
-_mesa_BlendEquationSeparatei(GLuint buf, GLenum modeRGB, GLenum modeA)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBlendEquationSeparatei(%u, %s %s)\n", buf,
- _mesa_lookup_enum_by_nr(modeRGB),
- _mesa_lookup_enum_by_nr(modeA));
-
- if (buf >= ctx->Const.MaxDrawBuffers) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glBlendEquationSeparatei(buffer=%u)",
- buf);
- return;
- }
-
- if (!legal_blend_equation(ctx, modeRGB, GL_TRUE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparatei(modeRGB)");
- return;
- }
-
- if (!legal_blend_equation(ctx, modeA, GL_TRUE)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparatei(modeA)");
- return;
- }
-
- if (ctx->Color.Blend[buf].EquationRGB == modeRGB &&
- ctx->Color.Blend[buf].EquationA == modeA)
- return; /* no change */
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- ctx->Color.Blend[buf].EquationRGB = modeRGB;
- ctx->Color.Blend[buf].EquationA = modeA;
- ctx->Color._BlendEquationPerBuffer = GL_TRUE;
-
- if (ctx->Driver.BlendEquationSeparatei)
- ctx->Driver.BlendEquationSeparatei(ctx, buf, modeRGB, modeA);
-}
-
-
-
-#endif /* _HAVE_FULL_GL */
-
-
-/**
- * Set the blending color.
- *
- * \param red red color component.
- * \param green green color component.
- * \param blue blue color component.
- * \param alpha alpha color component.
- *
- * \sa glBlendColor().
- *
- * Clamps the parameters and updates gl_colorbuffer_attrib::BlendColor. On a
- * change, flushes the vertices and notifies the driver via
- * dd_function_table::BlendColor callback.
- */
-void GLAPIENTRY
-_mesa_BlendColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )
-{
- GLfloat tmp[4];
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- tmp[0] = CLAMP( red, 0.0F, 1.0F );
- tmp[1] = CLAMP( green, 0.0F, 1.0F );
- tmp[2] = CLAMP( blue, 0.0F, 1.0F );
- tmp[3] = CLAMP( alpha, 0.0F, 1.0F );
-
- if (TEST_EQ_4V(tmp, ctx->Color.BlendColor))
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- COPY_4FV( ctx->Color.BlendColor, tmp );
-
- if (ctx->Driver.BlendColor)
- (*ctx->Driver.BlendColor)(ctx, tmp);
-}
-
-
-/**
- * Specify the alpha test function.
- *
- * \param func alpha comparison function.
- * \param ref reference value.
- *
- * Verifies the parameters and updates gl_colorbuffer_attrib.
- * On a change, flushes the vertices and notifies the driver via
- * dd_function_table::AlphaFunc callback.
- */
-void GLAPIENTRY
-_mesa_AlphaFunc( GLenum func, GLclampf ref )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glAlphaFunc(%s, %f)\n",
- _mesa_lookup_enum_by_nr(func), ref);
-
- switch (func) {
- case GL_NEVER:
- case GL_LESS:
- case GL_EQUAL:
- case GL_LEQUAL:
- case GL_GREATER:
- case GL_NOTEQUAL:
- case GL_GEQUAL:
- case GL_ALWAYS:
- ref = CLAMP(ref, 0.0F, 1.0F);
-
- if (ctx->Color.AlphaFunc == func && ctx->Color.AlphaRef == ref)
- return; /* no change */
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- ctx->Color.AlphaFunc = func;
- ctx->Color.AlphaRef = ref;
-
- if (ctx->Driver.AlphaFunc)
- ctx->Driver.AlphaFunc(ctx, func, ref);
- return;
-
- default:
- _mesa_error( ctx, GL_INVALID_ENUM, "glAlphaFunc(func)" );
- return;
- }
-}
-
-
-/**
- * Specify a logic pixel operation for color index rendering.
- *
- * \param opcode operation.
- *
- * Verifies that \p opcode is a valid enum and updates
-gl_colorbuffer_attrib::LogicOp.
- * On a change, flushes the vertices and notifies the driver via the
- * dd_function_table::LogicOpcode callback.
- */
-void GLAPIENTRY
-_mesa_LogicOp( GLenum opcode )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glLogicOp(%s)\n", _mesa_lookup_enum_by_nr(opcode));
-
- switch (opcode) {
- case GL_CLEAR:
- case GL_SET:
- case GL_COPY:
- case GL_COPY_INVERTED:
- case GL_NOOP:
- case GL_INVERT:
- case GL_AND:
- case GL_NAND:
- case GL_OR:
- case GL_NOR:
- case GL_XOR:
- case GL_EQUIV:
- case GL_AND_REVERSE:
- case GL_AND_INVERTED:
- case GL_OR_REVERSE:
- case GL_OR_INVERTED:
- break;
- default:
- _mesa_error( ctx, GL_INVALID_ENUM, "glLogicOp" );
- return;
- }
-
- if (ctx->Color.LogicOp == opcode)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- ctx->Color.LogicOp = opcode;
-
- if (ctx->Driver.LogicOpcode)
- ctx->Driver.LogicOpcode( ctx, opcode );
-}
-
-#if _HAVE_FULL_GL
-void GLAPIENTRY
-_mesa_IndexMask( GLuint mask )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (ctx->Color.IndexMask == mask)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- ctx->Color.IndexMask = mask;
-}
-#endif
-
-
-/**
- * Enable or disable writing of frame buffer color components.
- *
- * \param red whether to mask writing of the red color component.
- * \param green whether to mask writing of the green color component.
- * \param blue whether to mask writing of the blue color component.
- * \param alpha whether to mask writing of the alpha color component.
- *
- * \sa glColorMask().
- *
- * Sets the appropriate value of gl_colorbuffer_attrib::ColorMask. On a
- * change, flushes the vertices and notifies the driver via the
- * dd_function_table::ColorMask callback.
- */
-void GLAPIENTRY
-_mesa_ColorMask( GLboolean red, GLboolean green,
- GLboolean blue, GLboolean alpha )
-{
- GET_CURRENT_CONTEXT(ctx);
- GLubyte tmp[4];
- GLuint i;
- GLboolean flushed;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glColorMask(%d, %d, %d, %d)\n",
- red, green, blue, alpha);
-
- /* Shouldn't have any information about channel depth in core mesa
- * -- should probably store these as the native booleans:
- */
- tmp[RCOMP] = red ? 0xff : 0x0;
- tmp[GCOMP] = green ? 0xff : 0x0;
- tmp[BCOMP] = blue ? 0xff : 0x0;
- tmp[ACOMP] = alpha ? 0xff : 0x0;
-
- flushed = GL_FALSE;
- for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
- if (!TEST_EQ_4V(tmp, ctx->Color.ColorMask[i])) {
- if (!flushed) {
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- }
- flushed = GL_TRUE;
- COPY_4UBV(ctx->Color.ColorMask[i], tmp);
- }
- }
-
- if (ctx->Driver.ColorMask)
- ctx->Driver.ColorMask( ctx, red, green, blue, alpha );
-}
-
-
-/**
- * For GL_EXT_draw_buffers2 and GL3
- */
-void GLAPIENTRY
-_mesa_ColorMaskIndexed( GLuint buf, GLboolean red, GLboolean green,
- GLboolean blue, GLboolean alpha )
-{
- GLubyte tmp[4];
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glColorMaskIndexed %u %d %d %d %d\n",
- buf, red, green, blue, alpha);
-
- if (buf >= ctx->Const.MaxDrawBuffers) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glColorMaskIndexed(buf=%u)", buf);
- return;
- }
-
- /* Shouldn't have any information about channel depth in core mesa
- * -- should probably store these as the native booleans:
- */
- tmp[RCOMP] = red ? 0xff : 0x0;
- tmp[GCOMP] = green ? 0xff : 0x0;
- tmp[BCOMP] = blue ? 0xff : 0x0;
- tmp[ACOMP] = alpha ? 0xff : 0x0;
-
- if (TEST_EQ_4V(tmp, ctx->Color.ColorMask[buf]))
- return;
-
- FLUSH_VERTICES(ctx, _NEW_COLOR);
- COPY_4UBV(ctx->Color.ColorMask[buf], tmp);
-
- if (ctx->Driver.ColorMaskIndexed)
- ctx->Driver.ColorMaskIndexed(ctx, buf, red, green, blue, alpha);
-}
-
-
-extern void GLAPIENTRY
-_mesa_ClampColorARB(GLenum target, GLenum clamp)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (clamp != GL_TRUE && clamp != GL_FALSE && clamp != GL_FIXED_ONLY_ARB) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glClampColorARB(clamp)");
- return;
- }
-
- switch (target) {
- case GL_CLAMP_VERTEX_COLOR_ARB:
- ctx->Light.ClampVertexColor = clamp;
- break;
- case GL_CLAMP_FRAGMENT_COLOR_ARB:
- ctx->Color.ClampFragmentColor = clamp;
- break;
- case GL_CLAMP_READ_COLOR_ARB:
- ctx->Color.ClampReadColor = clamp;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glClampColorARB(target)");
- return;
- }
-}
-
-
-
-
-/**********************************************************************/
-/** \name Initialization */
-/*@{*/
-
-/**
- * Initialization of the context's Color attribute group.
- *
- * \param ctx GL context.
- *
- * Initializes the related fields in the context color attribute group,
- * __struct gl_contextRec::Color.
- */
-void _mesa_init_color( struct gl_context * ctx )
-{
- GLuint i;
-
- /* Color buffer group */
- ctx->Color.IndexMask = ~0u;
- memset(ctx->Color.ColorMask, 0xff, sizeof(ctx->Color.ColorMask));
- ctx->Color.ClearIndex = 0;
- ASSIGN_4V( ctx->Color.ClearColor, 0, 0, 0, 0 );
- ctx->Color.AlphaEnabled = GL_FALSE;
- ctx->Color.AlphaFunc = GL_ALWAYS;
- ctx->Color.AlphaRef = 0;
- ctx->Color.BlendEnabled = 0x0;
- for (i = 0; i < Elements(ctx->Color.Blend); i++) {
- ctx->Color.Blend[i].SrcRGB = GL_ONE;
- ctx->Color.Blend[i].DstRGB = GL_ZERO;
- ctx->Color.Blend[i].SrcA = GL_ONE;
- ctx->Color.Blend[i].DstA = GL_ZERO;
- ctx->Color.Blend[i].EquationRGB = GL_FUNC_ADD;
- ctx->Color.Blend[i].EquationA = GL_FUNC_ADD;
- }
- ASSIGN_4V( ctx->Color.BlendColor, 0.0, 0.0, 0.0, 0.0 );
- ctx->Color.IndexLogicOpEnabled = GL_FALSE;
- ctx->Color.ColorLogicOpEnabled = GL_FALSE;
- ctx->Color._LogicOpEnabled = GL_FALSE;
- ctx->Color.LogicOp = GL_COPY;
- ctx->Color.DitherFlag = GL_TRUE;
-
- if (ctx->Visual.doubleBufferMode) {
- ctx->Color.DrawBuffer[0] = GL_BACK;
- }
- else {
- ctx->Color.DrawBuffer[0] = GL_FRONT;
- }
-
- ctx->Color.ClampFragmentColor = GL_FIXED_ONLY_ARB;
- ctx->Color.ClampReadColor = GL_FIXED_ONLY_ARB;
-}
-
-/*@}*/
+/**
+ * \file blend.c
+ * Blending operations.
+ */
+
+/*
+ * Mesa 3-D graphics library
+ * Version: 6.5.1
+ *
+ * Copyright (C) 1999-2006 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.
+ */
+
+
+
+#include "glheader.h"
+#include "blend.h"
+#include "context.h"
+#include "enums.h"
+#include "macros.h"
+#include "mtypes.h"
+
+
+
+/**
+ * Check if given blend source factor is legal.
+ * \return GL_TRUE if legal, GL_FALSE otherwise.
+ */
+static GLboolean
+legal_src_factor(const struct gl_context *ctx, GLenum factor)
+{
+ switch (factor) {
+ case GL_SRC_COLOR:
+ case GL_ONE_MINUS_SRC_COLOR:
+ return ctx->Extensions.NV_blend_square;
+ case GL_ZERO:
+ case GL_ONE:
+ case GL_DST_COLOR:
+ case GL_ONE_MINUS_DST_COLOR:
+ case GL_SRC_ALPHA:
+ case GL_ONE_MINUS_SRC_ALPHA:
+ case GL_DST_ALPHA:
+ case GL_ONE_MINUS_DST_ALPHA:
+ case GL_SRC_ALPHA_SATURATE:
+ case GL_CONSTANT_COLOR:
+ case GL_ONE_MINUS_CONSTANT_COLOR:
+ case GL_CONSTANT_ALPHA:
+ case GL_ONE_MINUS_CONSTANT_ALPHA:
+ return GL_TRUE;
+ default:
+ return GL_FALSE;
+ }
+}
+
+
+/**
+ * Check if given blend destination factor is legal.
+ * \return GL_TRUE if legal, GL_FALSE otherwise.
+ */
+static GLboolean
+legal_dst_factor(const struct gl_context *ctx, GLenum factor)
+{
+ switch (factor) {
+ case GL_DST_COLOR:
+ case GL_ONE_MINUS_DST_COLOR:
+ return ctx->Extensions.NV_blend_square;
+ case GL_ZERO:
+ case GL_ONE:
+ case GL_SRC_COLOR:
+ case GL_ONE_MINUS_SRC_COLOR:
+ case GL_SRC_ALPHA:
+ case GL_ONE_MINUS_SRC_ALPHA:
+ case GL_DST_ALPHA:
+ case GL_ONE_MINUS_DST_ALPHA:
+ case GL_CONSTANT_COLOR:
+ case GL_ONE_MINUS_CONSTANT_COLOR:
+ case GL_CONSTANT_ALPHA:
+ case GL_ONE_MINUS_CONSTANT_ALPHA:
+ return GL_TRUE;
+ default:
+ return GL_FALSE;
+ }
+}
+
+
+/**
+ * Check if src/dest RGB/A blend factors are legal. If not generate
+ * a GL error.
+ * \return GL_TRUE if factors are legal, GL_FALSE otherwise.
+ */
+static GLboolean
+validate_blend_factors(struct gl_context *ctx, const char *func,
+ GLenum sfactorRGB, GLenum dfactorRGB,
+ GLenum sfactorA, GLenum dfactorA)
+{
+ if (!legal_src_factor(ctx, sfactorRGB)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "%s(sfactorRGB = %s)", func,
+ _mesa_lookup_enum_by_nr(sfactorRGB));
+ return GL_FALSE;
+ }
+
+ if (!legal_dst_factor(ctx, dfactorRGB)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "%s(dfactorRGB = %s)", func,
+ _mesa_lookup_enum_by_nr(dfactorRGB));
+ return GL_FALSE;
+ }
+
+ if (sfactorA != sfactorRGB && !legal_src_factor(ctx, sfactorA)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "%s(sfactorA = %s)", func,
+ _mesa_lookup_enum_by_nr(sfactorA));
+ return GL_FALSE;
+ }
+
+ if (dfactorA != dfactorRGB && !legal_dst_factor(ctx, dfactorA)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "%s(dfactorA = %s)", func,
+ _mesa_lookup_enum_by_nr(dfactorA));
+ return GL_FALSE;
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Specify the blending operation.
+ *
+ * \param sfactor source factor operator.
+ * \param dfactor destination factor operator.
+ *
+ * \sa glBlendFunc, glBlendFuncSeparateEXT
+ */
+void GLAPIENTRY
+_mesa_BlendFunc( GLenum sfactor, GLenum dfactor )
+{
+ _mesa_BlendFuncSeparateEXT(sfactor, dfactor, sfactor, dfactor);
+}
+
+
+/**
+ * Set the separate blend source/dest factors for all draw buffers.
+ *
+ * \param sfactorRGB RGB source factor operator.
+ * \param dfactorRGB RGB destination factor operator.
+ * \param sfactorA alpha source factor operator.
+ * \param dfactorA alpha destination factor operator.
+ */
+void GLAPIENTRY
+_mesa_BlendFuncSeparateEXT( GLenum sfactorRGB, GLenum dfactorRGB,
+ GLenum sfactorA, GLenum dfactorA )
+{
+ GLuint buf, numBuffers;
+ GLboolean changed;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBlendFuncSeparate %s %s %s %s\n",
+ _mesa_lookup_enum_by_nr(sfactorRGB),
+ _mesa_lookup_enum_by_nr(dfactorRGB),
+ _mesa_lookup_enum_by_nr(sfactorA),
+ _mesa_lookup_enum_by_nr(dfactorA));
+
+ if (!validate_blend_factors(ctx, "glBlendFuncSeparate",
+ sfactorRGB, dfactorRGB,
+ sfactorA, dfactorA)) {
+ return;
+ }
+
+ numBuffers = ctx->Extensions.ARB_draw_buffers_blend
+ ? ctx->Const.MaxDrawBuffers : 1;
+
+ changed = GL_FALSE;
+ for (buf = 0; buf < numBuffers; buf++) {
+ if (ctx->Color.Blend[buf].SrcRGB != sfactorRGB ||
+ ctx->Color.Blend[buf].DstRGB != dfactorRGB ||
+ ctx->Color.Blend[buf].SrcA != sfactorA ||
+ ctx->Color.Blend[buf].DstA != dfactorA) {
+ changed = GL_TRUE;
+ break;
+ }
+ }
+ if (!changed)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+
+ for (buf = 0; buf < numBuffers; buf++) {
+ ctx->Color.Blend[buf].SrcRGB = sfactorRGB;
+ ctx->Color.Blend[buf].DstRGB = dfactorRGB;
+ ctx->Color.Blend[buf].SrcA = sfactorA;
+ ctx->Color.Blend[buf].DstA = dfactorA;
+ }
+ ctx->Color._BlendFuncPerBuffer = GL_FALSE;
+
+ if (ctx->Driver.BlendFuncSeparate) {
+ ctx->Driver.BlendFuncSeparate(ctx, sfactorRGB, dfactorRGB,
+ sfactorA, dfactorA);
+ }
+}
+
+
+#if _HAVE_FULL_GL
+
+
+/**
+ * Set blend source/dest factors for one color buffer/target.
+ */
+void GLAPIENTRY
+_mesa_BlendFunci(GLuint buf, GLenum sfactor, GLenum dfactor)
+{
+ _mesa_BlendFuncSeparatei(buf, sfactor, dfactor, sfactor, dfactor);
+}
+
+
+/**
+ * Set separate blend source/dest factors for one color buffer/target.
+ */
+void GLAPIENTRY
+_mesa_BlendFuncSeparatei(GLuint buf, GLenum sfactorRGB, GLenum dfactorRGB,
+ GLenum sfactorA, GLenum dfactorA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (!ctx->Extensions.ARB_draw_buffers_blend) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glBlendFunc[Separate]i()");
+ return;
+ }
+
+ if (buf >= ctx->Const.MaxDrawBuffers) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glBlendFuncSeparatei(buffer=%u)",
+ buf);
+ return;
+ }
+
+ if (!validate_blend_factors(ctx, "glBlendFuncSeparatei",
+ sfactorRGB, dfactorRGB,
+ sfactorA, dfactorA)) {
+ return;
+ }
+
+ if (ctx->Color.Blend[buf].SrcRGB == sfactorRGB &&
+ ctx->Color.Blend[buf].DstRGB == dfactorRGB &&
+ ctx->Color.Blend[buf].SrcA == sfactorA &&
+ ctx->Color.Blend[buf].DstA == dfactorA)
+ return; /* no change */
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+
+ ctx->Color.Blend[buf].SrcRGB = sfactorRGB;
+ ctx->Color.Blend[buf].DstRGB = dfactorRGB;
+ ctx->Color.Blend[buf].SrcA = sfactorA;
+ ctx->Color.Blend[buf].DstA = dfactorA;
+ ctx->Color._BlendFuncPerBuffer = GL_TRUE;
+
+ if (ctx->Driver.BlendFuncSeparatei) {
+ ctx->Driver.BlendFuncSeparatei(ctx, buf, sfactorRGB, dfactorRGB,
+ sfactorA, dfactorA);
+ }
+}
+
+
+/**
+ * Check if given blend equation is legal.
+ * \return GL_TRUE if legal, GL_FALSE otherwise.
+ */
+static GLboolean
+legal_blend_equation(const struct gl_context *ctx,
+ GLenum mode, GLboolean is_separate)
+{
+ switch (mode) {
+ case GL_FUNC_ADD:
+ return GL_TRUE;
+ case GL_MIN:
+ case GL_MAX:
+ return ctx->Extensions.EXT_blend_minmax;
+ case GL_LOGIC_OP:
+ /* glBlendEquationSeparate cannot take GL_LOGIC_OP as a parameter.
+ */
+ return ctx->Extensions.EXT_blend_logic_op && !is_separate;
+ case GL_FUNC_SUBTRACT:
+ case GL_FUNC_REVERSE_SUBTRACT:
+ return ctx->Extensions.EXT_blend_subtract;
+ default:
+ return GL_FALSE;
+ }
+}
+
+
+/* This is really an extension function! */
+void GLAPIENTRY
+_mesa_BlendEquation( GLenum mode )
+{
+ GLuint buf, numBuffers;
+ GLboolean changed;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBlendEquation(%s)\n",
+ _mesa_lookup_enum_by_nr(mode));
+
+ if (!legal_blend_equation(ctx, mode, GL_FALSE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquation");
+ return;
+ }
+
+ numBuffers = ctx->Extensions.ARB_draw_buffers_blend
+ ? ctx->Const.MaxDrawBuffers : 1;
+
+ changed = GL_FALSE;
+ for (buf = 0; buf < numBuffers; buf++) {
+ if (ctx->Color.Blend[buf].EquationRGB != mode ||
+ ctx->Color.Blend[buf].EquationA != mode) {
+ changed = GL_TRUE;
+ break;
+ }
+ }
+ if (!changed)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ for (buf = 0; buf < numBuffers; buf++) {
+ ctx->Color.Blend[buf].EquationRGB = mode;
+ ctx->Color.Blend[buf].EquationA = mode;
+ }
+ ctx->Color._BlendEquationPerBuffer = GL_FALSE;
+
+ if (ctx->Driver.BlendEquationSeparate)
+ (*ctx->Driver.BlendEquationSeparate)( ctx, mode, mode );
+}
+
+
+/**
+ * Set blend equation for one color buffer/target.
+ */
+void GLAPIENTRY
+_mesa_BlendEquationi(GLuint buf, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBlendEquationi(%u, %s)\n",
+ buf, _mesa_lookup_enum_by_nr(mode));
+
+ if (buf >= ctx->Const.MaxDrawBuffers) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glBlendFuncSeparatei(buffer=%u)",
+ buf);
+ return;
+ }
+
+ if (!legal_blend_equation(ctx, mode, GL_FALSE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationi");
+ return;
+ }
+
+ if (ctx->Color.Blend[buf].EquationRGB == mode &&
+ ctx->Color.Blend[buf].EquationA == mode)
+ return; /* no change */
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ ctx->Color.Blend[buf].EquationRGB = mode;
+ ctx->Color.Blend[buf].EquationA = mode;
+ ctx->Color._BlendEquationPerBuffer = GL_TRUE;
+
+ if (ctx->Driver.BlendEquationSeparatei)
+ ctx->Driver.BlendEquationSeparatei(ctx, buf, mode, mode);
+}
+
+
+void GLAPIENTRY
+_mesa_BlendEquationSeparateEXT( GLenum modeRGB, GLenum modeA )
+{
+ GLuint buf, numBuffers;
+ GLboolean changed;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBlendEquationSeparateEXT(%s %s)\n",
+ _mesa_lookup_enum_by_nr(modeRGB),
+ _mesa_lookup_enum_by_nr(modeA));
+
+ if ( (modeRGB != modeA) && !ctx->Extensions.EXT_blend_equation_separate ) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glBlendEquationSeparateEXT not supported by driver");
+ return;
+ }
+
+ if (!legal_blend_equation(ctx, modeRGB, GL_TRUE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparateEXT(modeRGB)");
+ return;
+ }
+
+ if (!legal_blend_equation(ctx, modeA, GL_TRUE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparateEXT(modeA)");
+ return;
+ }
+
+ numBuffers = ctx->Extensions.ARB_draw_buffers_blend
+ ? ctx->Const.MaxDrawBuffers : 1;
+
+ changed = GL_FALSE;
+ for (buf = 0; buf < numBuffers; buf++) {
+ if (ctx->Color.Blend[buf].EquationRGB != modeRGB ||
+ ctx->Color.Blend[buf].EquationA != modeA) {
+ changed = GL_TRUE;
+ break;
+ }
+ }
+ if (!changed)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ for (buf = 0; buf < numBuffers; buf++) {
+ ctx->Color.Blend[buf].EquationRGB = modeRGB;
+ ctx->Color.Blend[buf].EquationA = modeA;
+ }
+ ctx->Color._BlendEquationPerBuffer = GL_FALSE;
+
+ if (ctx->Driver.BlendEquationSeparate)
+ ctx->Driver.BlendEquationSeparate(ctx, modeRGB, modeA);
+}
+
+
+/**
+ * Set separate blend equations for one color buffer/target.
+ */
+void
+_mesa_BlendEquationSeparatei(GLuint buf, GLenum modeRGB, GLenum modeA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBlendEquationSeparatei(%u, %s %s)\n", buf,
+ _mesa_lookup_enum_by_nr(modeRGB),
+ _mesa_lookup_enum_by_nr(modeA));
+
+ if (buf >= ctx->Const.MaxDrawBuffers) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glBlendEquationSeparatei(buffer=%u)",
+ buf);
+ return;
+ }
+
+ if (!legal_blend_equation(ctx, modeRGB, GL_TRUE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparatei(modeRGB)");
+ return;
+ }
+
+ if (!legal_blend_equation(ctx, modeA, GL_TRUE)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBlendEquationSeparatei(modeA)");
+ return;
+ }
+
+ if (ctx->Color.Blend[buf].EquationRGB == modeRGB &&
+ ctx->Color.Blend[buf].EquationA == modeA)
+ return; /* no change */
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ ctx->Color.Blend[buf].EquationRGB = modeRGB;
+ ctx->Color.Blend[buf].EquationA = modeA;
+ ctx->Color._BlendEquationPerBuffer = GL_TRUE;
+
+ if (ctx->Driver.BlendEquationSeparatei)
+ ctx->Driver.BlendEquationSeparatei(ctx, buf, modeRGB, modeA);
+}
+
+
+
+#endif /* _HAVE_FULL_GL */
+
+
+/**
+ * Set the blending color.
+ *
+ * \param red red color component.
+ * \param green green color component.
+ * \param blue blue color component.
+ * \param alpha alpha color component.
+ *
+ * \sa glBlendColor().
+ *
+ * Clamps the parameters and updates gl_colorbuffer_attrib::BlendColor. On a
+ * change, flushes the vertices and notifies the driver via
+ * dd_function_table::BlendColor callback.
+ */
+void GLAPIENTRY
+_mesa_BlendColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha )
+{
+ GLfloat tmp[4];
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ tmp[0] = CLAMP( red, 0.0F, 1.0F );
+ tmp[1] = CLAMP( green, 0.0F, 1.0F );
+ tmp[2] = CLAMP( blue, 0.0F, 1.0F );
+ tmp[3] = CLAMP( alpha, 0.0F, 1.0F );
+
+ if (TEST_EQ_4V(tmp, ctx->Color.BlendColor))
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ COPY_4FV( ctx->Color.BlendColor, tmp );
+
+ if (ctx->Driver.BlendColor)
+ (*ctx->Driver.BlendColor)(ctx, tmp);
+}
+
+
+/**
+ * Specify the alpha test function.
+ *
+ * \param func alpha comparison function.
+ * \param ref reference value.
+ *
+ * Verifies the parameters and updates gl_colorbuffer_attrib.
+ * On a change, flushes the vertices and notifies the driver via
+ * dd_function_table::AlphaFunc callback.
+ */
+void GLAPIENTRY
+_mesa_AlphaFunc( GLenum func, GLclampf ref )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glAlphaFunc(%s, %f)\n",
+ _mesa_lookup_enum_by_nr(func), ref);
+
+ switch (func) {
+ case GL_NEVER:
+ case GL_LESS:
+ case GL_EQUAL:
+ case GL_LEQUAL:
+ case GL_GREATER:
+ case GL_NOTEQUAL:
+ case GL_GEQUAL:
+ case GL_ALWAYS:
+ ref = CLAMP(ref, 0.0F, 1.0F);
+
+ if (ctx->Color.AlphaFunc == func && ctx->Color.AlphaRef == ref)
+ return; /* no change */
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ ctx->Color.AlphaFunc = func;
+ ctx->Color.AlphaRef = ref;
+
+ if (ctx->Driver.AlphaFunc)
+ ctx->Driver.AlphaFunc(ctx, func, ref);
+ return;
+
+ default:
+ _mesa_error( ctx, GL_INVALID_ENUM, "glAlphaFunc(func)" );
+ return;
+ }
+}
+
+
+/**
+ * Specify a logic pixel operation for color index rendering.
+ *
+ * \param opcode operation.
+ *
+ * Verifies that \p opcode is a valid enum and updates
+gl_colorbuffer_attrib::LogicOp.
+ * On a change, flushes the vertices and notifies the driver via the
+ * dd_function_table::LogicOpcode callback.
+ */
+void GLAPIENTRY
+_mesa_LogicOp( GLenum opcode )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glLogicOp(%s)\n", _mesa_lookup_enum_by_nr(opcode));
+
+ switch (opcode) {
+ case GL_CLEAR:
+ case GL_SET:
+ case GL_COPY:
+ case GL_COPY_INVERTED:
+ case GL_NOOP:
+ case GL_INVERT:
+ case GL_AND:
+ case GL_NAND:
+ case GL_OR:
+ case GL_NOR:
+ case GL_XOR:
+ case GL_EQUIV:
+ case GL_AND_REVERSE:
+ case GL_AND_INVERTED:
+ case GL_OR_REVERSE:
+ case GL_OR_INVERTED:
+ break;
+ default:
+ _mesa_error( ctx, GL_INVALID_ENUM, "glLogicOp" );
+ return;
+ }
+
+ if (ctx->Color.LogicOp == opcode)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ ctx->Color.LogicOp = opcode;
+
+ if (ctx->Driver.LogicOpcode)
+ ctx->Driver.LogicOpcode( ctx, opcode );
+}
+
+#if _HAVE_FULL_GL
+void GLAPIENTRY
+_mesa_IndexMask( GLuint mask )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (ctx->Color.IndexMask == mask)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ ctx->Color.IndexMask = mask;
+}
+#endif
+
+
+/**
+ * Enable or disable writing of frame buffer color components.
+ *
+ * \param red whether to mask writing of the red color component.
+ * \param green whether to mask writing of the green color component.
+ * \param blue whether to mask writing of the blue color component.
+ * \param alpha whether to mask writing of the alpha color component.
+ *
+ * \sa glColorMask().
+ *
+ * Sets the appropriate value of gl_colorbuffer_attrib::ColorMask. On a
+ * change, flushes the vertices and notifies the driver via the
+ * dd_function_table::ColorMask callback.
+ */
+void GLAPIENTRY
+_mesa_ColorMask( GLboolean red, GLboolean green,
+ GLboolean blue, GLboolean alpha )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLubyte tmp[4];
+ GLuint i;
+ GLboolean flushed;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glColorMask(%d, %d, %d, %d)\n",
+ red, green, blue, alpha);
+
+ /* Shouldn't have any information about channel depth in core mesa
+ * -- should probably store these as the native booleans:
+ */
+ tmp[RCOMP] = red ? 0xff : 0x0;
+ tmp[GCOMP] = green ? 0xff : 0x0;
+ tmp[BCOMP] = blue ? 0xff : 0x0;
+ tmp[ACOMP] = alpha ? 0xff : 0x0;
+
+ flushed = GL_FALSE;
+ for (i = 0; i < ctx->Const.MaxDrawBuffers; i++) {
+ if (!TEST_EQ_4V(tmp, ctx->Color.ColorMask[i])) {
+ if (!flushed) {
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ }
+ flushed = GL_TRUE;
+ COPY_4UBV(ctx->Color.ColorMask[i], tmp);
+ }
+ }
+
+ if (ctx->Driver.ColorMask)
+ ctx->Driver.ColorMask( ctx, red, green, blue, alpha );
+}
+
+
+/**
+ * For GL_EXT_draw_buffers2 and GL3
+ */
+void GLAPIENTRY
+_mesa_ColorMaskIndexed( GLuint buf, GLboolean red, GLboolean green,
+ GLboolean blue, GLboolean alpha )
+{
+ GLubyte tmp[4];
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glColorMaskIndexed %u %d %d %d %d\n",
+ buf, red, green, blue, alpha);
+
+ if (buf >= ctx->Const.MaxDrawBuffers) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glColorMaskIndexed(buf=%u)", buf);
+ return;
+ }
+
+ /* Shouldn't have any information about channel depth in core mesa
+ * -- should probably store these as the native booleans:
+ */
+ tmp[RCOMP] = red ? 0xff : 0x0;
+ tmp[GCOMP] = green ? 0xff : 0x0;
+ tmp[BCOMP] = blue ? 0xff : 0x0;
+ tmp[ACOMP] = alpha ? 0xff : 0x0;
+
+ if (TEST_EQ_4V(tmp, ctx->Color.ColorMask[buf]))
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_COLOR);
+ COPY_4UBV(ctx->Color.ColorMask[buf], tmp);
+
+ if (ctx->Driver.ColorMaskIndexed)
+ ctx->Driver.ColorMaskIndexed(ctx, buf, red, green, blue, alpha);
+}
+
+
+extern void GLAPIENTRY
+_mesa_ClampColorARB(GLenum target, GLenum clamp)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (clamp != GL_TRUE && clamp != GL_FALSE && clamp != GL_FIXED_ONLY_ARB) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glClampColorARB(clamp)");
+ return;
+ }
+
+ switch (target) {
+ case GL_CLAMP_VERTEX_COLOR_ARB:
+ ctx->Light.ClampVertexColor = clamp;
+ break;
+ case GL_CLAMP_FRAGMENT_COLOR_ARB:
+ ctx->Color.ClampFragmentColor = clamp;
+ break;
+ case GL_CLAMP_READ_COLOR_ARB:
+ ctx->Color.ClampReadColor = clamp;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glClampColorARB(target)");
+ return;
+ }
+}
+
+
+
+
+/**********************************************************************/
+/** \name Initialization */
+/*@{*/
+
+/**
+ * Initialization of the context's Color attribute group.
+ *
+ * \param ctx GL context.
+ *
+ * Initializes the related fields in the context color attribute group,
+ * __struct gl_contextRec::Color.
+ */
+void _mesa_init_color( struct gl_context * ctx )
+{
+ GLuint i;
+
+ /* Color buffer group */
+ ctx->Color.IndexMask = ~0u;
+ memset(ctx->Color.ColorMask, 0xff, sizeof(ctx->Color.ColorMask));
+ ctx->Color.ClearIndex = 0;
+ ASSIGN_4V( ctx->Color.ClearColor, 0, 0, 0, 0 );
+ ctx->Color.AlphaEnabled = GL_FALSE;
+ ctx->Color.AlphaFunc = GL_ALWAYS;
+ ctx->Color.AlphaRef = 0;
+ ctx->Color.BlendEnabled = 0x0;
+ for (i = 0; i < Elements(ctx->Color.Blend); i++) {
+ ctx->Color.Blend[i].SrcRGB = GL_ONE;
+ ctx->Color.Blend[i].DstRGB = GL_ZERO;
+ ctx->Color.Blend[i].SrcA = GL_ONE;
+ ctx->Color.Blend[i].DstA = GL_ZERO;
+ ctx->Color.Blend[i].EquationRGB = GL_FUNC_ADD;
+ ctx->Color.Blend[i].EquationA = GL_FUNC_ADD;
+ }
+ ASSIGN_4V( ctx->Color.BlendColor, 0.0, 0.0, 0.0, 0.0 );
+ ctx->Color.IndexLogicOpEnabled = GL_FALSE;
+ ctx->Color.ColorLogicOpEnabled = GL_FALSE;
+ ctx->Color._LogicOpEnabled = GL_FALSE;
+ ctx->Color.LogicOp = GL_COPY;
+ ctx->Color.DitherFlag = GL_TRUE;
+
+ if (ctx->Visual.doubleBufferMode) {
+ ctx->Color.DrawBuffer[0] = GL_BACK;
+ }
+ else {
+ ctx->Color.DrawBuffer[0] = GL_FRONT;
+ }
+
+ ctx->Color.ClampFragmentColor = GL_FIXED_ONLY_ARB;
+ ctx->Color.ClampReadColor = GL_FIXED_ONLY_ARB;
+}
+
+/*@}*/
diff --git a/mesalib/src/mesa/main/bufferobj.c b/mesalib/src/mesa/main/bufferobj.c
index 75afae0ad..2de4602b8 100644
--- a/mesalib/src/mesa/main/bufferobj.c
+++ b/mesalib/src/mesa/main/bufferobj.c
@@ -1,2158 +1,2158 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.6
- *
- * Copyright (C) 1999-2008 Brian Paul All Rights Reserved.
- * Copyright (C) 2009 VMware, Inc. 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 bufferobj.c
- * \brief Functions for the GL_ARB_vertex/pixel_buffer_object extensions.
- * \author Brian Paul, Ian Romanick
- */
-
-
-#include "glheader.h"
-#include "enums.h"
-#include "hash.h"
-#include "imports.h"
-#include "image.h"
-#include "context.h"
-#include "bufferobj.h"
-#include "fbobject.h"
-#include "mfeatures.h"
-#include "mtypes.h"
-#include "texobj.h"
-
-
-/* Debug flags */
-/*#define VBO_DEBUG*/
-/*#define BOUNDS_CHECK*/
-
-
-#if FEATURE_OES_mapbuffer
-#define DEFAULT_ACCESS GL_MAP_WRITE_BIT
-#else
-#define DEFAULT_ACCESS (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)
-#endif
-
-
-/**
- * Used as a placeholder for buffer objects between glGenBuffers() and
- * glBindBuffer() so that glIsBuffer() can work correctly.
- */
-static struct gl_buffer_object DummyBufferObject;
-
-
-/**
- * Return pointer to address of a buffer object target.
- * \param ctx the GL context
- * \param target the buffer object target to be retrieved.
- * \return pointer to pointer to the buffer object bound to \c target in the
- * specified context or \c NULL if \c target is invalid.
- */
-static INLINE struct gl_buffer_object **
-get_buffer_target(struct gl_context *ctx, GLenum target)
-{
- switch (target) {
- case GL_ARRAY_BUFFER_ARB:
- return &ctx->Array.ArrayBufferObj;
- case GL_ELEMENT_ARRAY_BUFFER_ARB:
- return &ctx->Array.ElementArrayBufferObj;
- case GL_PIXEL_PACK_BUFFER_EXT:
- return &ctx->Pack.BufferObj;
- case GL_PIXEL_UNPACK_BUFFER_EXT:
- return &ctx->Unpack.BufferObj;
- case GL_COPY_READ_BUFFER:
- return &ctx->CopyReadBuffer;
- case GL_COPY_WRITE_BUFFER:
- return &ctx->CopyWriteBuffer;
-#if FEATURE_EXT_transform_feedback
- case GL_TRANSFORM_FEEDBACK_BUFFER:
- if (ctx->Extensions.EXT_transform_feedback) {
- return &ctx->TransformFeedback.CurrentBuffer;
- }
- break;
-#endif
- default:
- return NULL;
- }
- return NULL;
-}
-
-
-/**
- * Get the buffer object bound to the specified target in a GL context.
- * \param ctx the GL context
- * \param target the buffer object target to be retrieved.
- * \return pointer to the buffer object bound to \c target in the
- * specified context or \c NULL if \c target is invalid.
- */
-static INLINE struct gl_buffer_object *
-get_buffer(struct gl_context *ctx, GLenum target)
-{
- struct gl_buffer_object **bufObj = get_buffer_target(ctx, target);
- if (bufObj)
- return *bufObj;
- return NULL;
-}
-
-
-/**
- * Convert a GLbitfield describing the mapped buffer access flags
- * into one of GL_READ_WRITE, GL_READ_ONLY, or GL_WRITE_ONLY.
- */
-static GLenum
-simplified_access_mode(GLbitfield access)
-{
- const GLbitfield rwFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
- if ((access & rwFlags) == rwFlags)
- return GL_READ_WRITE;
- if ((access & GL_MAP_READ_BIT) == GL_MAP_READ_BIT)
- return GL_READ_ONLY;
- if ((access & GL_MAP_WRITE_BIT) == GL_MAP_WRITE_BIT)
- return GL_WRITE_ONLY;
- return GL_READ_WRITE; /* this should never happen, but no big deal */
-}
-
-
-/**
- * Tests the subdata range parameters and sets the GL error code for
- * \c glBufferSubDataARB and \c glGetBufferSubDataARB.
- *
- * \param ctx GL context.
- * \param target Buffer object target on which to operate.
- * \param offset Offset of the first byte of the subdata range.
- * \param size Size, in bytes, of the subdata range.
- * \param caller Name of calling function for recording errors.
- * \return A pointer to the buffer object bound to \c target in the
- * specified context or \c NULL if any of the parameter or state
- * conditions for \c glBufferSubDataARB or \c glGetBufferSubDataARB
- * are invalid.
- *
- * \sa glBufferSubDataARB, glGetBufferSubDataARB
- */
-static struct gl_buffer_object *
-buffer_object_subdata_range_good( struct gl_context * ctx, GLenum target,
- GLintptrARB offset, GLsizeiptrARB size,
- const char *caller )
-{
- struct gl_buffer_object *bufObj;
-
- if (size < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "%s(size < 0)", caller);
- return NULL;
- }
-
- if (offset < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "%s(offset < 0)", caller);
- return NULL;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "%s(target)", caller);
- return NULL;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
- return NULL;
- }
- if (offset + size > bufObj->Size) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "%s(size + offset > buffer size)", caller);
- return NULL;
- }
- if (_mesa_bufferobj_mapped(bufObj)) {
- /* Buffer is currently mapped */
- _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
- return NULL;
- }
-
- return bufObj;
-}
-
-
-/**
- * Allocate and initialize a new buffer object.
- *
- * Default callback for the \c dd_function_table::NewBufferObject() hook.
- */
-static struct gl_buffer_object *
-_mesa_new_buffer_object( struct gl_context *ctx, GLuint name, GLenum target )
-{
- struct gl_buffer_object *obj;
-
- (void) ctx;
-
- obj = MALLOC_STRUCT(gl_buffer_object);
- _mesa_initialize_buffer_object(obj, name, target);
- return obj;
-}
-
-
-/**
- * Delete a buffer object.
- *
- * Default callback for the \c dd_function_table::DeleteBuffer() hook.
- */
-static void
-_mesa_delete_buffer_object( struct gl_context *ctx, struct gl_buffer_object *bufObj )
-{
- (void) ctx;
-
- if (bufObj->Data)
- free(bufObj->Data);
-
- /* assign strange values here to help w/ debugging */
- bufObj->RefCount = -1000;
- bufObj->Name = ~0;
-
- _glthread_DESTROY_MUTEX(bufObj->Mutex);
- free(bufObj);
-}
-
-
-
-/**
- * Set ptr to bufObj w/ reference counting.
- */
-void
-_mesa_reference_buffer_object(struct gl_context *ctx,
- struct gl_buffer_object **ptr,
- struct gl_buffer_object *bufObj)
-{
- if (*ptr == bufObj)
- return;
-
- if (*ptr) {
- /* Unreference the old buffer */
- GLboolean deleteFlag = GL_FALSE;
- struct gl_buffer_object *oldObj = *ptr;
-
- _glthread_LOCK_MUTEX(oldObj->Mutex);
- ASSERT(oldObj->RefCount > 0);
- oldObj->RefCount--;
-#if 0
- printf("BufferObj %p %d DECR to %d\n",
- (void *) oldObj, oldObj->Name, oldObj->RefCount);
-#endif
- deleteFlag = (oldObj->RefCount == 0);
- _glthread_UNLOCK_MUTEX(oldObj->Mutex);
-
- if (deleteFlag) {
-
- /* some sanity checking: don't delete a buffer still in use */
-#if 0
- /* unfortunately, these tests are invalid during context tear-down */
- ASSERT(ctx->Array.ArrayBufferObj != bufObj);
- ASSERT(ctx->Array.ElementArrayBufferObj != bufObj);
- ASSERT(ctx->Array.ArrayObj->Vertex.BufferObj != bufObj);
-#endif
-
- ASSERT(ctx->Driver.DeleteBuffer);
- ctx->Driver.DeleteBuffer(ctx, oldObj);
- }
-
- *ptr = NULL;
- }
- ASSERT(!*ptr);
-
- if (bufObj) {
- /* reference new buffer */
- _glthread_LOCK_MUTEX(bufObj->Mutex);
- if (bufObj->RefCount == 0) {
- /* this buffer's being deleted (look just above) */
- /* Not sure this can every really happen. Warn if it does. */
- _mesa_problem(NULL, "referencing deleted buffer object");
- *ptr = NULL;
- }
- else {
- bufObj->RefCount++;
-#if 0
- printf("BufferObj %p %d INCR to %d\n",
- (void *) bufObj, bufObj->Name, bufObj->RefCount);
-#endif
- *ptr = bufObj;
- }
- _glthread_UNLOCK_MUTEX(bufObj->Mutex);
- }
-}
-
-
-/**
- * Initialize a buffer object to default values.
- */
-void
-_mesa_initialize_buffer_object( struct gl_buffer_object *obj,
- GLuint name, GLenum target )
-{
- (void) target;
-
- memset(obj, 0, sizeof(struct gl_buffer_object));
- _glthread_INIT_MUTEX(obj->Mutex);
- obj->RefCount = 1;
- obj->Name = name;
- obj->Usage = GL_STATIC_DRAW_ARB;
- obj->AccessFlags = DEFAULT_ACCESS;
-}
-
-
-/**
- * Allocate space for and store data in a buffer object. Any data that was
- * previously stored in the buffer object is lost. If \c data is \c NULL,
- * memory will be allocated, but no copy will occur.
- *
- * This is the default callback for \c dd_function_table::BufferData()
- * Note that all GL error checking will have been done already.
- *
- * \param ctx GL context.
- * \param target Buffer object target on which to operate.
- * \param size Size, in bytes, of the new data store.
- * \param data Pointer to the data to store in the buffer object. This
- * pointer may be \c NULL.
- * \param usage Hints about how the data will be used.
- * \param bufObj Object to be used.
- *
- * \return GL_TRUE for success, GL_FALSE for failure
- * \sa glBufferDataARB, dd_function_table::BufferData.
- */
-static GLboolean
-_mesa_buffer_data( struct gl_context *ctx, GLenum target, GLsizeiptrARB size,
- const GLvoid * data, GLenum usage,
- struct gl_buffer_object * bufObj )
-{
- void * new_data;
-
- (void) ctx; (void) target;
-
- new_data = _mesa_realloc( bufObj->Data, bufObj->Size, size );
- if (new_data) {
- bufObj->Data = (GLubyte *) new_data;
- bufObj->Size = size;
- bufObj->Usage = usage;
-
- if (data) {
- memcpy( bufObj->Data, data, size );
- }
-
- return GL_TRUE;
- }
- else {
- return GL_FALSE;
- }
-}
-
-
-/**
- * Replace data in a subrange of buffer object. If the data range
- * specified by \c size + \c offset extends beyond the end of the buffer or
- * if \c data is \c NULL, no copy is performed.
- *
- * This is the default callback for \c dd_function_table::BufferSubData()
- * Note that all GL error checking will have been done already.
- *
- * \param ctx GL context.
- * \param target Buffer object target on which to operate.
- * \param offset Offset of the first byte to be modified.
- * \param size Size, in bytes, of the data range.
- * \param data Pointer to the data to store in the buffer object.
- * \param bufObj Object to be used.
- *
- * \sa glBufferSubDataARB, dd_function_table::BufferSubData.
- */
-static void
-_mesa_buffer_subdata( struct gl_context *ctx, GLenum target, GLintptrARB offset,
- GLsizeiptrARB size, const GLvoid * data,
- struct gl_buffer_object * bufObj )
-{
- (void) ctx; (void) target;
-
- /* this should have been caught in _mesa_BufferSubData() */
- ASSERT(size + offset <= bufObj->Size);
-
- if (bufObj->Data) {
- memcpy( (GLubyte *) bufObj->Data + offset, data, size );
- }
-}
-
-
-/**
- * Retrieve data from a subrange of buffer object. If the data range
- * specified by \c size + \c offset extends beyond the end of the buffer or
- * if \c data is \c NULL, no copy is performed.
- *
- * This is the default callback for \c dd_function_table::GetBufferSubData()
- * Note that all GL error checking will have been done already.
- *
- * \param ctx GL context.
- * \param target Buffer object target on which to operate.
- * \param offset Offset of the first byte to be fetched.
- * \param size Size, in bytes, of the data range.
- * \param data Destination for data
- * \param bufObj Object to be used.
- *
- * \sa glBufferGetSubDataARB, dd_function_table::GetBufferSubData.
- */
-static void
-_mesa_buffer_get_subdata( struct gl_context *ctx, GLenum target, GLintptrARB offset,
- GLsizeiptrARB size, GLvoid * data,
- struct gl_buffer_object * bufObj )
-{
- (void) ctx; (void) target;
-
- if (bufObj->Data && ((GLsizeiptrARB) (size + offset) <= bufObj->Size)) {
- memcpy( data, (GLubyte *) bufObj->Data + offset, size );
- }
-}
-
-
-/**
- * Default callback for \c dd_function_tabel::MapBuffer().
- *
- * The function parameters will have been already tested for errors.
- *
- * \param ctx GL context.
- * \param target Buffer object target on which to operate.
- * \param access Information about how the buffer will be accessed.
- * \param bufObj Object to be mapped.
- * \return A pointer to the object's internal data store that can be accessed
- * by the processor
- *
- * \sa glMapBufferARB, dd_function_table::MapBuffer
- */
-static void *
-_mesa_buffer_map( struct gl_context *ctx, GLenum target, GLenum access,
- struct gl_buffer_object *bufObj )
-{
- (void) ctx;
- (void) target;
- (void) access;
- /* Just return a direct pointer to the data */
- if (_mesa_bufferobj_mapped(bufObj)) {
- /* already mapped! */
- return NULL;
- }
- bufObj->Pointer = bufObj->Data;
- bufObj->Length = bufObj->Size;
- bufObj->Offset = 0;
- return bufObj->Pointer;
-}
-
-
-/**
- * Default fallback for \c dd_function_table::MapBufferRange().
- * Called via glMapBufferRange().
- */
-static void *
-_mesa_buffer_map_range( struct gl_context *ctx, GLenum target, GLintptr offset,
- GLsizeiptr length, GLbitfield access,
- struct gl_buffer_object *bufObj )
-{
- (void) ctx;
- (void) target;
- assert(!_mesa_bufferobj_mapped(bufObj));
- /* Just return a direct pointer to the data */
- bufObj->Pointer = bufObj->Data + offset;
- bufObj->Length = length;
- bufObj->Offset = offset;
- bufObj->AccessFlags = access;
- return bufObj->Pointer;
-}
-
-
-/**
- * Default fallback for \c dd_function_table::FlushMappedBufferRange().
- * Called via glFlushMappedBufferRange().
- */
-static void
-_mesa_buffer_flush_mapped_range( struct gl_context *ctx, GLenum target,
- GLintptr offset, GLsizeiptr length,
- struct gl_buffer_object *obj )
-{
- (void) ctx;
- (void) target;
- (void) offset;
- (void) length;
- (void) obj;
- /* no-op */
-}
-
-
-/**
- * Default callback for \c dd_function_table::MapBuffer().
- *
- * The input parameters will have been already tested for errors.
- *
- * \sa glUnmapBufferARB, dd_function_table::UnmapBuffer
- */
-static GLboolean
-_mesa_buffer_unmap( struct gl_context *ctx, GLenum target,
- struct gl_buffer_object *bufObj )
-{
- (void) ctx;
- (void) target;
- /* XXX we might assert here that bufObj->Pointer is non-null */
- bufObj->Pointer = NULL;
- bufObj->Length = 0;
- bufObj->Offset = 0;
- bufObj->AccessFlags = 0x0;
- return GL_TRUE;
-}
-
-
-/**
- * Default fallback for \c dd_function_table::CopyBufferSubData().
- * Called via glCopyBuffserSubData().
- */
-static void
-_mesa_copy_buffer_subdata(struct gl_context *ctx,
- struct gl_buffer_object *src,
- struct gl_buffer_object *dst,
- GLintptr readOffset, GLintptr writeOffset,
- GLsizeiptr size)
-{
- GLubyte *srcPtr, *dstPtr;
-
- /* buffer should not already be mapped */
- assert(!_mesa_bufferobj_mapped(src));
- assert(!_mesa_bufferobj_mapped(dst));
-
- srcPtr = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_COPY_READ_BUFFER,
- GL_READ_ONLY, src);
- dstPtr = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_COPY_WRITE_BUFFER,
- GL_WRITE_ONLY, dst);
-
- if (srcPtr && dstPtr)
- memcpy(dstPtr + writeOffset, srcPtr + readOffset, size);
-
- ctx->Driver.UnmapBuffer(ctx, GL_COPY_READ_BUFFER, src);
- ctx->Driver.UnmapBuffer(ctx, GL_COPY_WRITE_BUFFER, dst);
-}
-
-
-
-/**
- * Initialize the state associated with buffer objects
- */
-void
-_mesa_init_buffer_objects( struct gl_context *ctx )
-{
- memset(&DummyBufferObject, 0, sizeof(DummyBufferObject));
- DummyBufferObject.RefCount = 1000*1000*1000; /* never delete */
-
- _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj,
- ctx->Shared->NullBufferObj);
- _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj,
- ctx->Shared->NullBufferObj);
-
- _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer,
- ctx->Shared->NullBufferObj);
- _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer,
- ctx->Shared->NullBufferObj);
-}
-
-
-void
-_mesa_free_buffer_objects( struct gl_context *ctx )
-{
- _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
- _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj, NULL);
-
- _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer, NULL);
- _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer, NULL);
-}
-
-
-/**
- * Bind the specified target to buffer for the specified context.
- * Called by glBindBuffer() and other functions.
- */
-static void
-bind_buffer_object(struct gl_context *ctx, GLenum target, GLuint buffer)
-{
- struct gl_buffer_object *oldBufObj;
- struct gl_buffer_object *newBufObj = NULL;
- struct gl_buffer_object **bindTarget = NULL;
-
- bindTarget = get_buffer_target(ctx, target);
- if (!bindTarget) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBindBufferARB(target 0x%x)", target);
- return;
- }
-
- /* Get pointer to old buffer object (to be unbound) */
- oldBufObj = *bindTarget;
- if (oldBufObj && oldBufObj->Name == buffer)
- return; /* rebinding the same buffer object- no change */
-
- /*
- * Get pointer to new buffer object (newBufObj)
- */
- if (buffer == 0) {
- /* The spec says there's not a buffer object named 0, but we use
- * one internally because it simplifies things.
- */
- newBufObj = ctx->Shared->NullBufferObj;
- }
- else {
- /* non-default buffer object */
- newBufObj = _mesa_lookup_bufferobj(ctx, buffer);
- if (!newBufObj || newBufObj == &DummyBufferObject) {
- /* If this is a new buffer object id, or one which was generated but
- * never used before, allocate a buffer object now.
- */
- ASSERT(ctx->Driver.NewBufferObject);
- newBufObj = ctx->Driver.NewBufferObject(ctx, buffer, target);
- if (!newBufObj) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindBufferARB");
- return;
- }
- _mesa_HashInsert(ctx->Shared->BufferObjects, buffer, newBufObj);
- }
- }
-
- /* bind new buffer */
- _mesa_reference_buffer_object(ctx, bindTarget, newBufObj);
-
- /* Pass BindBuffer call to device driver */
- if (ctx->Driver.BindBuffer)
- ctx->Driver.BindBuffer( ctx, target, newBufObj );
-}
-
-
-/**
- * Update the default buffer objects in the given context to reference those
- * specified in the shared state and release those referencing the old
- * shared state.
- */
-void
-_mesa_update_default_objects_buffer_objects(struct gl_context *ctx)
-{
- /* Bind the NullBufferObj to remove references to those
- * in the shared context hash table.
- */
- bind_buffer_object( ctx, GL_ARRAY_BUFFER_ARB, 0);
- bind_buffer_object( ctx, GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
- bind_buffer_object( ctx, GL_PIXEL_PACK_BUFFER_ARB, 0);
- bind_buffer_object( ctx, GL_PIXEL_UNPACK_BUFFER_ARB, 0);
-}
-
-
-/**
- * When we're about to read pixel data out of a PBO (via glDrawPixels,
- * glTexImage, etc) or write data into a PBO (via glReadPixels,
- * glGetTexImage, etc) we call this function to check that we're not
- * going to read out of bounds.
- *
- * XXX This would also be a convenient time to check that the PBO isn't
- * currently mapped. Whoever calls this function should check for that.
- * Remember, we can't use a PBO when it's mapped!
- *
- * If we're not using a PBO, this is a no-op.
- *
- * \param width width of image to read/write
- * \param height height of image to read/write
- * \param depth depth of image to read/write
- * \param format format of image to read/write
- * \param type datatype of image to read/write
- * \param ptr the user-provided pointer/offset
- * \return GL_TRUE if the PBO access is OK, GL_FALSE if the access would
- * go out of bounds.
- */
-GLboolean
-_mesa_validate_pbo_access(GLuint dimensions,
- const struct gl_pixelstore_attrib *pack,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid *ptr)
-{
- GLvoid *start, *end;
- const GLubyte *sizeAddr; /* buffer size, cast to a pointer */
-
- if (!_mesa_is_bufferobj(pack->BufferObj))
- return GL_TRUE; /* no PBO, OK */
-
- if (pack->BufferObj->Size == 0)
- /* no buffer! */
- return GL_FALSE;
-
- /* get address of first pixel we'll read */
- start = _mesa_image_address(dimensions, pack, ptr, width, height,
- format, type, 0, 0, 0);
-
- /* get address just past the last pixel we'll read */
- end = _mesa_image_address(dimensions, pack, ptr, width, height,
- format, type, depth-1, height-1, width);
-
-
- sizeAddr = ((const GLubyte *) 0) + pack->BufferObj->Size;
-
- if ((const GLubyte *) start > sizeAddr) {
- /* This will catch negative values / wrap-around */
- return GL_FALSE;
- }
- if ((const GLubyte *) end > sizeAddr) {
- /* Image read goes beyond end of buffer */
- return GL_FALSE;
- }
-
- /* OK! */
- return GL_TRUE;
-}
-
-
-/**
- * For commands that read from a PBO (glDrawPixels, glTexImage,
- * glPolygonStipple, etc), if we're reading from a PBO, map it read-only
- * and return the pointer into the PBO. If we're not reading from a
- * PBO, return \p src as-is.
- * If non-null return, must call _mesa_unmap_pbo_source() when done.
- *
- * \return NULL if error, else pointer to start of data
- */
-const GLvoid *
-_mesa_map_pbo_source(struct gl_context *ctx,
- const struct gl_pixelstore_attrib *unpack,
- const GLvoid *src)
-{
- const GLubyte *buf;
-
- if (_mesa_is_bufferobj(unpack->BufferObj)) {
- /* unpack from PBO */
- buf = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
- GL_READ_ONLY_ARB,
- unpack->BufferObj);
- if (!buf)
- return NULL;
-
- buf = ADD_POINTERS(buf, src);
- }
- else {
- /* unpack from normal memory */
- buf = src;
- }
-
- return buf;
-}
-
-
-/**
- * Combine PBO-read validation and mapping.
- * If any GL errors are detected, they'll be recorded and NULL returned.
- * \sa _mesa_validate_pbo_access
- * \sa _mesa_map_pbo_source
- * A call to this function should have a matching call to
- * _mesa_unmap_pbo_source().
- */
-const GLvoid *
-_mesa_map_validate_pbo_source(struct gl_context *ctx,
- GLuint dimensions,
- const struct gl_pixelstore_attrib *unpack,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid *ptr,
- const char *where)
-{
- ASSERT(dimensions == 1 || dimensions == 2 || dimensions == 3);
-
- if (!_mesa_is_bufferobj(unpack->BufferObj)) {
- /* non-PBO access: no validation to be done */
- return ptr;
- }
-
- if (!_mesa_validate_pbo_access(dimensions, unpack,
- width, height, depth, format, type, ptr)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(out of bounds PBO access)", where);
- return NULL;
- }
-
- if (_mesa_bufferobj_mapped(unpack->BufferObj)) {
- /* buffer is already mapped - that's an error */
- _mesa_error(ctx, GL_INVALID_OPERATION, "%s(PBO is mapped)", where);
- return NULL;
- }
-
- ptr = _mesa_map_pbo_source(ctx, unpack, ptr);
- return ptr;
-}
-
-
-/**
- * Counterpart to _mesa_map_pbo_source()
- */
-void
-_mesa_unmap_pbo_source(struct gl_context *ctx,
- const struct gl_pixelstore_attrib *unpack)
-{
- ASSERT(unpack != &ctx->Pack); /* catch pack/unpack mismatch */
- if (_mesa_is_bufferobj(unpack->BufferObj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
- unpack->BufferObj);
- }
-}
-
-
-/**
- * For commands that write to a PBO (glReadPixels, glGetColorTable, etc),
- * if we're writing to a PBO, map it write-only and return the pointer
- * into the PBO. If we're not writing to a PBO, return \p dst as-is.
- * If non-null return, must call _mesa_unmap_pbo_dest() when done.
- *
- * \return NULL if error, else pointer to start of data
- */
-void *
-_mesa_map_pbo_dest(struct gl_context *ctx,
- const struct gl_pixelstore_attrib *pack,
- GLvoid *dest)
-{
- void *buf;
-
- if (_mesa_is_bufferobj(pack->BufferObj)) {
- /* pack into PBO */
- buf = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_PIXEL_PACK_BUFFER_EXT,
- GL_WRITE_ONLY_ARB,
- pack->BufferObj);
- if (!buf)
- return NULL;
-
- buf = ADD_POINTERS(buf, dest);
- }
- else {
- /* pack to normal memory */
- buf = dest;
- }
-
- return buf;
-}
-
-
-/**
- * Combine PBO-write validation and mapping.
- * If any GL errors are detected, they'll be recorded and NULL returned.
- * \sa _mesa_validate_pbo_access
- * \sa _mesa_map_pbo_dest
- * A call to this function should have a matching call to
- * _mesa_unmap_pbo_dest().
- */
-GLvoid *
-_mesa_map_validate_pbo_dest(struct gl_context *ctx,
- GLuint dimensions,
- const struct gl_pixelstore_attrib *unpack,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, GLvoid *ptr,
- const char *where)
-{
- ASSERT(dimensions == 1 || dimensions == 2 || dimensions == 3);
-
- if (!_mesa_is_bufferobj(unpack->BufferObj)) {
- /* non-PBO access: no validation to be done */
- return ptr;
- }
-
- if (!_mesa_validate_pbo_access(dimensions, unpack,
- width, height, depth, format, type, ptr)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(out of bounds PBO access)", where);
- return NULL;
- }
-
- if (_mesa_bufferobj_mapped(unpack->BufferObj)) {
- /* buffer is already mapped - that's an error */
- _mesa_error(ctx, GL_INVALID_OPERATION, "%s(PBO is mapped)", where);
- return NULL;
- }
-
- ptr = _mesa_map_pbo_dest(ctx, unpack, ptr);
- return ptr;
-}
-
-
-/**
- * Counterpart to _mesa_map_pbo_dest()
- */
-void
-_mesa_unmap_pbo_dest(struct gl_context *ctx,
- const struct gl_pixelstore_attrib *pack)
-{
- ASSERT(pack != &ctx->Unpack); /* catch pack/unpack mismatch */
- if (_mesa_is_bufferobj(pack->BufferObj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_PACK_BUFFER_EXT, pack->BufferObj);
- }
-}
-
-
-
-/**
- * Return the gl_buffer_object for the given ID.
- * Always return NULL for ID 0.
- */
-struct gl_buffer_object *
-_mesa_lookup_bufferobj(struct gl_context *ctx, GLuint buffer)
-{
- if (buffer == 0)
- return NULL;
- else
- return (struct gl_buffer_object *)
- _mesa_HashLookup(ctx->Shared->BufferObjects, buffer);
-}
-
-
-/**
- * If *ptr points to obj, set ptr = the Null/default buffer object.
- * This is a helper for buffer object deletion.
- * The GL spec says that deleting a buffer object causes it to get
- * unbound from all arrays in the current context.
- */
-static void
-unbind(struct gl_context *ctx,
- struct gl_buffer_object **ptr,
- struct gl_buffer_object *obj)
-{
- if (*ptr == obj) {
- _mesa_reference_buffer_object(ctx, ptr, ctx->Shared->NullBufferObj);
- }
-}
-
-
-/**
- * Plug default/fallback buffer object functions into the device
- * driver hooks.
- */
-void
-_mesa_init_buffer_object_functions(struct dd_function_table *driver)
-{
- /* GL_ARB_vertex/pixel_buffer_object */
- driver->NewBufferObject = _mesa_new_buffer_object;
- driver->DeleteBuffer = _mesa_delete_buffer_object;
- driver->BindBuffer = NULL;
- driver->BufferData = _mesa_buffer_data;
- driver->BufferSubData = _mesa_buffer_subdata;
- driver->GetBufferSubData = _mesa_buffer_get_subdata;
- driver->MapBuffer = _mesa_buffer_map;
- driver->UnmapBuffer = _mesa_buffer_unmap;
-
- /* GL_ARB_map_buffer_range */
- driver->MapBufferRange = _mesa_buffer_map_range;
- driver->FlushMappedBufferRange = _mesa_buffer_flush_mapped_range;
-
- /* GL_ARB_copy_buffer */
- driver->CopyBufferSubData = _mesa_copy_buffer_subdata;
-}
-
-
-
-/**********************************************************************/
-/* API Functions */
-/**********************************************************************/
-
-void GLAPIENTRY
-_mesa_BindBufferARB(GLenum target, GLuint buffer)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBindBuffer(%s, %u)\n",
- _mesa_lookup_enum_by_nr(target), buffer);
-
- bind_buffer_object(ctx, target, buffer);
-}
-
-
-/**
- * Delete a set of buffer objects.
- *
- * \param n Number of buffer objects to delete.
- * \param ids Array of \c n buffer object IDs.
- */
-void GLAPIENTRY
-_mesa_DeleteBuffersARB(GLsizei n, const GLuint *ids)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLsizei i;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (n < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteBuffersARB(n)");
- return;
- }
-
- _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
-
- for (i = 0; i < n; i++) {
- struct gl_buffer_object *bufObj = _mesa_lookup_bufferobj(ctx, ids[i]);
- if (bufObj) {
- struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
- GLuint j;
-
- ASSERT(bufObj->Name == ids[i] || bufObj == &DummyBufferObject);
-
- if (_mesa_bufferobj_mapped(bufObj)) {
- /* if mapped, unmap it now */
- ctx->Driver.UnmapBuffer(ctx, 0, bufObj);
- bufObj->AccessFlags = DEFAULT_ACCESS;
- bufObj->Pointer = NULL;
- }
-
- /* unbind any vertex pointers bound to this buffer */
- unbind(ctx, &arrayObj->Vertex.BufferObj, bufObj);
- unbind(ctx, &arrayObj->Weight.BufferObj, bufObj);
- unbind(ctx, &arrayObj->Normal.BufferObj, bufObj);
- unbind(ctx, &arrayObj->Color.BufferObj, bufObj);
- unbind(ctx, &arrayObj->SecondaryColor.BufferObj, bufObj);
- unbind(ctx, &arrayObj->FogCoord.BufferObj, bufObj);
- unbind(ctx, &arrayObj->Index.BufferObj, bufObj);
- unbind(ctx, &arrayObj->EdgeFlag.BufferObj, bufObj);
- for (j = 0; j < Elements(arrayObj->TexCoord); j++) {
- unbind(ctx, &arrayObj->TexCoord[j].BufferObj, bufObj);
- }
- for (j = 0; j < Elements(arrayObj->VertexAttrib); j++) {
- unbind(ctx, &arrayObj->VertexAttrib[j].BufferObj, bufObj);
- }
-
- if (ctx->Array.ArrayBufferObj == bufObj) {
- _mesa_BindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
- }
- if (ctx->Array.ElementArrayBufferObj == bufObj) {
- _mesa_BindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 );
- }
-
- /* unbind any pixel pack/unpack pointers bound to this buffer */
- if (ctx->Pack.BufferObj == bufObj) {
- _mesa_BindBufferARB( GL_PIXEL_PACK_BUFFER_EXT, 0 );
- }
- if (ctx->Unpack.BufferObj == bufObj) {
- _mesa_BindBufferARB( GL_PIXEL_UNPACK_BUFFER_EXT, 0 );
- }
-
- /* The ID is immediately freed for re-use */
- _mesa_HashRemove(ctx->Shared->BufferObjects, ids[i]);
- _mesa_reference_buffer_object(ctx, &bufObj, NULL);
- }
- }
-
- _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
-}
-
-
-/**
- * Generate a set of unique buffer object IDs and store them in \c buffer.
- *
- * \param n Number of IDs to generate.
- * \param buffer Array of \c n locations to store the IDs.
- */
-void GLAPIENTRY
-_mesa_GenBuffersARB(GLsizei n, GLuint *buffer)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLuint first;
- GLint i;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGenBuffers(%d)\n", n);
-
- if (n < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGenBuffersARB");
- return;
- }
-
- if (!buffer) {
- return;
- }
-
- /*
- * This must be atomic (generation and allocation of buffer object IDs)
- */
- _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
-
- first = _mesa_HashFindFreeKeyBlock(ctx->Shared->BufferObjects, n);
-
- /* Insert the ID and pointer to dummy buffer object into hash table */
- for (i = 0; i < n; i++) {
- _mesa_HashInsert(ctx->Shared->BufferObjects, first + i,
- &DummyBufferObject);
- buffer[i] = first + i;
- }
-
- _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
-}
-
-
-/**
- * Determine if ID is the name of a buffer object.
- *
- * \param id ID of the potential buffer object.
- * \return \c GL_TRUE if \c id is the name of a buffer object,
- * \c GL_FALSE otherwise.
- */
-GLboolean GLAPIENTRY
-_mesa_IsBufferARB(GLuint id)
-{
- struct gl_buffer_object *bufObj;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
-
- _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
- bufObj = _mesa_lookup_bufferobj(ctx, id);
- _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
-
- return bufObj && bufObj != &DummyBufferObject;
-}
-
-
-void GLAPIENTRY
-_mesa_BufferDataARB(GLenum target, GLsizeiptrARB size,
- const GLvoid * data, GLenum usage)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBufferData(%s, %ld, %p, %s)\n",
- _mesa_lookup_enum_by_nr(target),
- (long int) size, data,
- _mesa_lookup_enum_by_nr(usage));
-
- if (size < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glBufferDataARB(size < 0)");
- return;
- }
-
- switch (usage) {
- case GL_STREAM_DRAW_ARB:
- case GL_STREAM_READ_ARB:
- case GL_STREAM_COPY_ARB:
- case GL_STATIC_DRAW_ARB:
- case GL_STATIC_READ_ARB:
- case GL_STATIC_COPY_ARB:
- case GL_DYNAMIC_DRAW_ARB:
- case GL_DYNAMIC_READ_ARB:
- case GL_DYNAMIC_COPY_ARB:
- /* OK */
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glBufferDataARB(usage)");
- return;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBufferDataARB(target)" );
- return;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glBufferDataARB(buffer 0)" );
- return;
- }
-
- if (_mesa_bufferobj_mapped(bufObj)) {
- /* Unmap the existing buffer. We'll replace it now. Not an error. */
- ctx->Driver.UnmapBuffer(ctx, target, bufObj);
- bufObj->AccessFlags = DEFAULT_ACCESS;
- ASSERT(bufObj->Pointer == NULL);
- }
-
- FLUSH_VERTICES(ctx, _NEW_BUFFER_OBJECT);
-
- bufObj->Written = GL_TRUE;
-
-#ifdef VBO_DEBUG
- printf("glBufferDataARB(%u, sz %ld, from %p, usage 0x%x)\n",
- bufObj->Name, size, data, usage);
-#endif
-
-#ifdef BOUNDS_CHECK
- size += 100;
-#endif
-
- ASSERT(ctx->Driver.BufferData);
- if (!ctx->Driver.BufferData( ctx, target, size, data, usage, bufObj )) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBufferDataARB()");
- }
-}
-
-
-void GLAPIENTRY
-_mesa_BufferSubDataARB(GLenum target, GLintptrARB offset,
- GLsizeiptrARB size, const GLvoid * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
- "glBufferSubDataARB" );
- if (!bufObj) {
- /* error already recorded */
- return;
- }
-
- if (size == 0)
- return;
-
- bufObj->Written = GL_TRUE;
-
- ASSERT(ctx->Driver.BufferSubData);
- ctx->Driver.BufferSubData( ctx, target, offset, size, data, bufObj );
-}
-
-
-void GLAPIENTRY
-_mesa_GetBufferSubDataARB(GLenum target, GLintptrARB offset,
- GLsizeiptrARB size, void * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
- "glGetBufferSubDataARB" );
- if (!bufObj) {
- /* error already recorded */
- return;
- }
-
- ASSERT(ctx->Driver.GetBufferSubData);
- ctx->Driver.GetBufferSubData( ctx, target, offset, size, data, bufObj );
-}
-
-
-void * GLAPIENTRY
-_mesa_MapBufferARB(GLenum target, GLenum access)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object * bufObj;
- GLbitfield accessFlags;
- void *map;
-
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
-
- switch (access) {
- case GL_READ_ONLY_ARB:
- accessFlags = GL_MAP_READ_BIT;
- break;
- case GL_WRITE_ONLY_ARB:
- accessFlags = GL_MAP_WRITE_BIT;
- break;
- case GL_READ_WRITE_ARB:
- accessFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glMapBufferARB(access)");
- return NULL;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glMapBufferARB(target)" );
- return NULL;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glMapBufferARB(buffer 0)" );
- return NULL;
- }
- if (_mesa_bufferobj_mapped(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glMapBufferARB(already mapped)");
- return NULL;
- }
-
- ASSERT(ctx->Driver.MapBuffer);
- map = ctx->Driver.MapBuffer( ctx, target, access, bufObj );
- if (!map) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
- return NULL;
- }
- else {
- /* The driver callback should have set these fields.
- * This is important because other modules (like VBO) might call
- * the driver function directly.
- */
- ASSERT(bufObj->Pointer == map);
- ASSERT(bufObj->Length == bufObj->Size);
- ASSERT(bufObj->Offset == 0);
- bufObj->AccessFlags = accessFlags;
- }
-
- if (access == GL_WRITE_ONLY_ARB || access == GL_READ_WRITE_ARB)
- bufObj->Written = GL_TRUE;
-
-#ifdef VBO_DEBUG
- printf("glMapBufferARB(%u, sz %ld, access 0x%x)\n",
- bufObj->Name, bufObj->Size, access);
- if (access == GL_WRITE_ONLY_ARB) {
- GLuint i;
- GLubyte *b = (GLubyte *) bufObj->Pointer;
- for (i = 0; i < bufObj->Size; i++)
- b[i] = i & 0xff;
- }
-#endif
-
-#ifdef BOUNDS_CHECK
- {
- GLubyte *buf = (GLubyte *) bufObj->Pointer;
- GLuint i;
- /* buffer is 100 bytes larger than requested, fill with magic value */
- for (i = 0; i < 100; i++) {
- buf[bufObj->Size - i - 1] = 123;
- }
- }
-#endif
-
- return bufObj->Pointer;
-}
-
-
-GLboolean GLAPIENTRY
-_mesa_UnmapBufferARB(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- GLboolean status = GL_TRUE;
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glUnmapBufferARB(target)" );
- return GL_FALSE;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glUnmapBufferARB" );
- return GL_FALSE;
- }
- if (!_mesa_bufferobj_mapped(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glUnmapBufferARB");
- return GL_FALSE;
- }
-
-#ifdef BOUNDS_CHECK
- if (bufObj->Access != GL_READ_ONLY_ARB) {
- GLubyte *buf = (GLubyte *) bufObj->Pointer;
- GLuint i;
- /* check that last 100 bytes are still = magic value */
- for (i = 0; i < 100; i++) {
- GLuint pos = bufObj->Size - i - 1;
- if (buf[pos] != 123) {
- _mesa_warning(ctx, "Out of bounds buffer object write detected"
- " at position %d (value = %u)\n",
- pos, buf[pos]);
- }
- }
- }
-#endif
-
-#ifdef VBO_DEBUG
- if (bufObj->AccessFlags & GL_MAP_WRITE_BIT) {
- GLuint i, unchanged = 0;
- GLubyte *b = (GLubyte *) bufObj->Pointer;
- GLint pos = -1;
- /* check which bytes changed */
- for (i = 0; i < bufObj->Size - 1; i++) {
- if (b[i] == (i & 0xff) && b[i+1] == ((i+1) & 0xff)) {
- unchanged++;
- if (pos == -1)
- pos = i;
- }
- }
- if (unchanged) {
- printf("glUnmapBufferARB(%u): %u of %ld unchanged, starting at %d\n",
- bufObj->Name, unchanged, bufObj->Size, pos);
- }
- }
-#endif
-
- status = ctx->Driver.UnmapBuffer( ctx, target, bufObj );
- bufObj->AccessFlags = DEFAULT_ACCESS;
- ASSERT(bufObj->Pointer == NULL);
- ASSERT(bufObj->Offset == 0);
- ASSERT(bufObj->Length == 0);
-
- return status;
-}
-
-
-void GLAPIENTRY
-_mesa_GetBufferParameterivARB(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameterivARB(target)" );
- return;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferParameterivARB" );
- return;
- }
-
- switch (pname) {
- case GL_BUFFER_SIZE_ARB:
- *params = (GLint) bufObj->Size;
- return;
- case GL_BUFFER_USAGE_ARB:
- *params = bufObj->Usage;
- return;
- case GL_BUFFER_ACCESS_ARB:
- *params = simplified_access_mode(bufObj->AccessFlags);
- return;
- case GL_BUFFER_MAPPED_ARB:
- *params = _mesa_bufferobj_mapped(bufObj);
- return;
- case GL_BUFFER_ACCESS_FLAGS:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = bufObj->AccessFlags;
- return;
- case GL_BUFFER_MAP_OFFSET:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = (GLint) bufObj->Offset;
- return;
- case GL_BUFFER_MAP_LENGTH:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = (GLint) bufObj->Length;
- return;
- default:
- ; /* fall-through */
- }
-
-invalid_pname:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameterivARB(pname=%s)",
- _mesa_lookup_enum_by_nr(pname));
-}
-
-
-/**
- * New in GL 3.2
- * This is pretty much a duplicate of GetBufferParameteriv() but the
- * GL_BUFFER_SIZE_ARB attribute will be 64-bits on a 64-bit system.
- */
-void GLAPIENTRY
-_mesa_GetBufferParameteri64v(GLenum target, GLenum pname, GLint64 *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameteri64v(target)" );
- return;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferParameteri64v" );
- return;
- }
-
- switch (pname) {
- case GL_BUFFER_SIZE_ARB:
- *params = bufObj->Size;
- return;
- case GL_BUFFER_USAGE_ARB:
- *params = bufObj->Usage;
- return;
- case GL_BUFFER_ACCESS_ARB:
- *params = simplified_access_mode(bufObj->AccessFlags);
- return;
- case GL_BUFFER_ACCESS_FLAGS:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = bufObj->AccessFlags;
- return;
- case GL_BUFFER_MAPPED_ARB:
- *params = _mesa_bufferobj_mapped(bufObj);
- return;
- case GL_BUFFER_MAP_OFFSET:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = bufObj->Offset;
- return;
- case GL_BUFFER_MAP_LENGTH:
- if (ctx->VersionMajor < 3)
- goto invalid_pname;
- *params = bufObj->Length;
- return;
- default:
- ; /* fall-through */
- }
-
-invalid_pname:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameteri64v(pname=%s)",
- _mesa_lookup_enum_by_nr(pname));
-}
-
-
-void GLAPIENTRY
-_mesa_GetBufferPointervARB(GLenum target, GLenum pname, GLvoid **params)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object * bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (pname != GL_BUFFER_MAP_POINTER_ARB) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferPointervARB(pname)");
- return;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferPointervARB(target)" );
- return;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferPointervARB" );
- return;
- }
-
- *params = bufObj->Pointer;
-}
-
-
-void GLAPIENTRY
-_mesa_CopyBufferSubData(GLenum readTarget, GLenum writeTarget,
- GLintptr readOffset, GLintptr writeOffset,
- GLsizeiptr size)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *src, *dst;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- src = get_buffer(ctx, readTarget);
- if (!src || !_mesa_is_bufferobj(src)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glCopyBuffserSubData(readTarget = 0x%x)", readTarget);
- return;
- }
-
- dst = get_buffer(ctx, writeTarget);
- if (!dst || !_mesa_is_bufferobj(dst)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glCopyBuffserSubData(writeTarget = 0x%x)", writeTarget);
- return;
- }
-
- if (_mesa_bufferobj_mapped(src)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glCopyBuffserSubData(readBuffer is mapped)");
- return;
- }
-
- if (_mesa_bufferobj_mapped(dst)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glCopyBuffserSubData(writeBuffer is mapped)");
- return;
- }
-
- if (readOffset < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glCopyBuffserSubData(readOffset = %d)", (int) readOffset);
- return;
- }
-
- if (writeOffset < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glCopyBuffserSubData(writeOffset = %d)", (int) writeOffset);
- return;
- }
-
- if (readOffset + size > src->Size) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glCopyBuffserSubData(readOffset + size = %d)",
- (int) (readOffset + size));
- return;
- }
-
- if (writeOffset + size > dst->Size) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glCopyBuffserSubData(writeOffset + size = %d)",
- (int) (writeOffset + size));
- return;
- }
-
- if (src == dst) {
- if (readOffset + size <= writeOffset) {
- /* OK */
- }
- else if (writeOffset + size <= readOffset) {
- /* OK */
- }
- else {
- /* overlapping src/dst is illegal */
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glCopyBuffserSubData(overlapping src/dst)");
- return;
- }
- }
-
- ctx->Driver.CopyBufferSubData(ctx, src, dst, readOffset, writeOffset, size);
-}
-
-
-/**
- * See GL_ARB_map_buffer_range spec
- */
-void * GLAPIENTRY
-_mesa_MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length,
- GLbitfield access)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- void *map;
-
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
-
- if (!ctx->Extensions.ARB_map_buffer_range) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(extension not supported)");
- return NULL;
- }
-
- if (offset < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(offset = %ld)", (long)offset);
- return NULL;
- }
-
- if (length < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(length = %ld)", (long)length);
- return NULL;
- }
-
- if ((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == 0) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(access indicates neither read or write)");
- return NULL;
- }
-
- if (access & GL_MAP_READ_BIT) {
- if ((access & GL_MAP_INVALIDATE_RANGE_BIT) ||
- (access & GL_MAP_INVALIDATE_BUFFER_BIT) ||
- (access & GL_MAP_UNSYNCHRONIZED_BIT)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(invalid access flags)");
- return NULL;
- }
- }
-
- if ((access & GL_MAP_FLUSH_EXPLICIT_BIT) &&
- ((access & GL_MAP_WRITE_BIT) == 0)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(invalid access flags)");
- return NULL;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj || !_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glMapBufferRange(target = 0x%x)", target);
- return NULL;
- }
-
- if (offset + length > bufObj->Size) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(offset + length > size)");
- return NULL;
- }
-
- if (_mesa_bufferobj_mapped(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(buffer already mapped)");
- return NULL;
- }
-
- ASSERT(ctx->Driver.MapBufferRange);
- map = ctx->Driver.MapBufferRange(ctx, target, offset, length,
- access, bufObj);
- if (!map) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
- }
- else {
- /* The driver callback should have set all these fields.
- * This is important because other modules (like VBO) might call
- * the driver function directly.
- */
- ASSERT(bufObj->Pointer == map);
- ASSERT(bufObj->Length == length);
- ASSERT(bufObj->Offset == offset);
- ASSERT(bufObj->AccessFlags == access);
- }
-
- return map;
-}
-
-
-/**
- * See GL_ARB_map_buffer_range spec
- */
-void GLAPIENTRY
-_mesa_FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_buffer_object *bufObj;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (!ctx->Extensions.ARB_map_buffer_range) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(extension not supported)");
- return;
- }
-
- if (offset < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(offset = %ld)", (long)offset);
- return;
- }
-
- if (length < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(length = %ld)", (long)length);
- return;
- }
-
- bufObj = get_buffer(ctx, target);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glMapBufferRange(target = 0x%x)", target);
- return;
- }
-
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(current buffer is 0)");
- return;
- }
-
- if (!_mesa_bufferobj_mapped(bufObj)) {
- /* buffer is not mapped */
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(buffer is not mapped)");
- return;
- }
-
- if ((bufObj->AccessFlags & GL_MAP_FLUSH_EXPLICIT_BIT) == 0) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glMapBufferRange(GL_MAP_FLUSH_EXPLICIT_BIT not set)");
- return;
- }
-
- if (offset + length > bufObj->Length) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glMapBufferRange(offset %ld + length %ld > mapped length %ld)",
- (long)offset, (long)length, (long)bufObj->Length);
- return;
- }
-
- ASSERT(bufObj->AccessFlags & GL_MAP_WRITE_BIT);
-
- if (ctx->Driver.FlushMappedBufferRange)
- ctx->Driver.FlushMappedBufferRange(ctx, target, offset, length, bufObj);
-}
-
-
-#if FEATURE_APPLE_object_purgeable
-static GLenum
-_mesa_BufferObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_buffer_object *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_bufferobj(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectPurgeable(name = 0x%x)", name);
- return 0;
- }
- if (!_mesa_is_bufferobj(bufObj)) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glObjectPurgeable(buffer 0)" );
- return 0;
- }
-
- if (bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectPurgeable(name = 0x%x) is already purgeable", name);
- return GL_VOLATILE_APPLE;
- }
-
- bufObj->Purgeable = GL_TRUE;
-
- retval = GL_VOLATILE_APPLE;
- if (ctx->Driver.BufferObjectPurgeable)
- retval = ctx->Driver.BufferObjectPurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-static GLenum
-_mesa_RenderObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_renderbuffer *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_renderbuffer(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return 0;
- }
-
- if (bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectPurgeable(name = 0x%x) is already purgeable", name);
- return GL_VOLATILE_APPLE;
- }
-
- bufObj->Purgeable = GL_TRUE;
-
- retval = GL_VOLATILE_APPLE;
- if (ctx->Driver.RenderObjectPurgeable)
- retval = ctx->Driver.RenderObjectPurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-static GLenum
-_mesa_TextureObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_texture_object *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_texture(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectPurgeable(name = 0x%x)", name);
- return 0;
- }
-
- if (bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectPurgeable(name = 0x%x) is already purgeable", name);
- return GL_VOLATILE_APPLE;
- }
-
- bufObj->Purgeable = GL_TRUE;
-
- retval = GL_VOLATILE_APPLE;
- if (ctx->Driver.TextureObjectPurgeable)
- retval = ctx->Driver.TextureObjectPurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-GLenum GLAPIENTRY
-_mesa_ObjectPurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
-{
- GLenum retval;
-
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
-
- if (name == 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectPurgeable(name = 0x%x)", name);
- return 0;
- }
-
- switch (option) {
- case GL_VOLATILE_APPLE:
- case GL_RELEASED_APPLE:
- /* legal */
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glObjectPurgeable(name = 0x%x) invalid option: %d",
- name, option);
- return 0;
- }
-
- switch (objectType) {
- case GL_TEXTURE:
- retval = _mesa_TextureObjectPurgeable (ctx, name, option);
- break;
- case GL_RENDERBUFFER_EXT:
- retval = _mesa_RenderObjectPurgeable (ctx, name, option);
- break;
- case GL_BUFFER_OBJECT_APPLE:
- retval = _mesa_BufferObjectPurgeable (ctx, name, option);
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glObjectPurgeable(name = 0x%x) invalid type: %d",
- name, objectType);
- return 0;
- }
-
- /* In strict conformance to the spec, we must only return VOLATILE when
- * when passed the VOLATILE option. Madness.
- *
- * XXX First fix the spec, then fix me.
- */
- return option == GL_VOLATILE_APPLE ? GL_VOLATILE_APPLE : retval;
-}
-
-
-static GLenum
-_mesa_BufferObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_buffer_object *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_bufferobj(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return 0;
- }
-
- if (! bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectUnpurgeable(name = 0x%x) object is "
- " already \"unpurged\"", name);
- return 0;
- }
-
- bufObj->Purgeable = GL_FALSE;
-
- retval = option;
- if (ctx->Driver.BufferObjectUnpurgeable)
- retval = ctx->Driver.BufferObjectUnpurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-static GLenum
-_mesa_RenderObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_renderbuffer *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_renderbuffer(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return 0;
- }
-
- if (! bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectUnpurgeable(name = 0x%x) object is "
- " already \"unpurged\"", name);
- return 0;
- }
-
- bufObj->Purgeable = GL_FALSE;
-
- retval = option;
- if (ctx->Driver.RenderObjectUnpurgeable)
- retval = ctx->Driver.RenderObjectUnpurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-static GLenum
-_mesa_TextureObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
-{
- struct gl_texture_object *bufObj;
- GLenum retval;
-
- bufObj = _mesa_lookup_texture(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return 0;
- }
-
- if (! bufObj->Purgeable) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glObjectUnpurgeable(name = 0x%x) object is"
- " already \"unpurged\"", name);
- return 0;
- }
-
- bufObj->Purgeable = GL_FALSE;
-
- retval = option;
- if (ctx->Driver.TextureObjectUnpurgeable)
- retval = ctx->Driver.TextureObjectUnpurgeable(ctx, bufObj, option);
-
- return retval;
-}
-
-
-GLenum GLAPIENTRY
-_mesa_ObjectUnpurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
-
- if (name == 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return 0;
- }
-
- switch (option) {
- case GL_RETAINED_APPLE:
- case GL_UNDEFINED_APPLE:
- /* legal */
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glObjectUnpurgeable(name = 0x%x) invalid option: %d",
- name, option);
- return 0;
- }
-
- switch (objectType) {
- case GL_BUFFER_OBJECT_APPLE:
- return _mesa_BufferObjectUnpurgeable(ctx, name, option);
- case GL_TEXTURE:
- return _mesa_TextureObjectUnpurgeable(ctx, name, option);
- case GL_RENDERBUFFER_EXT:
- return _mesa_RenderObjectUnpurgeable(ctx, name, option);
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glObjectUnpurgeable(name = 0x%x) invalid type: %d",
- name, objectType);
- return 0;
- }
-}
-
-
-static void
-_mesa_GetBufferObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
- GLenum pname, GLint* params)
-{
- struct gl_buffer_object *bufObj;
-
- bufObj = _mesa_lookup_bufferobj(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glGetObjectParameteriv(name = 0x%x) invalid object", name);
- return;
- }
-
- switch (pname) {
- case GL_PURGEABLE_APPLE:
- *params = bufObj->Purgeable;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
- name, pname);
- break;
- }
-}
-
-
-static void
-_mesa_GetRenderObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
- GLenum pname, GLint* params)
-{
- struct gl_renderbuffer *bufObj;
-
- bufObj = _mesa_lookup_renderbuffer(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return;
- }
-
- switch (pname) {
- case GL_PURGEABLE_APPLE:
- *params = bufObj->Purgeable;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
- name, pname);
- break;
- }
-}
-
-
-static void
-_mesa_GetTextureObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
- GLenum pname, GLint* params)
-{
- struct gl_texture_object *bufObj;
-
- bufObj = _mesa_lookup_texture(ctx, name);
- if (!bufObj) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glObjectUnpurgeable(name = 0x%x)", name);
- return;
- }
-
- switch (pname) {
- case GL_PURGEABLE_APPLE:
- *params = bufObj->Purgeable;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
- name, pname);
- break;
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GetObjectParameterivAPPLE(GLenum objectType, GLuint name, GLenum pname,
- GLint* params)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (name == 0) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glGetObjectParameteriv(name = 0x%x)", name);
- return;
- }
-
- switch (objectType) {
- case GL_TEXTURE:
- _mesa_GetTextureObjectParameterivAPPLE (ctx, name, pname, params);
- break;
- case GL_BUFFER_OBJECT_APPLE:
- _mesa_GetBufferObjectParameterivAPPLE (ctx, name, pname, params);
- break;
- case GL_RENDERBUFFER_EXT:
- _mesa_GetRenderObjectParameterivAPPLE (ctx, name, pname, params);
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetObjectParameteriv(name = 0x%x) invalid type: %d",
- name, objectType);
- }
-}
-
-#endif /* FEATURE_APPLE_object_purgeable */
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.6
+ *
+ * Copyright (C) 1999-2008 Brian Paul All Rights Reserved.
+ * Copyright (C) 2009 VMware, Inc. 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 bufferobj.c
+ * \brief Functions for the GL_ARB_vertex/pixel_buffer_object extensions.
+ * \author Brian Paul, Ian Romanick
+ */
+
+
+#include "glheader.h"
+#include "enums.h"
+#include "hash.h"
+#include "imports.h"
+#include "image.h"
+#include "context.h"
+#include "bufferobj.h"
+#include "fbobject.h"
+#include "mfeatures.h"
+#include "mtypes.h"
+#include "texobj.h"
+
+
+/* Debug flags */
+/*#define VBO_DEBUG*/
+/*#define BOUNDS_CHECK*/
+
+
+#if FEATURE_OES_mapbuffer
+#define DEFAULT_ACCESS GL_MAP_WRITE_BIT
+#else
+#define DEFAULT_ACCESS (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)
+#endif
+
+
+/**
+ * Used as a placeholder for buffer objects between glGenBuffers() and
+ * glBindBuffer() so that glIsBuffer() can work correctly.
+ */
+static struct gl_buffer_object DummyBufferObject;
+
+
+/**
+ * Return pointer to address of a buffer object target.
+ * \param ctx the GL context
+ * \param target the buffer object target to be retrieved.
+ * \return pointer to pointer to the buffer object bound to \c target in the
+ * specified context or \c NULL if \c target is invalid.
+ */
+static INLINE struct gl_buffer_object **
+get_buffer_target(struct gl_context *ctx, GLenum target)
+{
+ switch (target) {
+ case GL_ARRAY_BUFFER_ARB:
+ return &ctx->Array.ArrayBufferObj;
+ case GL_ELEMENT_ARRAY_BUFFER_ARB:
+ return &ctx->Array.ElementArrayBufferObj;
+ case GL_PIXEL_PACK_BUFFER_EXT:
+ return &ctx->Pack.BufferObj;
+ case GL_PIXEL_UNPACK_BUFFER_EXT:
+ return &ctx->Unpack.BufferObj;
+ case GL_COPY_READ_BUFFER:
+ return &ctx->CopyReadBuffer;
+ case GL_COPY_WRITE_BUFFER:
+ return &ctx->CopyWriteBuffer;
+#if FEATURE_EXT_transform_feedback
+ case GL_TRANSFORM_FEEDBACK_BUFFER:
+ if (ctx->Extensions.EXT_transform_feedback) {
+ return &ctx->TransformFeedback.CurrentBuffer;
+ }
+ break;
+#endif
+ default:
+ return NULL;
+ }
+ return NULL;
+}
+
+
+/**
+ * Get the buffer object bound to the specified target in a GL context.
+ * \param ctx the GL context
+ * \param target the buffer object target to be retrieved.
+ * \return pointer to the buffer object bound to \c target in the
+ * specified context or \c NULL if \c target is invalid.
+ */
+static INLINE struct gl_buffer_object *
+get_buffer(struct gl_context *ctx, GLenum target)
+{
+ struct gl_buffer_object **bufObj = get_buffer_target(ctx, target);
+ if (bufObj)
+ return *bufObj;
+ return NULL;
+}
+
+
+/**
+ * Convert a GLbitfield describing the mapped buffer access flags
+ * into one of GL_READ_WRITE, GL_READ_ONLY, or GL_WRITE_ONLY.
+ */
+static GLenum
+simplified_access_mode(GLbitfield access)
+{
+ const GLbitfield rwFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
+ if ((access & rwFlags) == rwFlags)
+ return GL_READ_WRITE;
+ if ((access & GL_MAP_READ_BIT) == GL_MAP_READ_BIT)
+ return GL_READ_ONLY;
+ if ((access & GL_MAP_WRITE_BIT) == GL_MAP_WRITE_BIT)
+ return GL_WRITE_ONLY;
+ return GL_READ_WRITE; /* this should never happen, but no big deal */
+}
+
+
+/**
+ * Tests the subdata range parameters and sets the GL error code for
+ * \c glBufferSubDataARB and \c glGetBufferSubDataARB.
+ *
+ * \param ctx GL context.
+ * \param target Buffer object target on which to operate.
+ * \param offset Offset of the first byte of the subdata range.
+ * \param size Size, in bytes, of the subdata range.
+ * \param caller Name of calling function for recording errors.
+ * \return A pointer to the buffer object bound to \c target in the
+ * specified context or \c NULL if any of the parameter or state
+ * conditions for \c glBufferSubDataARB or \c glGetBufferSubDataARB
+ * are invalid.
+ *
+ * \sa glBufferSubDataARB, glGetBufferSubDataARB
+ */
+static struct gl_buffer_object *
+buffer_object_subdata_range_good( struct gl_context * ctx, GLenum target,
+ GLintptrARB offset, GLsizeiptrARB size,
+ const char *caller )
+{
+ struct gl_buffer_object *bufObj;
+
+ if (size < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "%s(size < 0)", caller);
+ return NULL;
+ }
+
+ if (offset < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "%s(offset < 0)", caller);
+ return NULL;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "%s(target)", caller);
+ return NULL;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
+ return NULL;
+ }
+ if (offset + size > bufObj->Size) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "%s(size + offset > buffer size)", caller);
+ return NULL;
+ }
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ /* Buffer is currently mapped */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "%s", caller);
+ return NULL;
+ }
+
+ return bufObj;
+}
+
+
+/**
+ * Allocate and initialize a new buffer object.
+ *
+ * Default callback for the \c dd_function_table::NewBufferObject() hook.
+ */
+struct gl_buffer_object *
+_mesa_new_buffer_object( struct gl_context *ctx, GLuint name, GLenum target )
+{
+ struct gl_buffer_object *obj;
+
+ (void) ctx;
+
+ obj = MALLOC_STRUCT(gl_buffer_object);
+ _mesa_initialize_buffer_object(obj, name, target);
+ return obj;
+}
+
+
+/**
+ * Delete a buffer object.
+ *
+ * Default callback for the \c dd_function_table::DeleteBuffer() hook.
+ */
+void
+_mesa_delete_buffer_object( struct gl_context *ctx, struct gl_buffer_object *bufObj )
+{
+ (void) ctx;
+
+ if (bufObj->Data)
+ free(bufObj->Data);
+
+ /* assign strange values here to help w/ debugging */
+ bufObj->RefCount = -1000;
+ bufObj->Name = ~0;
+
+ _glthread_DESTROY_MUTEX(bufObj->Mutex);
+ free(bufObj);
+}
+
+
+
+/**
+ * Set ptr to bufObj w/ reference counting.
+ */
+void
+_mesa_reference_buffer_object(struct gl_context *ctx,
+ struct gl_buffer_object **ptr,
+ struct gl_buffer_object *bufObj)
+{
+ if (*ptr == bufObj)
+ return;
+
+ if (*ptr) {
+ /* Unreference the old buffer */
+ GLboolean deleteFlag = GL_FALSE;
+ struct gl_buffer_object *oldObj = *ptr;
+
+ _glthread_LOCK_MUTEX(oldObj->Mutex);
+ ASSERT(oldObj->RefCount > 0);
+ oldObj->RefCount--;
+#if 0
+ printf("BufferObj %p %d DECR to %d\n",
+ (void *) oldObj, oldObj->Name, oldObj->RefCount);
+#endif
+ deleteFlag = (oldObj->RefCount == 0);
+ _glthread_UNLOCK_MUTEX(oldObj->Mutex);
+
+ if (deleteFlag) {
+
+ /* some sanity checking: don't delete a buffer still in use */
+#if 0
+ /* unfortunately, these tests are invalid during context tear-down */
+ ASSERT(ctx->Array.ArrayBufferObj != bufObj);
+ ASSERT(ctx->Array.ElementArrayBufferObj != bufObj);
+ ASSERT(ctx->Array.ArrayObj->Vertex.BufferObj != bufObj);
+#endif
+
+ ASSERT(ctx->Driver.DeleteBuffer);
+ ctx->Driver.DeleteBuffer(ctx, oldObj);
+ }
+
+ *ptr = NULL;
+ }
+ ASSERT(!*ptr);
+
+ if (bufObj) {
+ /* reference new buffer */
+ _glthread_LOCK_MUTEX(bufObj->Mutex);
+ if (bufObj->RefCount == 0) {
+ /* this buffer's being deleted (look just above) */
+ /* Not sure this can every really happen. Warn if it does. */
+ _mesa_problem(NULL, "referencing deleted buffer object");
+ *ptr = NULL;
+ }
+ else {
+ bufObj->RefCount++;
+#if 0
+ printf("BufferObj %p %d INCR to %d\n",
+ (void *) bufObj, bufObj->Name, bufObj->RefCount);
+#endif
+ *ptr = bufObj;
+ }
+ _glthread_UNLOCK_MUTEX(bufObj->Mutex);
+ }
+}
+
+
+/**
+ * Initialize a buffer object to default values.
+ */
+void
+_mesa_initialize_buffer_object( struct gl_buffer_object *obj,
+ GLuint name, GLenum target )
+{
+ (void) target;
+
+ memset(obj, 0, sizeof(struct gl_buffer_object));
+ _glthread_INIT_MUTEX(obj->Mutex);
+ obj->RefCount = 1;
+ obj->Name = name;
+ obj->Usage = GL_STATIC_DRAW_ARB;
+ obj->AccessFlags = DEFAULT_ACCESS;
+}
+
+
+/**
+ * Allocate space for and store data in a buffer object. Any data that was
+ * previously stored in the buffer object is lost. If \c data is \c NULL,
+ * memory will be allocated, but no copy will occur.
+ *
+ * This is the default callback for \c dd_function_table::BufferData()
+ * Note that all GL error checking will have been done already.
+ *
+ * \param ctx GL context.
+ * \param target Buffer object target on which to operate.
+ * \param size Size, in bytes, of the new data store.
+ * \param data Pointer to the data to store in the buffer object. This
+ * pointer may be \c NULL.
+ * \param usage Hints about how the data will be used.
+ * \param bufObj Object to be used.
+ *
+ * \return GL_TRUE for success, GL_FALSE for failure
+ * \sa glBufferDataARB, dd_function_table::BufferData.
+ */
+GLboolean
+_mesa_buffer_data( struct gl_context *ctx, GLenum target, GLsizeiptrARB size,
+ const GLvoid * data, GLenum usage,
+ struct gl_buffer_object * bufObj )
+{
+ void * new_data;
+
+ (void) ctx; (void) target;
+
+ new_data = _mesa_realloc( bufObj->Data, bufObj->Size, size );
+ if (new_data) {
+ bufObj->Data = (GLubyte *) new_data;
+ bufObj->Size = size;
+ bufObj->Usage = usage;
+
+ if (data) {
+ memcpy( bufObj->Data, data, size );
+ }
+
+ return GL_TRUE;
+ }
+ else {
+ return GL_FALSE;
+ }
+}
+
+
+/**
+ * Replace data in a subrange of buffer object. If the data range
+ * specified by \c size + \c offset extends beyond the end of the buffer or
+ * if \c data is \c NULL, no copy is performed.
+ *
+ * This is the default callback for \c dd_function_table::BufferSubData()
+ * Note that all GL error checking will have been done already.
+ *
+ * \param ctx GL context.
+ * \param target Buffer object target on which to operate.
+ * \param offset Offset of the first byte to be modified.
+ * \param size Size, in bytes, of the data range.
+ * \param data Pointer to the data to store in the buffer object.
+ * \param bufObj Object to be used.
+ *
+ * \sa glBufferSubDataARB, dd_function_table::BufferSubData.
+ */
+void
+_mesa_buffer_subdata( struct gl_context *ctx, GLenum target, GLintptrARB offset,
+ GLsizeiptrARB size, const GLvoid * data,
+ struct gl_buffer_object * bufObj )
+{
+ (void) ctx; (void) target;
+
+ /* this should have been caught in _mesa_BufferSubData() */
+ ASSERT(size + offset <= bufObj->Size);
+
+ if (bufObj->Data) {
+ memcpy( (GLubyte *) bufObj->Data + offset, data, size );
+ }
+}
+
+
+/**
+ * Retrieve data from a subrange of buffer object. If the data range
+ * specified by \c size + \c offset extends beyond the end of the buffer or
+ * if \c data is \c NULL, no copy is performed.
+ *
+ * This is the default callback for \c dd_function_table::GetBufferSubData()
+ * Note that all GL error checking will have been done already.
+ *
+ * \param ctx GL context.
+ * \param target Buffer object target on which to operate.
+ * \param offset Offset of the first byte to be fetched.
+ * \param size Size, in bytes, of the data range.
+ * \param data Destination for data
+ * \param bufObj Object to be used.
+ *
+ * \sa glBufferGetSubDataARB, dd_function_table::GetBufferSubData.
+ */
+void
+_mesa_buffer_get_subdata( struct gl_context *ctx, GLenum target, GLintptrARB offset,
+ GLsizeiptrARB size, GLvoid * data,
+ struct gl_buffer_object * bufObj )
+{
+ (void) ctx; (void) target;
+
+ if (bufObj->Data && ((GLsizeiptrARB) (size + offset) <= bufObj->Size)) {
+ memcpy( data, (GLubyte *) bufObj->Data + offset, size );
+ }
+}
+
+
+/**
+ * Default callback for \c dd_function_tabel::MapBuffer().
+ *
+ * The function parameters will have been already tested for errors.
+ *
+ * \param ctx GL context.
+ * \param target Buffer object target on which to operate.
+ * \param access Information about how the buffer will be accessed.
+ * \param bufObj Object to be mapped.
+ * \return A pointer to the object's internal data store that can be accessed
+ * by the processor
+ *
+ * \sa glMapBufferARB, dd_function_table::MapBuffer
+ */
+void *
+_mesa_buffer_map( struct gl_context *ctx, GLenum target, GLenum access,
+ struct gl_buffer_object *bufObj )
+{
+ (void) ctx;
+ (void) target;
+ (void) access;
+ /* Just return a direct pointer to the data */
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ /* already mapped! */
+ return NULL;
+ }
+ bufObj->Pointer = bufObj->Data;
+ bufObj->Length = bufObj->Size;
+ bufObj->Offset = 0;
+ return bufObj->Pointer;
+}
+
+
+/**
+ * Default fallback for \c dd_function_table::MapBufferRange().
+ * Called via glMapBufferRange().
+ */
+static void *
+_mesa_buffer_map_range( struct gl_context *ctx, GLenum target, GLintptr offset,
+ GLsizeiptr length, GLbitfield access,
+ struct gl_buffer_object *bufObj )
+{
+ (void) ctx;
+ (void) target;
+ assert(!_mesa_bufferobj_mapped(bufObj));
+ /* Just return a direct pointer to the data */
+ bufObj->Pointer = bufObj->Data + offset;
+ bufObj->Length = length;
+ bufObj->Offset = offset;
+ bufObj->AccessFlags = access;
+ return bufObj->Pointer;
+}
+
+
+/**
+ * Default fallback for \c dd_function_table::FlushMappedBufferRange().
+ * Called via glFlushMappedBufferRange().
+ */
+static void
+_mesa_buffer_flush_mapped_range( struct gl_context *ctx, GLenum target,
+ GLintptr offset, GLsizeiptr length,
+ struct gl_buffer_object *obj )
+{
+ (void) ctx;
+ (void) target;
+ (void) offset;
+ (void) length;
+ (void) obj;
+ /* no-op */
+}
+
+
+/**
+ * Default callback for \c dd_function_table::MapBuffer().
+ *
+ * The input parameters will have been already tested for errors.
+ *
+ * \sa glUnmapBufferARB, dd_function_table::UnmapBuffer
+ */
+GLboolean
+_mesa_buffer_unmap( struct gl_context *ctx, GLenum target,
+ struct gl_buffer_object *bufObj )
+{
+ (void) ctx;
+ (void) target;
+ /* XXX we might assert here that bufObj->Pointer is non-null */
+ bufObj->Pointer = NULL;
+ bufObj->Length = 0;
+ bufObj->Offset = 0;
+ bufObj->AccessFlags = 0x0;
+ return GL_TRUE;
+}
+
+
+/**
+ * Default fallback for \c dd_function_table::CopyBufferSubData().
+ * Called via glCopyBuffserSubData().
+ */
+static void
+_mesa_copy_buffer_subdata(struct gl_context *ctx,
+ struct gl_buffer_object *src,
+ struct gl_buffer_object *dst,
+ GLintptr readOffset, GLintptr writeOffset,
+ GLsizeiptr size)
+{
+ GLubyte *srcPtr, *dstPtr;
+
+ /* buffer should not already be mapped */
+ assert(!_mesa_bufferobj_mapped(src));
+ assert(!_mesa_bufferobj_mapped(dst));
+
+ srcPtr = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_COPY_READ_BUFFER,
+ GL_READ_ONLY, src);
+ dstPtr = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_COPY_WRITE_BUFFER,
+ GL_WRITE_ONLY, dst);
+
+ if (srcPtr && dstPtr)
+ memcpy(dstPtr + writeOffset, srcPtr + readOffset, size);
+
+ ctx->Driver.UnmapBuffer(ctx, GL_COPY_READ_BUFFER, src);
+ ctx->Driver.UnmapBuffer(ctx, GL_COPY_WRITE_BUFFER, dst);
+}
+
+
+
+/**
+ * Initialize the state associated with buffer objects
+ */
+void
+_mesa_init_buffer_objects( struct gl_context *ctx )
+{
+ memset(&DummyBufferObject, 0, sizeof(DummyBufferObject));
+ DummyBufferObject.RefCount = 1000*1000*1000; /* never delete */
+
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj,
+ ctx->Shared->NullBufferObj);
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj,
+ ctx->Shared->NullBufferObj);
+
+ _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer,
+ ctx->Shared->NullBufferObj);
+ _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer,
+ ctx->Shared->NullBufferObj);
+}
+
+
+void
+_mesa_free_buffer_objects( struct gl_context *ctx )
+{
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj, NULL);
+
+ _mesa_reference_buffer_object(ctx, &ctx->CopyReadBuffer, NULL);
+ _mesa_reference_buffer_object(ctx, &ctx->CopyWriteBuffer, NULL);
+}
+
+
+/**
+ * Bind the specified target to buffer for the specified context.
+ * Called by glBindBuffer() and other functions.
+ */
+static void
+bind_buffer_object(struct gl_context *ctx, GLenum target, GLuint buffer)
+{
+ struct gl_buffer_object *oldBufObj;
+ struct gl_buffer_object *newBufObj = NULL;
+ struct gl_buffer_object **bindTarget = NULL;
+
+ bindTarget = get_buffer_target(ctx, target);
+ if (!bindTarget) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBindBufferARB(target 0x%x)", target);
+ return;
+ }
+
+ /* Get pointer to old buffer object (to be unbound) */
+ oldBufObj = *bindTarget;
+ if (oldBufObj && oldBufObj->Name == buffer)
+ return; /* rebinding the same buffer object- no change */
+
+ /*
+ * Get pointer to new buffer object (newBufObj)
+ */
+ if (buffer == 0) {
+ /* The spec says there's not a buffer object named 0, but we use
+ * one internally because it simplifies things.
+ */
+ newBufObj = ctx->Shared->NullBufferObj;
+ }
+ else {
+ /* non-default buffer object */
+ newBufObj = _mesa_lookup_bufferobj(ctx, buffer);
+ if (!newBufObj || newBufObj == &DummyBufferObject) {
+ /* If this is a new buffer object id, or one which was generated but
+ * never used before, allocate a buffer object now.
+ */
+ ASSERT(ctx->Driver.NewBufferObject);
+ newBufObj = ctx->Driver.NewBufferObject(ctx, buffer, target);
+ if (!newBufObj) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindBufferARB");
+ return;
+ }
+ _mesa_HashInsert(ctx->Shared->BufferObjects, buffer, newBufObj);
+ }
+ }
+
+ /* bind new buffer */
+ _mesa_reference_buffer_object(ctx, bindTarget, newBufObj);
+
+ /* Pass BindBuffer call to device driver */
+ if (ctx->Driver.BindBuffer)
+ ctx->Driver.BindBuffer( ctx, target, newBufObj );
+}
+
+
+/**
+ * Update the default buffer objects in the given context to reference those
+ * specified in the shared state and release those referencing the old
+ * shared state.
+ */
+void
+_mesa_update_default_objects_buffer_objects(struct gl_context *ctx)
+{
+ /* Bind the NullBufferObj to remove references to those
+ * in the shared context hash table.
+ */
+ bind_buffer_object( ctx, GL_ARRAY_BUFFER_ARB, 0);
+ bind_buffer_object( ctx, GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
+ bind_buffer_object( ctx, GL_PIXEL_PACK_BUFFER_ARB, 0);
+ bind_buffer_object( ctx, GL_PIXEL_UNPACK_BUFFER_ARB, 0);
+}
+
+
+/**
+ * When we're about to read pixel data out of a PBO (via glDrawPixels,
+ * glTexImage, etc) or write data into a PBO (via glReadPixels,
+ * glGetTexImage, etc) we call this function to check that we're not
+ * going to read out of bounds.
+ *
+ * XXX This would also be a convenient time to check that the PBO isn't
+ * currently mapped. Whoever calls this function should check for that.
+ * Remember, we can't use a PBO when it's mapped!
+ *
+ * If we're not using a PBO, this is a no-op.
+ *
+ * \param width width of image to read/write
+ * \param height height of image to read/write
+ * \param depth depth of image to read/write
+ * \param format format of image to read/write
+ * \param type datatype of image to read/write
+ * \param ptr the user-provided pointer/offset
+ * \return GL_TRUE if the PBO access is OK, GL_FALSE if the access would
+ * go out of bounds.
+ */
+GLboolean
+_mesa_validate_pbo_access(GLuint dimensions,
+ const struct gl_pixelstore_attrib *pack,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid *ptr)
+{
+ GLvoid *start, *end;
+ const GLubyte *sizeAddr; /* buffer size, cast to a pointer */
+
+ if (!_mesa_is_bufferobj(pack->BufferObj))
+ return GL_TRUE; /* no PBO, OK */
+
+ if (pack->BufferObj->Size == 0)
+ /* no buffer! */
+ return GL_FALSE;
+
+ /* get address of first pixel we'll read */
+ start = _mesa_image_address(dimensions, pack, ptr, width, height,
+ format, type, 0, 0, 0);
+
+ /* get address just past the last pixel we'll read */
+ end = _mesa_image_address(dimensions, pack, ptr, width, height,
+ format, type, depth-1, height-1, width);
+
+
+ sizeAddr = ((const GLubyte *) 0) + pack->BufferObj->Size;
+
+ if ((const GLubyte *) start > sizeAddr) {
+ /* This will catch negative values / wrap-around */
+ return GL_FALSE;
+ }
+ if ((const GLubyte *) end > sizeAddr) {
+ /* Image read goes beyond end of buffer */
+ return GL_FALSE;
+ }
+
+ /* OK! */
+ return GL_TRUE;
+}
+
+
+/**
+ * For commands that read from a PBO (glDrawPixels, glTexImage,
+ * glPolygonStipple, etc), if we're reading from a PBO, map it read-only
+ * and return the pointer into the PBO. If we're not reading from a
+ * PBO, return \p src as-is.
+ * If non-null return, must call _mesa_unmap_pbo_source() when done.
+ *
+ * \return NULL if error, else pointer to start of data
+ */
+const GLvoid *
+_mesa_map_pbo_source(struct gl_context *ctx,
+ const struct gl_pixelstore_attrib *unpack,
+ const GLvoid *src)
+{
+ const GLubyte *buf;
+
+ if (_mesa_is_bufferobj(unpack->BufferObj)) {
+ /* unpack from PBO */
+ buf = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
+ GL_READ_ONLY_ARB,
+ unpack->BufferObj);
+ if (!buf)
+ return NULL;
+
+ buf = ADD_POINTERS(buf, src);
+ }
+ else {
+ /* unpack from normal memory */
+ buf = src;
+ }
+
+ return buf;
+}
+
+
+/**
+ * Combine PBO-read validation and mapping.
+ * If any GL errors are detected, they'll be recorded and NULL returned.
+ * \sa _mesa_validate_pbo_access
+ * \sa _mesa_map_pbo_source
+ * A call to this function should have a matching call to
+ * _mesa_unmap_pbo_source().
+ */
+const GLvoid *
+_mesa_map_validate_pbo_source(struct gl_context *ctx,
+ GLuint dimensions,
+ const struct gl_pixelstore_attrib *unpack,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid *ptr,
+ const char *where)
+{
+ ASSERT(dimensions == 1 || dimensions == 2 || dimensions == 3);
+
+ if (!_mesa_is_bufferobj(unpack->BufferObj)) {
+ /* non-PBO access: no validation to be done */
+ return ptr;
+ }
+
+ if (!_mesa_validate_pbo_access(dimensions, unpack,
+ width, height, depth, format, type, ptr)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(out of bounds PBO access)", where);
+ return NULL;
+ }
+
+ if (_mesa_bufferobj_mapped(unpack->BufferObj)) {
+ /* buffer is already mapped - that's an error */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "%s(PBO is mapped)", where);
+ return NULL;
+ }
+
+ ptr = _mesa_map_pbo_source(ctx, unpack, ptr);
+ return ptr;
+}
+
+
+/**
+ * Counterpart to _mesa_map_pbo_source()
+ */
+void
+_mesa_unmap_pbo_source(struct gl_context *ctx,
+ const struct gl_pixelstore_attrib *unpack)
+{
+ ASSERT(unpack != &ctx->Pack); /* catch pack/unpack mismatch */
+ if (_mesa_is_bufferobj(unpack->BufferObj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
+ unpack->BufferObj);
+ }
+}
+
+
+/**
+ * For commands that write to a PBO (glReadPixels, glGetColorTable, etc),
+ * if we're writing to a PBO, map it write-only and return the pointer
+ * into the PBO. If we're not writing to a PBO, return \p dst as-is.
+ * If non-null return, must call _mesa_unmap_pbo_dest() when done.
+ *
+ * \return NULL if error, else pointer to start of data
+ */
+void *
+_mesa_map_pbo_dest(struct gl_context *ctx,
+ const struct gl_pixelstore_attrib *pack,
+ GLvoid *dest)
+{
+ void *buf;
+
+ if (_mesa_is_bufferobj(pack->BufferObj)) {
+ /* pack into PBO */
+ buf = (GLubyte *) ctx->Driver.MapBuffer(ctx, GL_PIXEL_PACK_BUFFER_EXT,
+ GL_WRITE_ONLY_ARB,
+ pack->BufferObj);
+ if (!buf)
+ return NULL;
+
+ buf = ADD_POINTERS(buf, dest);
+ }
+ else {
+ /* pack to normal memory */
+ buf = dest;
+ }
+
+ return buf;
+}
+
+
+/**
+ * Combine PBO-write validation and mapping.
+ * If any GL errors are detected, they'll be recorded and NULL returned.
+ * \sa _mesa_validate_pbo_access
+ * \sa _mesa_map_pbo_dest
+ * A call to this function should have a matching call to
+ * _mesa_unmap_pbo_dest().
+ */
+GLvoid *
+_mesa_map_validate_pbo_dest(struct gl_context *ctx,
+ GLuint dimensions,
+ const struct gl_pixelstore_attrib *unpack,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, GLvoid *ptr,
+ const char *where)
+{
+ ASSERT(dimensions == 1 || dimensions == 2 || dimensions == 3);
+
+ if (!_mesa_is_bufferobj(unpack->BufferObj)) {
+ /* non-PBO access: no validation to be done */
+ return ptr;
+ }
+
+ if (!_mesa_validate_pbo_access(dimensions, unpack,
+ width, height, depth, format, type, ptr)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(out of bounds PBO access)", where);
+ return NULL;
+ }
+
+ if (_mesa_bufferobj_mapped(unpack->BufferObj)) {
+ /* buffer is already mapped - that's an error */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "%s(PBO is mapped)", where);
+ return NULL;
+ }
+
+ ptr = _mesa_map_pbo_dest(ctx, unpack, ptr);
+ return ptr;
+}
+
+
+/**
+ * Counterpart to _mesa_map_pbo_dest()
+ */
+void
+_mesa_unmap_pbo_dest(struct gl_context *ctx,
+ const struct gl_pixelstore_attrib *pack)
+{
+ ASSERT(pack != &ctx->Unpack); /* catch pack/unpack mismatch */
+ if (_mesa_is_bufferobj(pack->BufferObj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_PACK_BUFFER_EXT, pack->BufferObj);
+ }
+}
+
+
+
+/**
+ * Return the gl_buffer_object for the given ID.
+ * Always return NULL for ID 0.
+ */
+struct gl_buffer_object *
+_mesa_lookup_bufferobj(struct gl_context *ctx, GLuint buffer)
+{
+ if (buffer == 0)
+ return NULL;
+ else
+ return (struct gl_buffer_object *)
+ _mesa_HashLookup(ctx->Shared->BufferObjects, buffer);
+}
+
+
+/**
+ * If *ptr points to obj, set ptr = the Null/default buffer object.
+ * This is a helper for buffer object deletion.
+ * The GL spec says that deleting a buffer object causes it to get
+ * unbound from all arrays in the current context.
+ */
+static void
+unbind(struct gl_context *ctx,
+ struct gl_buffer_object **ptr,
+ struct gl_buffer_object *obj)
+{
+ if (*ptr == obj) {
+ _mesa_reference_buffer_object(ctx, ptr, ctx->Shared->NullBufferObj);
+ }
+}
+
+
+/**
+ * Plug default/fallback buffer object functions into the device
+ * driver hooks.
+ */
+void
+_mesa_init_buffer_object_functions(struct dd_function_table *driver)
+{
+ /* GL_ARB_vertex/pixel_buffer_object */
+ driver->NewBufferObject = _mesa_new_buffer_object;
+ driver->DeleteBuffer = _mesa_delete_buffer_object;
+ driver->BindBuffer = NULL;
+ driver->BufferData = _mesa_buffer_data;
+ driver->BufferSubData = _mesa_buffer_subdata;
+ driver->GetBufferSubData = _mesa_buffer_get_subdata;
+ driver->MapBuffer = _mesa_buffer_map;
+ driver->UnmapBuffer = _mesa_buffer_unmap;
+
+ /* GL_ARB_map_buffer_range */
+ driver->MapBufferRange = _mesa_buffer_map_range;
+ driver->FlushMappedBufferRange = _mesa_buffer_flush_mapped_range;
+
+ /* GL_ARB_copy_buffer */
+ driver->CopyBufferSubData = _mesa_copy_buffer_subdata;
+}
+
+
+
+/**********************************************************************/
+/* API Functions */
+/**********************************************************************/
+
+void GLAPIENTRY
+_mesa_BindBufferARB(GLenum target, GLuint buffer)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBindBuffer(%s, %u)\n",
+ _mesa_lookup_enum_by_nr(target), buffer);
+
+ bind_buffer_object(ctx, target, buffer);
+}
+
+
+/**
+ * Delete a set of buffer objects.
+ *
+ * \param n Number of buffer objects to delete.
+ * \param ids Array of \c n buffer object IDs.
+ */
+void GLAPIENTRY
+_mesa_DeleteBuffersARB(GLsizei n, const GLuint *ids)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLsizei i;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (n < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteBuffersARB(n)");
+ return;
+ }
+
+ _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
+
+ for (i = 0; i < n; i++) {
+ struct gl_buffer_object *bufObj = _mesa_lookup_bufferobj(ctx, ids[i]);
+ if (bufObj) {
+ struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
+ GLuint j;
+
+ ASSERT(bufObj->Name == ids[i] || bufObj == &DummyBufferObject);
+
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ /* if mapped, unmap it now */
+ ctx->Driver.UnmapBuffer(ctx, 0, bufObj);
+ bufObj->AccessFlags = DEFAULT_ACCESS;
+ bufObj->Pointer = NULL;
+ }
+
+ /* unbind any vertex pointers bound to this buffer */
+ unbind(ctx, &arrayObj->Vertex.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->Weight.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->Normal.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->Color.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->SecondaryColor.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->FogCoord.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->Index.BufferObj, bufObj);
+ unbind(ctx, &arrayObj->EdgeFlag.BufferObj, bufObj);
+ for (j = 0; j < Elements(arrayObj->TexCoord); j++) {
+ unbind(ctx, &arrayObj->TexCoord[j].BufferObj, bufObj);
+ }
+ for (j = 0; j < Elements(arrayObj->VertexAttrib); j++) {
+ unbind(ctx, &arrayObj->VertexAttrib[j].BufferObj, bufObj);
+ }
+
+ if (ctx->Array.ArrayBufferObj == bufObj) {
+ _mesa_BindBufferARB( GL_ARRAY_BUFFER_ARB, 0 );
+ }
+ if (ctx->Array.ElementArrayBufferObj == bufObj) {
+ _mesa_BindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 );
+ }
+
+ /* unbind any pixel pack/unpack pointers bound to this buffer */
+ if (ctx->Pack.BufferObj == bufObj) {
+ _mesa_BindBufferARB( GL_PIXEL_PACK_BUFFER_EXT, 0 );
+ }
+ if (ctx->Unpack.BufferObj == bufObj) {
+ _mesa_BindBufferARB( GL_PIXEL_UNPACK_BUFFER_EXT, 0 );
+ }
+
+ /* The ID is immediately freed for re-use */
+ _mesa_HashRemove(ctx->Shared->BufferObjects, ids[i]);
+ _mesa_reference_buffer_object(ctx, &bufObj, NULL);
+ }
+ }
+
+ _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
+}
+
+
+/**
+ * Generate a set of unique buffer object IDs and store them in \c buffer.
+ *
+ * \param n Number of IDs to generate.
+ * \param buffer Array of \c n locations to store the IDs.
+ */
+void GLAPIENTRY
+_mesa_GenBuffersARB(GLsizei n, GLuint *buffer)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLuint first;
+ GLint i;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGenBuffers(%d)\n", n);
+
+ if (n < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGenBuffersARB");
+ return;
+ }
+
+ if (!buffer) {
+ return;
+ }
+
+ /*
+ * This must be atomic (generation and allocation of buffer object IDs)
+ */
+ _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
+
+ first = _mesa_HashFindFreeKeyBlock(ctx->Shared->BufferObjects, n);
+
+ /* Insert the ID and pointer to dummy buffer object into hash table */
+ for (i = 0; i < n; i++) {
+ _mesa_HashInsert(ctx->Shared->BufferObjects, first + i,
+ &DummyBufferObject);
+ buffer[i] = first + i;
+ }
+
+ _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
+}
+
+
+/**
+ * Determine if ID is the name of a buffer object.
+ *
+ * \param id ID of the potential buffer object.
+ * \return \c GL_TRUE if \c id is the name of a buffer object,
+ * \c GL_FALSE otherwise.
+ */
+GLboolean GLAPIENTRY
+_mesa_IsBufferARB(GLuint id)
+{
+ struct gl_buffer_object *bufObj;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
+
+ _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
+ bufObj = _mesa_lookup_bufferobj(ctx, id);
+ _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
+
+ return bufObj && bufObj != &DummyBufferObject;
+}
+
+
+void GLAPIENTRY
+_mesa_BufferDataARB(GLenum target, GLsizeiptrARB size,
+ const GLvoid * data, GLenum usage)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBufferData(%s, %ld, %p, %s)\n",
+ _mesa_lookup_enum_by_nr(target),
+ (long int) size, data,
+ _mesa_lookup_enum_by_nr(usage));
+
+ if (size < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glBufferDataARB(size < 0)");
+ return;
+ }
+
+ switch (usage) {
+ case GL_STREAM_DRAW_ARB:
+ case GL_STREAM_READ_ARB:
+ case GL_STREAM_COPY_ARB:
+ case GL_STATIC_DRAW_ARB:
+ case GL_STATIC_READ_ARB:
+ case GL_STATIC_COPY_ARB:
+ case GL_DYNAMIC_DRAW_ARB:
+ case GL_DYNAMIC_READ_ARB:
+ case GL_DYNAMIC_COPY_ARB:
+ /* OK */
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBufferDataARB(usage)");
+ return;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBufferDataARB(target)" );
+ return;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glBufferDataARB(buffer 0)" );
+ return;
+ }
+
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ /* Unmap the existing buffer. We'll replace it now. Not an error. */
+ ctx->Driver.UnmapBuffer(ctx, target, bufObj);
+ bufObj->AccessFlags = DEFAULT_ACCESS;
+ ASSERT(bufObj->Pointer == NULL);
+ }
+
+ FLUSH_VERTICES(ctx, _NEW_BUFFER_OBJECT);
+
+ bufObj->Written = GL_TRUE;
+
+#ifdef VBO_DEBUG
+ printf("glBufferDataARB(%u, sz %ld, from %p, usage 0x%x)\n",
+ bufObj->Name, size, data, usage);
+#endif
+
+#ifdef BOUNDS_CHECK
+ size += 100;
+#endif
+
+ ASSERT(ctx->Driver.BufferData);
+ if (!ctx->Driver.BufferData( ctx, target, size, data, usage, bufObj )) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBufferDataARB()");
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_BufferSubDataARB(GLenum target, GLintptrARB offset,
+ GLsizeiptrARB size, const GLvoid * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
+ "glBufferSubDataARB" );
+ if (!bufObj) {
+ /* error already recorded */
+ return;
+ }
+
+ if (size == 0)
+ return;
+
+ bufObj->Written = GL_TRUE;
+
+ ASSERT(ctx->Driver.BufferSubData);
+ ctx->Driver.BufferSubData( ctx, target, offset, size, data, bufObj );
+}
+
+
+void GLAPIENTRY
+_mesa_GetBufferSubDataARB(GLenum target, GLintptrARB offset,
+ GLsizeiptrARB size, void * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ bufObj = buffer_object_subdata_range_good( ctx, target, offset, size,
+ "glGetBufferSubDataARB" );
+ if (!bufObj) {
+ /* error already recorded */
+ return;
+ }
+
+ ASSERT(ctx->Driver.GetBufferSubData);
+ ctx->Driver.GetBufferSubData( ctx, target, offset, size, data, bufObj );
+}
+
+
+void * GLAPIENTRY
+_mesa_MapBufferARB(GLenum target, GLenum access)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object * bufObj;
+ GLbitfield accessFlags;
+ void *map;
+
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
+
+ switch (access) {
+ case GL_READ_ONLY_ARB:
+ accessFlags = GL_MAP_READ_BIT;
+ break;
+ case GL_WRITE_ONLY_ARB:
+ accessFlags = GL_MAP_WRITE_BIT;
+ break;
+ case GL_READ_WRITE_ARB:
+ accessFlags = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glMapBufferARB(access)");
+ return NULL;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glMapBufferARB(target)" );
+ return NULL;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glMapBufferARB(buffer 0)" );
+ return NULL;
+ }
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glMapBufferARB(already mapped)");
+ return NULL;
+ }
+
+ ASSERT(ctx->Driver.MapBuffer);
+ map = ctx->Driver.MapBuffer( ctx, target, access, bufObj );
+ if (!map) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
+ return NULL;
+ }
+ else {
+ /* The driver callback should have set these fields.
+ * This is important because other modules (like VBO) might call
+ * the driver function directly.
+ */
+ ASSERT(bufObj->Pointer == map);
+ ASSERT(bufObj->Length == bufObj->Size);
+ ASSERT(bufObj->Offset == 0);
+ bufObj->AccessFlags = accessFlags;
+ }
+
+ if (access == GL_WRITE_ONLY_ARB || access == GL_READ_WRITE_ARB)
+ bufObj->Written = GL_TRUE;
+
+#ifdef VBO_DEBUG
+ printf("glMapBufferARB(%u, sz %ld, access 0x%x)\n",
+ bufObj->Name, bufObj->Size, access);
+ if (access == GL_WRITE_ONLY_ARB) {
+ GLuint i;
+ GLubyte *b = (GLubyte *) bufObj->Pointer;
+ for (i = 0; i < bufObj->Size; i++)
+ b[i] = i & 0xff;
+ }
+#endif
+
+#ifdef BOUNDS_CHECK
+ {
+ GLubyte *buf = (GLubyte *) bufObj->Pointer;
+ GLuint i;
+ /* buffer is 100 bytes larger than requested, fill with magic value */
+ for (i = 0; i < 100; i++) {
+ buf[bufObj->Size - i - 1] = 123;
+ }
+ }
+#endif
+
+ return bufObj->Pointer;
+}
+
+
+GLboolean GLAPIENTRY
+_mesa_UnmapBufferARB(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ GLboolean status = GL_TRUE;
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glUnmapBufferARB(target)" );
+ return GL_FALSE;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glUnmapBufferARB" );
+ return GL_FALSE;
+ }
+ if (!_mesa_bufferobj_mapped(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glUnmapBufferARB");
+ return GL_FALSE;
+ }
+
+#ifdef BOUNDS_CHECK
+ if (bufObj->Access != GL_READ_ONLY_ARB) {
+ GLubyte *buf = (GLubyte *) bufObj->Pointer;
+ GLuint i;
+ /* check that last 100 bytes are still = magic value */
+ for (i = 0; i < 100; i++) {
+ GLuint pos = bufObj->Size - i - 1;
+ if (buf[pos] != 123) {
+ _mesa_warning(ctx, "Out of bounds buffer object write detected"
+ " at position %d (value = %u)\n",
+ pos, buf[pos]);
+ }
+ }
+ }
+#endif
+
+#ifdef VBO_DEBUG
+ if (bufObj->AccessFlags & GL_MAP_WRITE_BIT) {
+ GLuint i, unchanged = 0;
+ GLubyte *b = (GLubyte *) bufObj->Pointer;
+ GLint pos = -1;
+ /* check which bytes changed */
+ for (i = 0; i < bufObj->Size - 1; i++) {
+ if (b[i] == (i & 0xff) && b[i+1] == ((i+1) & 0xff)) {
+ unchanged++;
+ if (pos == -1)
+ pos = i;
+ }
+ }
+ if (unchanged) {
+ printf("glUnmapBufferARB(%u): %u of %ld unchanged, starting at %d\n",
+ bufObj->Name, unchanged, bufObj->Size, pos);
+ }
+ }
+#endif
+
+ status = ctx->Driver.UnmapBuffer( ctx, target, bufObj );
+ bufObj->AccessFlags = DEFAULT_ACCESS;
+ ASSERT(bufObj->Pointer == NULL);
+ ASSERT(bufObj->Offset == 0);
+ ASSERT(bufObj->Length == 0);
+
+ return status;
+}
+
+
+void GLAPIENTRY
+_mesa_GetBufferParameterivARB(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameterivARB(target)" );
+ return;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferParameterivARB" );
+ return;
+ }
+
+ switch (pname) {
+ case GL_BUFFER_SIZE_ARB:
+ *params = (GLint) bufObj->Size;
+ return;
+ case GL_BUFFER_USAGE_ARB:
+ *params = bufObj->Usage;
+ return;
+ case GL_BUFFER_ACCESS_ARB:
+ *params = simplified_access_mode(bufObj->AccessFlags);
+ return;
+ case GL_BUFFER_MAPPED_ARB:
+ *params = _mesa_bufferobj_mapped(bufObj);
+ return;
+ case GL_BUFFER_ACCESS_FLAGS:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = bufObj->AccessFlags;
+ return;
+ case GL_BUFFER_MAP_OFFSET:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = (GLint) bufObj->Offset;
+ return;
+ case GL_BUFFER_MAP_LENGTH:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = (GLint) bufObj->Length;
+ return;
+ default:
+ ; /* fall-through */
+ }
+
+invalid_pname:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameterivARB(pname=%s)",
+ _mesa_lookup_enum_by_nr(pname));
+}
+
+
+/**
+ * New in GL 3.2
+ * This is pretty much a duplicate of GetBufferParameteriv() but the
+ * GL_BUFFER_SIZE_ARB attribute will be 64-bits on a 64-bit system.
+ */
+void GLAPIENTRY
+_mesa_GetBufferParameteri64v(GLenum target, GLenum pname, GLint64 *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameteri64v(target)" );
+ return;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferParameteri64v" );
+ return;
+ }
+
+ switch (pname) {
+ case GL_BUFFER_SIZE_ARB:
+ *params = bufObj->Size;
+ return;
+ case GL_BUFFER_USAGE_ARB:
+ *params = bufObj->Usage;
+ return;
+ case GL_BUFFER_ACCESS_ARB:
+ *params = simplified_access_mode(bufObj->AccessFlags);
+ return;
+ case GL_BUFFER_ACCESS_FLAGS:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = bufObj->AccessFlags;
+ return;
+ case GL_BUFFER_MAPPED_ARB:
+ *params = _mesa_bufferobj_mapped(bufObj);
+ return;
+ case GL_BUFFER_MAP_OFFSET:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = bufObj->Offset;
+ return;
+ case GL_BUFFER_MAP_LENGTH:
+ if (ctx->VersionMajor < 3)
+ goto invalid_pname;
+ *params = bufObj->Length;
+ return;
+ default:
+ ; /* fall-through */
+ }
+
+invalid_pname:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferParameteri64v(pname=%s)",
+ _mesa_lookup_enum_by_nr(pname));
+}
+
+
+void GLAPIENTRY
+_mesa_GetBufferPointervARB(GLenum target, GLenum pname, GLvoid **params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object * bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (pname != GL_BUFFER_MAP_POINTER_ARB) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferPointervARB(pname)");
+ return;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetBufferPointervARB(target)" );
+ return;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glGetBufferPointervARB" );
+ return;
+ }
+
+ *params = bufObj->Pointer;
+}
+
+
+void GLAPIENTRY
+_mesa_CopyBufferSubData(GLenum readTarget, GLenum writeTarget,
+ GLintptr readOffset, GLintptr writeOffset,
+ GLsizeiptr size)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *src, *dst;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ src = get_buffer(ctx, readTarget);
+ if (!src || !_mesa_is_bufferobj(src)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glCopyBuffserSubData(readTarget = 0x%x)", readTarget);
+ return;
+ }
+
+ dst = get_buffer(ctx, writeTarget);
+ if (!dst || !_mesa_is_bufferobj(dst)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glCopyBuffserSubData(writeTarget = 0x%x)", writeTarget);
+ return;
+ }
+
+ if (_mesa_bufferobj_mapped(src)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glCopyBuffserSubData(readBuffer is mapped)");
+ return;
+ }
+
+ if (_mesa_bufferobj_mapped(dst)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glCopyBuffserSubData(writeBuffer is mapped)");
+ return;
+ }
+
+ if (readOffset < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glCopyBuffserSubData(readOffset = %d)", (int) readOffset);
+ return;
+ }
+
+ if (writeOffset < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glCopyBuffserSubData(writeOffset = %d)", (int) writeOffset);
+ return;
+ }
+
+ if (readOffset + size > src->Size) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glCopyBuffserSubData(readOffset + size = %d)",
+ (int) (readOffset + size));
+ return;
+ }
+
+ if (writeOffset + size > dst->Size) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glCopyBuffserSubData(writeOffset + size = %d)",
+ (int) (writeOffset + size));
+ return;
+ }
+
+ if (src == dst) {
+ if (readOffset + size <= writeOffset) {
+ /* OK */
+ }
+ else if (writeOffset + size <= readOffset) {
+ /* OK */
+ }
+ else {
+ /* overlapping src/dst is illegal */
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glCopyBuffserSubData(overlapping src/dst)");
+ return;
+ }
+ }
+
+ ctx->Driver.CopyBufferSubData(ctx, src, dst, readOffset, writeOffset, size);
+}
+
+
+/**
+ * See GL_ARB_map_buffer_range spec
+ */
+void * GLAPIENTRY
+_mesa_MapBufferRange(GLenum target, GLintptr offset, GLsizeiptr length,
+ GLbitfield access)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ void *map;
+
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, NULL);
+
+ if (!ctx->Extensions.ARB_map_buffer_range) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(extension not supported)");
+ return NULL;
+ }
+
+ if (offset < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(offset = %ld)", (long)offset);
+ return NULL;
+ }
+
+ if (length < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(length = %ld)", (long)length);
+ return NULL;
+ }
+
+ if ((access & (GL_MAP_READ_BIT | GL_MAP_WRITE_BIT)) == 0) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(access indicates neither read or write)");
+ return NULL;
+ }
+
+ if (access & GL_MAP_READ_BIT) {
+ if ((access & GL_MAP_INVALIDATE_RANGE_BIT) ||
+ (access & GL_MAP_INVALIDATE_BUFFER_BIT) ||
+ (access & GL_MAP_UNSYNCHRONIZED_BIT)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(invalid access flags)");
+ return NULL;
+ }
+ }
+
+ if ((access & GL_MAP_FLUSH_EXPLICIT_BIT) &&
+ ((access & GL_MAP_WRITE_BIT) == 0)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(invalid access flags)");
+ return NULL;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj || !_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glMapBufferRange(target = 0x%x)", target);
+ return NULL;
+ }
+
+ if (offset + length > bufObj->Size) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(offset + length > size)");
+ return NULL;
+ }
+
+ if (_mesa_bufferobj_mapped(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(buffer already mapped)");
+ return NULL;
+ }
+
+ ASSERT(ctx->Driver.MapBufferRange);
+ map = ctx->Driver.MapBufferRange(ctx, target, offset, length,
+ access, bufObj);
+ if (!map) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMapBufferARB(map failed)");
+ }
+ else {
+ /* The driver callback should have set all these fields.
+ * This is important because other modules (like VBO) might call
+ * the driver function directly.
+ */
+ ASSERT(bufObj->Pointer == map);
+ ASSERT(bufObj->Length == length);
+ ASSERT(bufObj->Offset == offset);
+ ASSERT(bufObj->AccessFlags == access);
+ }
+
+ return map;
+}
+
+
+/**
+ * See GL_ARB_map_buffer_range spec
+ */
+void GLAPIENTRY
+_mesa_FlushMappedBufferRange(GLenum target, GLintptr offset, GLsizeiptr length)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_buffer_object *bufObj;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (!ctx->Extensions.ARB_map_buffer_range) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(extension not supported)");
+ return;
+ }
+
+ if (offset < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(offset = %ld)", (long)offset);
+ return;
+ }
+
+ if (length < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(length = %ld)", (long)length);
+ return;
+ }
+
+ bufObj = get_buffer(ctx, target);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glMapBufferRange(target = 0x%x)", target);
+ return;
+ }
+
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(current buffer is 0)");
+ return;
+ }
+
+ if (!_mesa_bufferobj_mapped(bufObj)) {
+ /* buffer is not mapped */
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(buffer is not mapped)");
+ return;
+ }
+
+ if ((bufObj->AccessFlags & GL_MAP_FLUSH_EXPLICIT_BIT) == 0) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glMapBufferRange(GL_MAP_FLUSH_EXPLICIT_BIT not set)");
+ return;
+ }
+
+ if (offset + length > bufObj->Length) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glMapBufferRange(offset %ld + length %ld > mapped length %ld)",
+ (long)offset, (long)length, (long)bufObj->Length);
+ return;
+ }
+
+ ASSERT(bufObj->AccessFlags & GL_MAP_WRITE_BIT);
+
+ if (ctx->Driver.FlushMappedBufferRange)
+ ctx->Driver.FlushMappedBufferRange(ctx, target, offset, length, bufObj);
+}
+
+
+#if FEATURE_APPLE_object_purgeable
+static GLenum
+_mesa_BufferObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_buffer_object *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_bufferobj(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectPurgeable(name = 0x%x)", name);
+ return 0;
+ }
+ if (!_mesa_is_bufferobj(bufObj)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glObjectPurgeable(buffer 0)" );
+ return 0;
+ }
+
+ if (bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectPurgeable(name = 0x%x) is already purgeable", name);
+ return GL_VOLATILE_APPLE;
+ }
+
+ bufObj->Purgeable = GL_TRUE;
+
+ retval = GL_VOLATILE_APPLE;
+ if (ctx->Driver.BufferObjectPurgeable)
+ retval = ctx->Driver.BufferObjectPurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+static GLenum
+_mesa_RenderObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_renderbuffer *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_renderbuffer(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ if (bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectPurgeable(name = 0x%x) is already purgeable", name);
+ return GL_VOLATILE_APPLE;
+ }
+
+ bufObj->Purgeable = GL_TRUE;
+
+ retval = GL_VOLATILE_APPLE;
+ if (ctx->Driver.RenderObjectPurgeable)
+ retval = ctx->Driver.RenderObjectPurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+static GLenum
+_mesa_TextureObjectPurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_texture_object *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_texture(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectPurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ if (bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectPurgeable(name = 0x%x) is already purgeable", name);
+ return GL_VOLATILE_APPLE;
+ }
+
+ bufObj->Purgeable = GL_TRUE;
+
+ retval = GL_VOLATILE_APPLE;
+ if (ctx->Driver.TextureObjectPurgeable)
+ retval = ctx->Driver.TextureObjectPurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+GLenum GLAPIENTRY
+_mesa_ObjectPurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
+{
+ GLenum retval;
+
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
+
+ if (name == 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectPurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ switch (option) {
+ case GL_VOLATILE_APPLE:
+ case GL_RELEASED_APPLE:
+ /* legal */
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glObjectPurgeable(name = 0x%x) invalid option: %d",
+ name, option);
+ return 0;
+ }
+
+ switch (objectType) {
+ case GL_TEXTURE:
+ retval = _mesa_TextureObjectPurgeable (ctx, name, option);
+ break;
+ case GL_RENDERBUFFER_EXT:
+ retval = _mesa_RenderObjectPurgeable (ctx, name, option);
+ break;
+ case GL_BUFFER_OBJECT_APPLE:
+ retval = _mesa_BufferObjectPurgeable (ctx, name, option);
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glObjectPurgeable(name = 0x%x) invalid type: %d",
+ name, objectType);
+ return 0;
+ }
+
+ /* In strict conformance to the spec, we must only return VOLATILE when
+ * when passed the VOLATILE option. Madness.
+ *
+ * XXX First fix the spec, then fix me.
+ */
+ return option == GL_VOLATILE_APPLE ? GL_VOLATILE_APPLE : retval;
+}
+
+
+static GLenum
+_mesa_BufferObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_buffer_object *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_bufferobj(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ if (! bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectUnpurgeable(name = 0x%x) object is "
+ " already \"unpurged\"", name);
+ return 0;
+ }
+
+ bufObj->Purgeable = GL_FALSE;
+
+ retval = option;
+ if (ctx->Driver.BufferObjectUnpurgeable)
+ retval = ctx->Driver.BufferObjectUnpurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+static GLenum
+_mesa_RenderObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_renderbuffer *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_renderbuffer(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ if (! bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectUnpurgeable(name = 0x%x) object is "
+ " already \"unpurged\"", name);
+ return 0;
+ }
+
+ bufObj->Purgeable = GL_FALSE;
+
+ retval = option;
+ if (ctx->Driver.RenderObjectUnpurgeable)
+ retval = ctx->Driver.RenderObjectUnpurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+static GLenum
+_mesa_TextureObjectUnpurgeable(struct gl_context *ctx, GLuint name, GLenum option)
+{
+ struct gl_texture_object *bufObj;
+ GLenum retval;
+
+ bufObj = _mesa_lookup_texture(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ if (! bufObj->Purgeable) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glObjectUnpurgeable(name = 0x%x) object is"
+ " already \"unpurged\"", name);
+ return 0;
+ }
+
+ bufObj->Purgeable = GL_FALSE;
+
+ retval = option;
+ if (ctx->Driver.TextureObjectUnpurgeable)
+ retval = ctx->Driver.TextureObjectUnpurgeable(ctx, bufObj, option);
+
+ return retval;
+}
+
+
+GLenum GLAPIENTRY
+_mesa_ObjectUnpurgeableAPPLE(GLenum objectType, GLuint name, GLenum option)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
+
+ if (name == 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return 0;
+ }
+
+ switch (option) {
+ case GL_RETAINED_APPLE:
+ case GL_UNDEFINED_APPLE:
+ /* legal */
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glObjectUnpurgeable(name = 0x%x) invalid option: %d",
+ name, option);
+ return 0;
+ }
+
+ switch (objectType) {
+ case GL_BUFFER_OBJECT_APPLE:
+ return _mesa_BufferObjectUnpurgeable(ctx, name, option);
+ case GL_TEXTURE:
+ return _mesa_TextureObjectUnpurgeable(ctx, name, option);
+ case GL_RENDERBUFFER_EXT:
+ return _mesa_RenderObjectUnpurgeable(ctx, name, option);
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glObjectUnpurgeable(name = 0x%x) invalid type: %d",
+ name, objectType);
+ return 0;
+ }
+}
+
+
+static void
+_mesa_GetBufferObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
+ GLenum pname, GLint* params)
+{
+ struct gl_buffer_object *bufObj;
+
+ bufObj = _mesa_lookup_bufferobj(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glGetObjectParameteriv(name = 0x%x) invalid object", name);
+ return;
+ }
+
+ switch (pname) {
+ case GL_PURGEABLE_APPLE:
+ *params = bufObj->Purgeable;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
+ name, pname);
+ break;
+ }
+}
+
+
+static void
+_mesa_GetRenderObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
+ GLenum pname, GLint* params)
+{
+ struct gl_renderbuffer *bufObj;
+
+ bufObj = _mesa_lookup_renderbuffer(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return;
+ }
+
+ switch (pname) {
+ case GL_PURGEABLE_APPLE:
+ *params = bufObj->Purgeable;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
+ name, pname);
+ break;
+ }
+}
+
+
+static void
+_mesa_GetTextureObjectParameterivAPPLE(struct gl_context *ctx, GLuint name,
+ GLenum pname, GLint* params)
+{
+ struct gl_texture_object *bufObj;
+
+ bufObj = _mesa_lookup_texture(ctx, name);
+ if (!bufObj) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glObjectUnpurgeable(name = 0x%x)", name);
+ return;
+ }
+
+ switch (pname) {
+ case GL_PURGEABLE_APPLE:
+ *params = bufObj->Purgeable;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetObjectParameteriv(name = 0x%x) invalid enum: %d",
+ name, pname);
+ break;
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GetObjectParameterivAPPLE(GLenum objectType, GLuint name, GLenum pname,
+ GLint* params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (name == 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glGetObjectParameteriv(name = 0x%x)", name);
+ return;
+ }
+
+ switch (objectType) {
+ case GL_TEXTURE:
+ _mesa_GetTextureObjectParameterivAPPLE (ctx, name, pname, params);
+ break;
+ case GL_BUFFER_OBJECT_APPLE:
+ _mesa_GetBufferObjectParameterivAPPLE (ctx, name, pname, params);
+ break;
+ case GL_RENDERBUFFER_EXT:
+ _mesa_GetRenderObjectParameterivAPPLE (ctx, name, pname, params);
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetObjectParameteriv(name = 0x%x) invalid type: %d",
+ name, objectType);
+ }
+}
+
+#endif /* FEATURE_APPLE_object_purgeable */
diff --git a/mesalib/src/mesa/main/compiler.h b/mesalib/src/mesa/main/compiler.h
index 41cd48bc6..c1d773b18 100644
--- a/mesalib/src/mesa/main/compiler.h
+++ b/mesalib/src/mesa/main/compiler.h
@@ -60,29 +60,7 @@ extern "C" {
/**
* Get standard integer types
*/
-#if defined(_MSC_VER)
- typedef __int8 int8_t;
- typedef unsigned __int8 uint8_t;
- typedef __int16 int16_t;
- typedef unsigned __int16 uint16_t;
- typedef __int32 int32_t;
- typedef unsigned __int32 uint32_t;
- typedef __int64 int64_t;
- typedef unsigned __int64 uint64_t;
-
-# if defined(_WIN64)
- typedef __int64 intptr_t;
- typedef unsigned __int64 uintptr_t;
-# else
- typedef __int32 intptr_t;
- typedef unsigned __int32 uintptr_t;
-# endif
-
-# define INT64_C(__val) __val##i64
-# define UINT64_C(__val) __val##ui64
-#else
-# include <stdint.h>
-#endif
+#include <stdint.h>
/**
diff --git a/mesalib/src/mesa/main/context.c b/mesalib/src/mesa/main/context.c
index a94231455..cfb6b348b 100644
--- a/mesalib/src/mesa/main/context.c
+++ b/mesalib/src/mesa/main/context.c
@@ -1,1882 +1,1882 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.3
- *
- * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
- * Copyright (C) 2008 VMware, Inc. 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 context.c
- * Mesa context/visual/framebuffer management functions.
- * \author Brian Paul
- */
-
-/**
- * \mainpage Mesa Main Module
- *
- * \section MainIntroduction Introduction
- *
- * The Mesa Main module consists of all the files in the main/ directory.
- * Among the features of this module are:
- * <UL>
- * <LI> Structures to represent most GL state </LI>
- * <LI> State set/get functions </LI>
- * <LI> Display lists </LI>
- * <LI> Texture unit, object and image handling </LI>
- * <LI> Matrix and attribute stacks </LI>
- * </UL>
- *
- * Other modules are responsible for API dispatch, vertex transformation,
- * point/line/triangle setup, rasterization, vertex array caching,
- * vertex/fragment programs/shaders, etc.
- *
- *
- * \section AboutDoxygen About Doxygen
- *
- * If you're viewing this information as Doxygen-generated HTML you'll
- * see the documentation index at the top of this page.
- *
- * The first line lists the Mesa source code modules.
- * The second line lists the indexes available for viewing the documentation
- * for each module.
- *
- * Selecting the <b>Main page</b> link will display a summary of the module
- * (this page).
- *
- * Selecting <b>Data Structures</b> will list all C structures.
- *
- * Selecting the <b>File List</b> link will list all the source files in
- * the module.
- * Selecting a filename will show a list of all functions defined in that file.
- *
- * Selecting the <b>Data Fields</b> link will display a list of all
- * documented structure members.
- *
- * Selecting the <b>Globals</b> link will display a list
- * of all functions, structures, global variables and macros in the module.
- *
- */
-
-
-#include "glheader.h"
-#include "mfeatures.h"
-#include "imports.h"
-#include "accum.h"
-#include "api_exec.h"
-#include "arrayobj.h"
-#include "attrib.h"
-#include "blend.h"
-#include "buffers.h"
-#include "bufferobj.h"
-#include "context.h"
-#include "cpuinfo.h"
-#include "debug.h"
-#include "depth.h"
-#include "dlist.h"
-#include "eval.h"
-#include "extensions.h"
-#include "fbobject.h"
-#include "feedback.h"
-#include "fog.h"
-#include "formats.h"
-#include "framebuffer.h"
-#include "hint.h"
-#include "hash.h"
-#include "light.h"
-#include "lines.h"
-#include "macros.h"
-#include "matrix.h"
-#include "multisample.h"
-#include "pixel.h"
-#include "pixelstore.h"
-#include "points.h"
-#include "polygon.h"
-#include "queryobj.h"
-#include "syncobj.h"
-#include "rastpos.h"
-#include "remap.h"
-#include "scissor.h"
-#include "shared.h"
-#include "shaderobj.h"
-#include "simple_list.h"
-#include "state.h"
-#include "stencil.h"
-#include "texcompress_s3tc.h"
-#include "texstate.h"
-#include "transformfeedback.h"
-#include "mtypes.h"
-#include "varray.h"
-#include "version.h"
-#include "viewport.h"
-#include "vtxfmt.h"
-#include "program/program.h"
-#include "program/prog_print.h"
-#if _HAVE_FULL_GL
-#include "math/m_matrix.h"
-#endif
-#include "main/dispatch.h" /* for _gloffset_COUNT */
-
-#ifdef USE_SPARC_ASM
-#include "sparc/sparc.h"
-#endif
-
-#include "glsl_parser_extras.h"
-#include <stdbool.h>
-
-
-#ifndef MESA_VERBOSE
-int MESA_VERBOSE = 0;
-#endif
-
-#ifndef MESA_DEBUG_FLAGS
-int MESA_DEBUG_FLAGS = 0;
-#endif
-
-
-/* ubyte -> float conversion */
-GLfloat _mesa_ubyte_to_float_color_tab[256];
-
-
-
-/**
- * Swap buffers notification callback.
- *
- * \param ctx GL context.
- *
- * Called by window system just before swapping buffers.
- * We have to finish any pending rendering.
- */
-void
-_mesa_notifySwapBuffers(struct gl_context *ctx)
-{
- if (MESA_VERBOSE & VERBOSE_SWAPBUFFERS)
- _mesa_debug(ctx, "SwapBuffers\n");
- FLUSH_CURRENT( ctx, 0 );
- if (ctx->Driver.Flush) {
- ctx->Driver.Flush(ctx);
- }
-}
-
-
-/**********************************************************************/
-/** \name GL Visual allocation/destruction */
-/**********************************************************************/
-/*@{*/
-
-/**
- * Allocates a struct gl_config structure and initializes it via
- * _mesa_initialize_visual().
- *
- * \param dbFlag double buffering
- * \param stereoFlag stereo buffer
- * \param depthBits requested bits per depth buffer value. Any value in [0, 32]
- * is acceptable but the actual depth type will be GLushort or GLuint as
- * needed.
- * \param stencilBits requested minimum bits per stencil buffer value
- * \param accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits number of bits per color component in accum buffer.
- * \param indexBits number of bits per pixel if \p rgbFlag is GL_FALSE
- * \param redBits number of bits per color component in frame buffer for RGB(A)
- * mode. We always use 8 in core Mesa though.
- * \param greenBits same as above.
- * \param blueBits same as above.
- * \param alphaBits same as above.
- * \param numSamples not really used.
- *
- * \return pointer to new struct gl_config or NULL if requested parameters can't be
- * met.
- *
- * \note Need to add params for level and numAuxBuffers (at least)
- */
-struct gl_config *
-_mesa_create_visual( GLboolean dbFlag,
- GLboolean stereoFlag,
- GLint redBits,
- GLint greenBits,
- GLint blueBits,
- GLint alphaBits,
- GLint depthBits,
- GLint stencilBits,
- GLint accumRedBits,
- GLint accumGreenBits,
- GLint accumBlueBits,
- GLint accumAlphaBits,
- GLint numSamples )
-{
- struct gl_config *vis = CALLOC_STRUCT(gl_config);
- if (vis) {
- if (!_mesa_initialize_visual(vis, dbFlag, stereoFlag,
- redBits, greenBits, blueBits, alphaBits,
- depthBits, stencilBits,
- accumRedBits, accumGreenBits,
- accumBlueBits, accumAlphaBits,
- numSamples)) {
- free(vis);
- return NULL;
- }
- }
- return vis;
-}
-
-
-/**
- * Makes some sanity checks and fills in the fields of the struct
- * gl_config object with the given parameters. If the caller needs to
- * set additional fields, he should just probably init the whole
- * gl_config object himself.
- *
- * \return GL_TRUE on success, or GL_FALSE on failure.
- *
- * \sa _mesa_create_visual() above for the parameter description.
- */
-GLboolean
-_mesa_initialize_visual( struct gl_config *vis,
- GLboolean dbFlag,
- GLboolean stereoFlag,
- GLint redBits,
- GLint greenBits,
- GLint blueBits,
- GLint alphaBits,
- GLint depthBits,
- GLint stencilBits,
- GLint accumRedBits,
- GLint accumGreenBits,
- GLint accumBlueBits,
- GLint accumAlphaBits,
- GLint numSamples )
-{
- assert(vis);
-
- if (depthBits < 0 || depthBits > 32) {
- return GL_FALSE;
- }
- if (stencilBits < 0 || stencilBits > STENCIL_BITS) {
- return GL_FALSE;
- }
- assert(accumRedBits >= 0);
- assert(accumGreenBits >= 0);
- assert(accumBlueBits >= 0);
- assert(accumAlphaBits >= 0);
-
- vis->rgbMode = GL_TRUE;
- vis->doubleBufferMode = dbFlag;
- vis->stereoMode = stereoFlag;
-
- vis->redBits = redBits;
- vis->greenBits = greenBits;
- vis->blueBits = blueBits;
- vis->alphaBits = alphaBits;
- vis->rgbBits = redBits + greenBits + blueBits;
-
- vis->indexBits = 0;
- vis->depthBits = depthBits;
- vis->stencilBits = stencilBits;
-
- vis->accumRedBits = accumRedBits;
- vis->accumGreenBits = accumGreenBits;
- vis->accumBlueBits = accumBlueBits;
- vis->accumAlphaBits = accumAlphaBits;
-
- vis->haveAccumBuffer = accumRedBits > 0;
- vis->haveDepthBuffer = depthBits > 0;
- vis->haveStencilBuffer = stencilBits > 0;
-
- vis->numAuxBuffers = 0;
- vis->level = 0;
- vis->sampleBuffers = numSamples > 0 ? 1 : 0;
- vis->samples = numSamples;
-
- return GL_TRUE;
-}
-
-
-/**
- * Destroy a visual and free its memory.
- *
- * \param vis visual.
- *
- * Frees the visual structure.
- */
-void
-_mesa_destroy_visual( struct gl_config *vis )
-{
- free(vis);
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name Context allocation, initialization, destroying
- *
- * The purpose of the most initialization functions here is to provide the
- * default state values according to the OpenGL specification.
- */
-/**********************************************************************/
-/*@{*/
-
-
-/**
- * This is lame. gdb only seems to recognize enum types that are
- * actually used somewhere. We want to be able to print/use enum
- * values such as TEXTURE_2D_INDEX in gdb. But we don't actually use
- * the gl_texture_index type anywhere. Thus, this lame function.
- */
-static void
-dummy_enum_func(void)
-{
- gl_buffer_index bi = BUFFER_FRONT_LEFT;
- gl_face_index fi = FACE_POS_X;
- gl_frag_attrib fa = FRAG_ATTRIB_WPOS;
- gl_frag_result fr = FRAG_RESULT_DEPTH;
- gl_texture_index ti = TEXTURE_2D_ARRAY_INDEX;
- gl_vert_attrib va = VERT_ATTRIB_POS;
- gl_vert_result vr = VERT_RESULT_HPOS;
- gl_geom_attrib ga = GEOM_ATTRIB_POSITION;
- gl_geom_result gr = GEOM_RESULT_POS;
-
- (void) bi;
- (void) fi;
- (void) fa;
- (void) fr;
- (void) ti;
- (void) va;
- (void) vr;
- (void) ga;
- (void) gr;
-}
-
-
-/**
- * One-time initialization mutex lock.
- *
- * \sa Used by one_time_init().
- */
-_glthread_DECLARE_STATIC_MUTEX(OneTimeLock);
-
-
-
-/**
- * Calls all the various one-time-init functions in Mesa.
- *
- * While holding a global mutex lock, calls several initialization functions,
- * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
- * defined.
- *
- * \sa _math_init().
- */
-static void
-one_time_init( struct gl_context *ctx )
-{
- static GLbitfield api_init_mask = 0x0;
-
- _glthread_LOCK_MUTEX(OneTimeLock);
-
- /* truly one-time init */
- if (!api_init_mask) {
- GLuint i;
-
- /* do some implementation tests */
- assert( sizeof(GLbyte) == 1 );
- assert( sizeof(GLubyte) == 1 );
- assert( sizeof(GLshort) == 2 );
- assert( sizeof(GLushort) == 2 );
- assert( sizeof(GLint) == 4 );
- assert( sizeof(GLuint) == 4 );
-
- _mesa_get_cpu_features();
-
- _mesa_init_sqrt_table();
-
- /* context dependence is never a one-time thing... */
- _mesa_init_get_hash(ctx);
-
- for (i = 0; i < 256; i++) {
- _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
- }
-
-#if defined(DEBUG) && defined(__DATE__) && defined(__TIME__)
- if (MESA_VERBOSE != 0) {
- _mesa_debug(ctx, "Mesa %s DEBUG build %s %s\n",
- MESA_VERSION_STRING, __DATE__, __TIME__);
- }
-#endif
-
-#ifdef DEBUG
- _mesa_test_formats();
-#endif
- }
-
- /* per-API one-time init */
- if (!(api_init_mask & (1 << ctx->API))) {
- /*
- * This is fine as ES does not use the remap table, but it may not be
- * future-proof. We cannot always initialize the remap table because
- * when an app is linked to libGLES*, there are not enough dynamic
- * entries.
- */
- if (ctx->API == API_OPENGL)
- _mesa_init_remap_table();
- }
-
- api_init_mask |= 1 << ctx->API;
-
- _glthread_UNLOCK_MUTEX(OneTimeLock);
-
- /* Hopefully atexit() is widely available. If not, we may need some
- * #ifdef tests here.
- */
- atexit(_mesa_destroy_shader_compiler);
-
- dummy_enum_func();
-}
-
-
-/**
- * Initialize fields of gl_current_attrib (aka ctx->Current.*)
- */
-static void
-_mesa_init_current(struct gl_context *ctx)
-{
- GLuint i;
-
- /* Init all to (0,0,0,1) */
- for (i = 0; i < Elements(ctx->Current.Attrib); i++) {
- ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
- }
-
- /* redo special cases: */
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 0.0 );
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
- ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
-}
-
-
-/**
- * Init vertex/fragment/geometry program limits.
- * Important: drivers should override these with actual limits.
- */
-static void
-init_program_limits(GLenum type, struct gl_program_constants *prog)
-{
- prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
- prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
- prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
- prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
- prog->MaxTemps = MAX_PROGRAM_TEMPS;
- prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
- prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
- prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
-
- switch (type) {
- case GL_VERTEX_PROGRAM_ARB:
- prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
- prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
- prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
- break;
- case GL_FRAGMENT_PROGRAM_ARB:
- prog->MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS;
- prog->MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS;
- prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
- break;
- case MESA_GEOMETRY_PROGRAM:
- prog->MaxParameters = MAX_NV_VERTEX_PROGRAM_PARAMS;
- prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
- prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
-
- prog->MaxGeometryTextureImageUnits = MAX_GEOMETRY_TEXTURE_IMAGE_UNITS;
- prog->MaxGeometryVaryingComponents = MAX_GEOMETRY_VARYING_COMPONENTS;
- prog->MaxVertexVaryingComponents = MAX_VERTEX_VARYING_COMPONENTS;
- prog->MaxGeometryUniformComponents = MAX_GEOMETRY_UNIFORM_COMPONENTS;
- prog->MaxGeometryOutputVertices = MAX_GEOMETRY_OUTPUT_VERTICES;
- prog->MaxGeometryTotalOutputComponents = MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS;
- break;
- default:
- assert(0 && "Bad program type in init_program_limits()");
- }
-
- /* Set the native limits to zero. This implies that there is no native
- * support for shaders. Let the drivers fill in the actual values.
- */
- prog->MaxNativeInstructions = 0;
- prog->MaxNativeAluInstructions = 0;
- prog->MaxNativeTexInstructions = 0;
- prog->MaxNativeTexIndirections = 0;
- prog->MaxNativeAttribs = 0;
- prog->MaxNativeTemps = 0;
- prog->MaxNativeAddressRegs = 0;
- prog->MaxNativeParameters = 0;
-
- /* Set GLSL datatype range/precision info assuming IEEE float values.
- * Drivers should override these defaults as needed.
- */
- prog->MediumFloat.RangeMin = 127;
- prog->MediumFloat.RangeMax = 127;
- prog->MediumFloat.Precision = 23;
- prog->LowFloat = prog->HighFloat = prog->MediumFloat;
-
- /* Assume ints are stored as floats for now, since this is the least-common
- * denominator. The OpenGL ES spec implies (page 132) that the precision
- * of integer types should be 0. Practically speaking, IEEE
- * single-precision floating point values can only store integers in the
- * range [-0x01000000, 0x01000000] without loss of precision.
- */
- prog->MediumInt.RangeMin = 24;
- prog->MediumInt.RangeMax = 24;
- prog->MediumInt.Precision = 0;
- prog->LowInt = prog->HighInt = prog->MediumInt;
-}
-
-
-/**
- * Initialize fields of gl_constants (aka ctx->Const.*).
- * Use defaults from config.h. The device drivers will often override
- * some of these values (such as number of texture units).
- */
-static void
-_mesa_init_constants(struct gl_context *ctx)
-{
- assert(ctx);
-
- /* Constants, may be overriden (usually only reduced) by device drivers */
- ctx->Const.MaxTextureMbytes = MAX_TEXTURE_MBYTES;
- ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS;
- ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS;
- ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS;
- ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
- ctx->Const.MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
- ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
- ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
- ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits,
- ctx->Const.MaxTextureImageUnits);
- ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
- ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
- ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
- ctx->Const.SubPixelBits = SUB_PIXEL_BITS;
- ctx->Const.MinPointSize = MIN_POINT_SIZE;
- ctx->Const.MaxPointSize = MAX_POINT_SIZE;
- ctx->Const.MinPointSizeAA = MIN_POINT_SIZE;
- ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE;
- ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
- ctx->Const.MinLineWidth = MIN_LINE_WIDTH;
- ctx->Const.MaxLineWidth = MAX_LINE_WIDTH;
- ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH;
- ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH;
- ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
- ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE;
- ctx->Const.MaxClipPlanes = MAX_CLIP_PLANES;
- ctx->Const.MaxLights = MAX_LIGHTS;
- ctx->Const.MaxShininess = 128.0;
- ctx->Const.MaxSpotExponent = 128.0;
- ctx->Const.MaxViewportWidth = MAX_WIDTH;
- ctx->Const.MaxViewportHeight = MAX_HEIGHT;
-#if FEATURE_ARB_vertex_program
- init_program_limits(GL_VERTEX_PROGRAM_ARB, &ctx->Const.VertexProgram);
-#endif
-#if FEATURE_ARB_fragment_program
- init_program_limits(GL_FRAGMENT_PROGRAM_ARB, &ctx->Const.FragmentProgram);
-#endif
-#if FEATURE_ARB_geometry_shader4
- init_program_limits(MESA_GEOMETRY_PROGRAM, &ctx->Const.GeometryProgram);
-#endif
- ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES;
- ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
-
- /* CheckArrayBounds is overriden by drivers/x11 for X server */
- ctx->Const.CheckArrayBounds = GL_FALSE;
-
- /* GL_ARB_draw_buffers */
- ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS;
-
-#if FEATURE_EXT_framebuffer_object
- ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
- ctx->Const.MaxRenderbufferSize = MAX_WIDTH;
-#endif
-
-#if FEATURE_ARB_vertex_shader
- ctx->Const.MaxVertexTextureImageUnits = MAX_VERTEX_TEXTURE_IMAGE_UNITS;
- ctx->Const.MaxCombinedTextureImageUnits = MAX_COMBINED_TEXTURE_IMAGE_UNITS;
- ctx->Const.MaxVarying = MAX_VARYING;
-#endif
-
- /* Shading language version */
- if (ctx->API == API_OPENGL) {
- ctx->Const.GLSLVersion = 120;
- }
- else if (ctx->API == API_OPENGLES2) {
- ctx->Const.GLSLVersion = 100;
- }
- else if (ctx->API == API_OPENGLES) {
- ctx->Const.GLSLVersion = 0; /* GLSL not supported */
- }
-
- /* GL_ARB_framebuffer_object */
- ctx->Const.MaxSamples = 0;
-
- /* GL_ARB_sync */
- ctx->Const.MaxServerWaitTimeout = (GLuint64) ~0;
-
- /* GL_ATI_envmap_bumpmap */
- ctx->Const.SupportedBumpUnits = SUPPORTED_ATI_BUMP_UNITS;
-
- /* GL_EXT_provoking_vertex */
- ctx->Const.QuadsFollowProvokingVertexConvention = GL_TRUE;
-
- /* GL_EXT_transform_feedback */
- ctx->Const.MaxTransformFeedbackSeparateAttribs = MAX_FEEDBACK_ATTRIBS;
- ctx->Const.MaxTransformFeedbackSeparateComponents = 4 * MAX_FEEDBACK_ATTRIBS;
- ctx->Const.MaxTransformFeedbackInterleavedComponents = 4 * MAX_FEEDBACK_ATTRIBS;
-
- /* GL 3.2: hard-coded for now: */
- ctx->Const.ProfileMask = GL_CONTEXT_COMPATIBILITY_PROFILE_BIT;
-
- /** GL_EXT_gpu_shader4 */
- ctx->Const.MinProgramTexelOffset = -8;
- ctx->Const.MaxProgramTexelOffset = 7;
-}
-
-
-/**
- * Do some sanity checks on the limits/constants for the given context.
- * Only called the first time a context is bound.
- */
-static void
-check_context_limits(struct gl_context *ctx)
-{
- /* check that we don't exceed the size of various bitfields */
- assert(VERT_RESULT_MAX <=
- (8 * sizeof(ctx->VertexProgram._Current->Base.OutputsWritten)));
- assert(FRAG_ATTRIB_MAX <=
- (8 * sizeof(ctx->FragmentProgram._Current->Base.InputsRead)));
-
- assert(MAX_COMBINED_TEXTURE_IMAGE_UNITS <= 8 * sizeof(GLbitfield));
-
- /* shader-related checks */
- assert(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
- assert(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
-
- assert(MAX_NV_FRAGMENT_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
- assert(MAX_NV_VERTEX_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
- assert(MAX_NV_VERTEX_PROGRAM_INPUTS <= VERT_ATTRIB_MAX);
- assert(MAX_NV_VERTEX_PROGRAM_OUTPUTS <= VERT_RESULT_MAX);
-
- /* Texture unit checks */
- assert(ctx->Const.MaxTextureImageUnits > 0);
- assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
- assert(ctx->Const.MaxTextureCoordUnits > 0);
- assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
- assert(ctx->Const.MaxTextureUnits > 0);
- assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
- assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
- assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
- ctx->Const.MaxTextureCoordUnits));
- assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
- assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
- assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
- /* number of coord units cannot be greater than number of image units */
- assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
-
-
- /* Texture size checks */
- assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
- assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
- assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
- assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
-
- /* make sure largest texture image is <= MAX_WIDTH in size */
- assert((1 << (ctx->Const.MaxTextureLevels - 1)) <= MAX_WIDTH);
- assert((1 << (ctx->Const.MaxCubeTextureLevels - 1)) <= MAX_WIDTH);
- assert((1 << (ctx->Const.Max3DTextureLevels - 1)) <= MAX_WIDTH);
-
- /* Texture level checks */
- assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
- assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
-
- /* Max texture size should be <= max viewport size (render to texture) */
- assert((1 << (MAX_TEXTURE_LEVELS - 1)) <= MAX_WIDTH);
-
- assert(ctx->Const.MaxViewportWidth <= MAX_WIDTH);
- assert(ctx->Const.MaxViewportHeight <= MAX_WIDTH);
-
- assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
-
- /* if this fails, add more enum values to gl_buffer_index */
- assert(BUFFER_COLOR0 + MAX_DRAW_BUFFERS <= BUFFER_COUNT);
-
- /* XXX probably add more tests */
-}
-
-
-/**
- * Initialize the attribute groups in a GL context.
- *
- * \param ctx GL context.
- *
- * Initializes all the attributes, calling the respective <tt>init*</tt>
- * functions for the more complex data structures.
- */
-static GLboolean
-init_attrib_groups(struct gl_context *ctx)
-{
- assert(ctx);
-
- /* Constants */
- _mesa_init_constants( ctx );
-
- /* Extensions */
- _mesa_init_extensions( ctx );
-
- /* Attribute Groups */
- _mesa_init_accum( ctx );
- _mesa_init_attrib( ctx );
- _mesa_init_buffer_objects( ctx );
- _mesa_init_color( ctx );
- _mesa_init_current( ctx );
- _mesa_init_depth( ctx );
- _mesa_init_debug( ctx );
- _mesa_init_display_list( ctx );
- _mesa_init_eval( ctx );
- _mesa_init_fbobjects( ctx );
- _mesa_init_feedback( ctx );
- _mesa_init_fog( ctx );
- _mesa_init_hint( ctx );
- _mesa_init_line( ctx );
- _mesa_init_lighting( ctx );
- _mesa_init_matrix( ctx );
- _mesa_init_multisample( ctx );
- _mesa_init_pixel( ctx );
- _mesa_init_pixelstore( ctx );
- _mesa_init_point( ctx );
- _mesa_init_polygon( ctx );
- _mesa_init_program( ctx );
- _mesa_init_queryobj( ctx );
- _mesa_init_sync( ctx );
- _mesa_init_rastpos( ctx );
- _mesa_init_scissor( ctx );
- _mesa_init_shader_state( ctx );
- _mesa_init_stencil( ctx );
- _mesa_init_transform( ctx );
- _mesa_init_transform_feedback( ctx );
- _mesa_init_varray( ctx );
- _mesa_init_viewport( ctx );
-
- if (!_mesa_init_texture( ctx ))
- return GL_FALSE;
-
- _mesa_init_texture_s3tc( ctx );
-
- /* Miscellaneous */
- ctx->NewState = _NEW_ALL;
- ctx->ErrorValue = (GLenum) GL_NO_ERROR;
- ctx->varying_vp_inputs = ~0;
-
- return GL_TRUE;
-}
-
-
-/**
- * Update default objects in a GL context with respect to shared state.
- *
- * \param ctx GL context.
- *
- * Removes references to old default objects, (texture objects, program
- * objects, etc.) and changes to reference those from the current shared
- * state.
- */
-static GLboolean
-update_default_objects(struct gl_context *ctx)
-{
- assert(ctx);
-
- _mesa_update_default_objects_program(ctx);
- _mesa_update_default_objects_texture(ctx);
- _mesa_update_default_objects_buffer_objects(ctx);
-
- return GL_TRUE;
-}
-
-
-/**
- * This is the default function we plug into all dispatch table slots
- * This helps prevents a segfault when someone calls a GL function without
- * first checking if the extension's supported.
- */
-static int
-generic_nop(void)
-{
- _mesa_warning(NULL, "User called no-op dispatch function (an unsupported extension function?)");
- return 0;
-}
-
-
-/**
- * Allocate and initialize a new dispatch table.
- */
-struct _glapi_table *
-_mesa_alloc_dispatch_table(int size)
-{
- /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
- * In practice, this'll be the same for stand-alone Mesa. But for DRI
- * Mesa we do this to accomodate different versions of libGL and various
- * DRI drivers.
- */
- GLint numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
- struct _glapi_table *table;
-
- /* should never happen, but just in case */
- numEntries = MAX2(numEntries, size);
-
- table = (struct _glapi_table *) malloc(numEntries * sizeof(_glapi_proc));
- if (table) {
- _glapi_proc *entry = (_glapi_proc *) table;
- GLint i;
- for (i = 0; i < numEntries; i++) {
- entry[i] = (_glapi_proc) generic_nop;
- }
- }
- return table;
-}
-
-
-/**
- * Initialize a struct gl_context struct (rendering context).
- *
- * This includes allocating all the other structs and arrays which hang off of
- * the context by pointers.
- * Note that the driver needs to pass in its dd_function_table here since
- * we need to at least call driverFunctions->NewTextureObject to create the
- * default texture objects.
- *
- * Called by _mesa_create_context().
- *
- * Performs the imports and exports callback tables initialization, and
- * miscellaneous one-time initializations. If no shared context is supplied one
- * is allocated, and increase its reference count. Setups the GL API dispatch
- * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
- * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
- * for debug flags.
- *
- * \param ctx the context to initialize
- * \param api the GL API type to create the context for
- * \param visual describes the visual attributes for this context
- * \param share_list points to context to share textures, display lists,
- * etc with, or NULL
- * \param driverFunctions table of device driver functions for this context
- * to use
- * \param driverContext pointer to driver-specific context data
- */
-GLboolean
-_mesa_initialize_context(struct gl_context *ctx,
- gl_api api,
- const struct gl_config *visual,
- struct gl_context *share_list,
- const struct dd_function_table *driverFunctions,
- void *driverContext)
-{
- struct gl_shared_state *shared;
- int i;
-
- /*ASSERT(driverContext);*/
- assert(driverFunctions->NewTextureObject);
- assert(driverFunctions->FreeTexImageData);
-
- ctx->API = api;
- ctx->Visual = *visual;
- ctx->DrawBuffer = NULL;
- ctx->ReadBuffer = NULL;
- ctx->WinSysDrawBuffer = NULL;
- ctx->WinSysReadBuffer = NULL;
-
- /* misc one-time initializations */
- one_time_init(ctx);
-
- /* Plug in driver functions and context pointer here.
- * This is important because when we call alloc_shared_state() below
- * we'll call ctx->Driver.NewTextureObject() to create the default
- * textures.
- */
- ctx->Driver = *driverFunctions;
- ctx->DriverCtx = driverContext;
-
- if (share_list) {
- /* share state with another context */
- shared = share_list->Shared;
- }
- else {
- /* allocate new, unshared state */
- shared = _mesa_alloc_shared_state(ctx);
- if (!shared)
- return GL_FALSE;
- }
-
- _glthread_LOCK_MUTEX(shared->Mutex);
- ctx->Shared = shared;
- shared->RefCount++;
- _glthread_UNLOCK_MUTEX(shared->Mutex);
-
- if (!init_attrib_groups( ctx )) {
- _mesa_release_shared_state(ctx, ctx->Shared);
- return GL_FALSE;
- }
-
-#if FEATURE_dispatch
- /* setup the API dispatch tables */
- switch (ctx->API) {
-#if FEATURE_GL
- case API_OPENGL:
- ctx->Exec = _mesa_create_exec_table();
- break;
-#endif
-#if FEATURE_ES1
- case API_OPENGLES:
- ctx->Exec = _mesa_create_exec_table_es1();
- break;
-#endif
-#if FEATURE_ES2
- case API_OPENGLES2:
- ctx->Exec = _mesa_create_exec_table_es2();
- break;
-#endif
- default:
- _mesa_problem(ctx, "unknown or unsupported API");
- break;
- }
-
- if (!ctx->Exec) {
- _mesa_release_shared_state(ctx, ctx->Shared);
- return GL_FALSE;
- }
-#endif
- ctx->CurrentDispatch = ctx->Exec;
-
- ctx->FragmentProgram._MaintainTexEnvProgram
- = (_mesa_getenv("MESA_TEX_PROG") != NULL);
-
- ctx->VertexProgram._MaintainTnlProgram
- = (_mesa_getenv("MESA_TNL_PROG") != NULL);
- if (ctx->VertexProgram._MaintainTnlProgram) {
- /* this is required... */
- ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
- }
-
- /* Mesa core handles all the formats that mesa core knows about.
- * Drivers will want to override this list with just the formats
- * they can handle, and confirm that appropriate fallbacks exist in
- * _mesa_choose_tex_format().
- */
- memset(&ctx->TextureFormatSupported, GL_TRUE,
- sizeof(ctx->TextureFormatSupported));
-
- switch (ctx->API) {
- case API_OPENGL:
-#if FEATURE_dlist
- ctx->Save = _mesa_create_save_table();
- if (!ctx->Save) {
- _mesa_release_shared_state(ctx, ctx->Shared);
- free(ctx->Exec);
- return GL_FALSE;
- }
-
- _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt );
-#endif
- break;
- case API_OPENGLES:
- /**
- * GL_OES_texture_cube_map says
- * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
- */
- for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
- struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
- texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
- texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
- texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
- texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
- texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
- texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
- }
- break;
- case API_OPENGLES2:
- ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
- ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
- ctx->Point.PointSprite = GL_TRUE; /* always on for ES 2.x */
- break;
- }
-
- ctx->FirstTimeCurrent = GL_TRUE;
-
- return GL_TRUE;
-}
-
-
-/**
- * Allocate and initialize a struct gl_context structure.
- * Note that the driver needs to pass in its dd_function_table here since
- * we need to at least call driverFunctions->NewTextureObject to initialize
- * the rendering context.
- *
- * \param api the GL API type to create the context for
- * \param visual a struct gl_config pointer (we copy the struct contents)
- * \param share_list another context to share display lists with or NULL
- * \param driverFunctions points to the dd_function_table into which the
- * driver has plugged in all its special functions.
- * \param driverContext points to the device driver's private context state
- *
- * \return pointer to a new __struct gl_contextRec or NULL if error.
- */
-struct gl_context *
-_mesa_create_context(gl_api api,
- const struct gl_config *visual,
- struct gl_context *share_list,
- const struct dd_function_table *driverFunctions,
- void *driverContext)
-{
- struct gl_context *ctx;
-
- ASSERT(visual);
- /*ASSERT(driverContext);*/
-
- ctx = (struct gl_context *) calloc(1, sizeof(struct gl_context));
- if (!ctx)
- return NULL;
-
- if (_mesa_initialize_context(ctx, api, visual, share_list,
- driverFunctions, driverContext)) {
- return ctx;
- }
- else {
- free(ctx);
- return NULL;
- }
-}
-
-
-/**
- * Free the data associated with the given context.
- *
- * But doesn't free the struct gl_context struct itself.
- *
- * \sa _mesa_initialize_context() and init_attrib_groups().
- */
-void
-_mesa_free_context_data( struct gl_context *ctx )
-{
- if (!_mesa_get_current_context()){
- /* No current context, but we may need one in order to delete
- * texture objs, etc. So temporarily bind the context now.
- */
- _mesa_make_current(ctx, NULL, NULL);
- }
-
- /* unreference WinSysDraw/Read buffers */
- _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
- _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
- _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
- _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
-
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
-
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
-
- _mesa_free_attrib_data(ctx);
- _mesa_free_buffer_objects(ctx);
- _mesa_free_lighting_data( ctx );
- _mesa_free_eval_data( ctx );
- _mesa_free_texture_data( ctx );
- _mesa_free_matrix_data( ctx );
- _mesa_free_viewport_data( ctx );
- _mesa_free_program_data(ctx);
- _mesa_free_shader_state(ctx);
- _mesa_free_queryobj_data(ctx);
- _mesa_free_sync_data(ctx);
- _mesa_free_varray_data(ctx);
- _mesa_free_transform_feedback(ctx);
-
- _mesa_delete_array_object(ctx, ctx->Array.DefaultArrayObj);
-
-#if FEATURE_ARB_pixel_buffer_object
- _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
- _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
- _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
-#endif
-
-#if FEATURE_ARB_vertex_buffer_object
- _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
- _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj, NULL);
-#endif
-
- /* free dispatch tables */
- free(ctx->Exec);
- free(ctx->Save);
-
- /* Shared context state (display lists, textures, etc) */
- _mesa_release_shared_state( ctx, ctx->Shared );
-
- /* needs to be after freeing shared state */
- _mesa_free_display_list_data(ctx);
-
- if (ctx->Extensions.String)
- free((void *) ctx->Extensions.String);
-
- if (ctx->VersionString)
- free(ctx->VersionString);
-
- /* unbind the context if it's currently bound */
- if (ctx == _mesa_get_current_context()) {
- _mesa_make_current(NULL, NULL, NULL);
- }
-}
-
-
-/**
- * Destroy a struct gl_context structure.
- *
- * \param ctx GL context.
- *
- * Calls _mesa_free_context_data() and frees the gl_context object itself.
- */
-void
-_mesa_destroy_context( struct gl_context *ctx )
-{
- if (ctx) {
- _mesa_free_context_data(ctx);
- free( (void *) ctx );
- }
-}
-
-
-#if _HAVE_FULL_GL
-/**
- * Copy attribute groups from one context to another.
- *
- * \param src source context
- * \param dst destination context
- * \param mask bitwise OR of GL_*_BIT flags
- *
- * According to the bits specified in \p mask, copies the corresponding
- * attributes from \p src into \p dst. For many of the attributes a simple \c
- * memcpy is not enough due to the existence of internal pointers in their data
- * structures.
- */
-void
-_mesa_copy_context( const struct gl_context *src, struct gl_context *dst, GLuint mask )
-{
- if (mask & GL_ACCUM_BUFFER_BIT) {
- /* OK to memcpy */
- dst->Accum = src->Accum;
- }
- if (mask & GL_COLOR_BUFFER_BIT) {
- /* OK to memcpy */
- dst->Color = src->Color;
- }
- if (mask & GL_CURRENT_BIT) {
- /* OK to memcpy */
- dst->Current = src->Current;
- }
- if (mask & GL_DEPTH_BUFFER_BIT) {
- /* OK to memcpy */
- dst->Depth = src->Depth;
- }
- if (mask & GL_ENABLE_BIT) {
- /* no op */
- }
- if (mask & GL_EVAL_BIT) {
- /* OK to memcpy */
- dst->Eval = src->Eval;
- }
- if (mask & GL_FOG_BIT) {
- /* OK to memcpy */
- dst->Fog = src->Fog;
- }
- if (mask & GL_HINT_BIT) {
- /* OK to memcpy */
- dst->Hint = src->Hint;
- }
- if (mask & GL_LIGHTING_BIT) {
- GLuint i;
- /* begin with memcpy */
- dst->Light = src->Light;
- /* fixup linked lists to prevent pointer insanity */
- make_empty_list( &(dst->Light.EnabledList) );
- for (i = 0; i < MAX_LIGHTS; i++) {
- if (dst->Light.Light[i].Enabled) {
- insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
- }
- }
- }
- if (mask & GL_LINE_BIT) {
- /* OK to memcpy */
- dst->Line = src->Line;
- }
- if (mask & GL_LIST_BIT) {
- /* OK to memcpy */
- dst->List = src->List;
- }
- if (mask & GL_PIXEL_MODE_BIT) {
- /* OK to memcpy */
- dst->Pixel = src->Pixel;
- }
- if (mask & GL_POINT_BIT) {
- /* OK to memcpy */
- dst->Point = src->Point;
- }
- if (mask & GL_POLYGON_BIT) {
- /* OK to memcpy */
- dst->Polygon = src->Polygon;
- }
- if (mask & GL_POLYGON_STIPPLE_BIT) {
- /* Use loop instead of memcpy due to problem with Portland Group's
- * C compiler. Reported by John Stone.
- */
- GLuint i;
- for (i = 0; i < 32; i++) {
- dst->PolygonStipple[i] = src->PolygonStipple[i];
- }
- }
- if (mask & GL_SCISSOR_BIT) {
- /* OK to memcpy */
- dst->Scissor = src->Scissor;
- }
- if (mask & GL_STENCIL_BUFFER_BIT) {
- /* OK to memcpy */
- dst->Stencil = src->Stencil;
- }
- if (mask & GL_TEXTURE_BIT) {
- /* Cannot memcpy because of pointers */
- _mesa_copy_texture_state(src, dst);
- }
- if (mask & GL_TRANSFORM_BIT) {
- /* OK to memcpy */
- dst->Transform = src->Transform;
- }
- if (mask & GL_VIEWPORT_BIT) {
- /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
- dst->Viewport.X = src->Viewport.X;
- dst->Viewport.Y = src->Viewport.Y;
- dst->Viewport.Width = src->Viewport.Width;
- dst->Viewport.Height = src->Viewport.Height;
- dst->Viewport.Near = src->Viewport.Near;
- dst->Viewport.Far = src->Viewport.Far;
- _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
- }
-
- /* XXX FIXME: Call callbacks?
- */
- dst->NewState = _NEW_ALL;
-}
-#endif
-
-
-/**
- * Check if the given context can render into the given framebuffer
- * by checking visual attributes.
- *
- * Most of these tests could go away because Mesa is now pretty flexible
- * in terms of mixing rendering contexts with framebuffers. As long
- * as RGB vs. CI mode agree, we're probably good.
- *
- * \return GL_TRUE if compatible, GL_FALSE otherwise.
- */
-static GLboolean
-check_compatible(const struct gl_context *ctx,
- const struct gl_framebuffer *buffer)
-{
- const struct gl_config *ctxvis = &ctx->Visual;
- const struct gl_config *bufvis = &buffer->Visual;
-
- if (buffer == _mesa_get_incomplete_framebuffer())
- return GL_TRUE;
-
-#if 0
- /* disabling this fixes the fgl_glxgears pbuffer demo */
- if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
- return GL_FALSE;
-#endif
- if (ctxvis->stereoMode && !bufvis->stereoMode)
- return GL_FALSE;
- if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
- return GL_FALSE;
- if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
- return GL_FALSE;
- if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
- return GL_FALSE;
- if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
- return GL_FALSE;
- if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
- return GL_FALSE;
- if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
- return GL_FALSE;
-#if 0
- /* disabled (see bug 11161) */
- if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
- return GL_FALSE;
-#endif
- if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
- return GL_FALSE;
-
- return GL_TRUE;
-}
-
-
-/**
- * Do one-time initialization for the given framebuffer. Specifically,
- * ask the driver for the window's current size and update the framebuffer
- * object to match.
- * Really, the device driver should totally take care of this.
- */
-static void
-initialize_framebuffer_size(struct gl_context *ctx, struct gl_framebuffer *fb)
-{
- GLuint width, height;
- if (ctx->Driver.GetBufferSize) {
- ctx->Driver.GetBufferSize(fb, &width, &height);
- if (ctx->Driver.ResizeBuffers)
- ctx->Driver.ResizeBuffers(ctx, fb, width, height);
- fb->Initialized = GL_TRUE;
- }
-}
-
-
-/**
- * Check if the viewport/scissor size has not yet been initialized.
- * Initialize the size if the given width and height are non-zero.
- */
-void
-_mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
-{
- if (!ctx->ViewportInitialized && width > 0 && height > 0) {
- /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
- * potential infinite recursion.
- */
- ctx->ViewportInitialized = GL_TRUE;
- _mesa_set_viewport(ctx, 0, 0, width, height);
- _mesa_set_scissor(ctx, 0, 0, width, height);
- }
-}
-
-
-/**
- * Bind the given context to the given drawBuffer and readBuffer and
- * make it the current context for the calling thread.
- * We'll render into the drawBuffer and read pixels from the
- * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
- *
- * We check that the context's and framebuffer's visuals are compatible
- * and return immediately if they're not.
- *
- * \param newCtx the new GL context. If NULL then there will be no current GL
- * context.
- * \param drawBuffer the drawing framebuffer
- * \param readBuffer the reading framebuffer
- */
-GLboolean
-_mesa_make_current( struct gl_context *newCtx,
- struct gl_framebuffer *drawBuffer,
- struct gl_framebuffer *readBuffer )
-{
- GET_CURRENT_CONTEXT(curCtx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(newCtx, "_mesa_make_current()\n");
-
- /* Check that the context's and framebuffer's visuals are compatible.
- */
- if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
- if (!check_compatible(newCtx, drawBuffer)) {
- _mesa_warning(newCtx,
- "MakeCurrent: incompatible visuals for context and drawbuffer");
- return GL_FALSE;
- }
- }
- if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
- if (!check_compatible(newCtx, readBuffer)) {
- _mesa_warning(newCtx,
- "MakeCurrent: incompatible visuals for context and readbuffer");
- return GL_FALSE;
- }
- }
-
- if (curCtx &&
- (curCtx->WinSysDrawBuffer || curCtx->WinSysReadBuffer) && /* make sure this context is valid for flushing */
- curCtx != newCtx)
- _mesa_flush(curCtx);
-
- /* We used to call _glapi_check_multithread() here. Now do it in drivers */
- _glapi_set_context((void *) newCtx);
- ASSERT(_mesa_get_current_context() == newCtx);
-
- if (!newCtx) {
- _glapi_set_dispatch(NULL); /* none current */
- }
- else {
- _glapi_set_dispatch(newCtx->CurrentDispatch);
-
- if (drawBuffer && readBuffer) {
- /* TODO: check if newCtx and buffer's visual match??? */
-
- ASSERT(drawBuffer->Name == 0);
- ASSERT(readBuffer->Name == 0);
- _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
- _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
-
- /*
- * Only set the context's Draw/ReadBuffer fields if they're NULL
- * or not bound to a user-created FBO.
- */
- if (!newCtx->DrawBuffer || newCtx->DrawBuffer->Name == 0) {
- /* KW: merge conflict here, revisit.
- */
- /* fix up the fb fields - these will end up wrong otherwise
- * if the DRIdrawable changes, and everything relies on them.
- * This is a bit messy (same as needed in _mesa_BindFramebufferEXT)
- */
- unsigned int i;
- GLenum buffers[MAX_DRAW_BUFFERS];
-
- _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
-
- for(i = 0; i < newCtx->Const.MaxDrawBuffers; i++) {
- buffers[i] = newCtx->Color.DrawBuffer[i];
- }
-
- _mesa_drawbuffers(newCtx, newCtx->Const.MaxDrawBuffers,
- buffers, NULL);
- }
- if (!newCtx->ReadBuffer || newCtx->ReadBuffer->Name == 0) {
- _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
- }
-
- /* XXX only set this flag if we're really changing the draw/read
- * framebuffer bindings.
- */
- newCtx->NewState |= _NEW_BUFFERS;
-
-#if 1
- /* We want to get rid of these lines: */
-
-#if _HAVE_FULL_GL
- if (!drawBuffer->Initialized) {
- initialize_framebuffer_size(newCtx, drawBuffer);
- }
- if (readBuffer != drawBuffer && !readBuffer->Initialized) {
- initialize_framebuffer_size(newCtx, readBuffer);
- }
-
- _mesa_resizebuffers(newCtx);
-#endif
-
-#else
- /* We want the drawBuffer and readBuffer to be initialized by
- * the driver.
- * This generally means the Width and Height match the actual
- * window size and the renderbuffers (both hardware and software
- * based) are allocated to match. The later can generally be
- * done with a call to _mesa_resize_framebuffer().
- *
- * It's theoretically possible for a buffer to have zero width
- * or height, but for now, assert check that the driver did what's
- * expected of it.
- */
- ASSERT(drawBuffer->Width > 0);
- ASSERT(drawBuffer->Height > 0);
-#endif
-
- if (drawBuffer) {
- _mesa_check_init_viewport(newCtx,
- drawBuffer->Width, drawBuffer->Height);
- }
- }
-
- if (newCtx->FirstTimeCurrent) {
- _mesa_compute_version(newCtx);
-
- newCtx->Extensions.String = _mesa_make_extension_string(newCtx);
-
- check_context_limits(newCtx);
-
- /* We can use this to help debug user's problems. Tell them to set
- * the MESA_INFO env variable before running their app. Then the
- * first time each context is made current we'll print some useful
- * information.
- */
- if (_mesa_getenv("MESA_INFO")) {
- _mesa_print_info();
- }
-
- newCtx->FirstTimeCurrent = GL_FALSE;
- }
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Make context 'ctx' share the display lists, textures and programs
- * that are associated with 'ctxToShare'.
- * Any display lists, textures or programs associated with 'ctx' will
- * be deleted if nobody else is sharing them.
- */
-GLboolean
-_mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
-{
- if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
- struct gl_shared_state *oldSharedState = ctx->Shared;
-
- ctx->Shared = ctxToShare->Shared;
-
- _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
- ctx->Shared->RefCount++;
- _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
-
- update_default_objects(ctx);
-
- _mesa_release_shared_state(ctx, oldSharedState);
-
- return GL_TRUE;
- }
- else {
- return GL_FALSE;
- }
-}
-
-
-
-/**
- * \return pointer to the current GL context for this thread.
- *
- * Calls _glapi_get_context(). This isn't the fastest way to get the current
- * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
- * context.h.
- */
-struct gl_context *
-_mesa_get_current_context( void )
-{
- return (struct gl_context *) _glapi_get_context();
-}
-
-
-/**
- * Get context's current API dispatch table.
- *
- * It'll either be the immediate-mode execute dispatcher or the display list
- * compile dispatcher.
- *
- * \param ctx GL context.
- *
- * \return pointer to dispatch_table.
- *
- * Simply returns __struct gl_contextRec::CurrentDispatch.
- */
-struct _glapi_table *
-_mesa_get_dispatch(struct gl_context *ctx)
-{
- return ctx->CurrentDispatch;
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name Miscellaneous functions */
-/**********************************************************************/
-/*@{*/
-
-/**
- * Record an error.
- *
- * \param ctx GL context.
- * \param error error code.
- *
- * Records the given error code and call the driver's dd_function_table::Error
- * function if defined.
- *
- * \sa
- * This is called via _mesa_error().
- */
-void
-_mesa_record_error(struct gl_context *ctx, GLenum error)
-{
- if (!ctx)
- return;
-
- if (ctx->ErrorValue == GL_NO_ERROR) {
- ctx->ErrorValue = error;
- }
-
- /* Call device driver's error handler, if any. This is used on the Mac. */
- if (ctx->Driver.Error) {
- ctx->Driver.Error(ctx);
- }
-}
-
-
-/**
- * Flush commands and wait for completion.
- */
-void
-_mesa_finish(struct gl_context *ctx)
-{
- FLUSH_CURRENT( ctx, 0 );
- if (ctx->Driver.Finish) {
- ctx->Driver.Finish(ctx);
- }
-}
-
-
-/**
- * Flush commands.
- */
-void
-_mesa_flush(struct gl_context *ctx)
-{
- FLUSH_CURRENT( ctx, 0 );
- if (ctx->Driver.Flush) {
- ctx->Driver.Flush(ctx);
- }
-}
-
-
-
-/**
- * Execute glFinish().
- *
- * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
- * dd_function_table::Finish driver callback, if not NULL.
- */
-void GLAPIENTRY
-_mesa_Finish(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
- _mesa_finish(ctx);
-}
-
-
-/**
- * Execute glFlush().
- *
- * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
- * dd_function_table::Flush driver callback, if not NULL.
- */
-void GLAPIENTRY
-_mesa_Flush(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
- _mesa_flush(ctx);
-}
-
-
-/**
- * Set mvp_with_dp4 flag. If a driver has a preference for DP4 over
- * MUL/MAD, or vice versa, call this function to register that.
- * Otherwise we default to MUL/MAD.
- */
-void
-_mesa_set_mvp_with_dp4( struct gl_context *ctx,
- GLboolean flag )
-{
- ctx->mvp_with_dp4 = flag;
-}
-
-
-
-/**
- * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
- * is called to see if it's valid to render. This involves checking that
- * the current shader is valid and the framebuffer is complete.
- * If an error is detected it'll be recorded here.
- * \return GL_TRUE if OK to render, GL_FALSE if not
- */
-GLboolean
-_mesa_valid_to_render(struct gl_context *ctx, const char *where)
-{
- bool vert_from_glsl_shader = false;
- bool geom_from_glsl_shader = false;
- bool frag_from_glsl_shader = false;
-
- /* This depends on having up to date derived state (shaders) */
- if (ctx->NewState)
- _mesa_update_state(ctx);
-
- if (ctx->Shader.CurrentVertexProgram) {
- vert_from_glsl_shader = true;
-
- if (!ctx->Shader.CurrentVertexProgram->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(shader not linked)", where);
- return GL_FALSE;
- }
-#if 0 /* not normally enabled */
- {
- char errMsg[100];
- if (!_mesa_validate_shader_program(ctx,
- ctx->Shader.CurrentVertexProgram,
- errMsg)) {
- _mesa_warning(ctx, "Shader program %u is invalid: %s",
- ctx->Shader.CurrentVertexProgram->Name, errMsg);
- }
- }
-#endif
- }
-
- if (ctx->Shader.CurrentGeometryProgram) {
- geom_from_glsl_shader = true;
-
- if (!ctx->Shader.CurrentGeometryProgram->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(shader not linked)", where);
- return GL_FALSE;
- }
-#if 0 /* not normally enabled */
- {
- char errMsg[100];
- if (!_mesa_validate_shader_program(ctx,
- ctx->Shader.CurrentGeometryProgram,
- errMsg)) {
- _mesa_warning(ctx, "Shader program %u is invalid: %s",
- ctx->Shader.CurrentGeometryProgram->Name, errMsg);
- }
- }
-#endif
- }
-
- if (ctx->Shader.CurrentFragmentProgram) {
- frag_from_glsl_shader = true;
-
- if (!ctx->Shader.CurrentFragmentProgram->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(shader not linked)", where);
- return GL_FALSE;
- }
-#if 0 /* not normally enabled */
- {
- char errMsg[100];
- if (!_mesa_validate_shader_program(ctx,
- ctx->Shader.CurrentFragmentProgram,
- errMsg)) {
- _mesa_warning(ctx, "Shader program %u is invalid: %s",
- ctx->Shader.CurrentFragmentProgram->Name, errMsg);
- }
- }
-#endif
- }
-
- /* Any shader stages that are not supplied by the GLSL shader and have
- * assembly shaders enabled must now be validated.
- */
- if (!vert_from_glsl_shader
- && ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(vertex program not valid)", where);
- return GL_FALSE;
- }
-
- /* FINISHME: If GL_NV_geometry_program4 is ever supported, the current
- * FINISHME: geometry program should validated here.
- */
- (void) geom_from_glsl_shader;
-
- if (!frag_from_glsl_shader) {
- if (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(fragment program not valid)", where);
- return GL_FALSE;
- }
-
- /* If drawing to integer-valued color buffers, there must be an
- * active fragment shader (GL_EXT_texture_integer).
- */
- if (ctx->DrawBuffer && ctx->DrawBuffer->_IntegerColor) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(integer format but no fragment shader)", where);
- return GL_FALSE;
- }
- }
-
- if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
- _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
- "%s(incomplete framebuffer)", where);
- return GL_FALSE;
- }
-
-#ifdef DEBUG
- if (ctx->Shader.Flags & GLSL_LOG) {
- struct gl_shader_program *shProg[MESA_SHADER_TYPES];
- gl_shader_type i;
-
- shProg[MESA_SHADER_VERTEX] = ctx->Shader.CurrentVertexProgram;
- shProg[MESA_SHADER_GEOMETRY] = ctx->Shader.CurrentGeometryProgram;
- shProg[MESA_SHADER_FRAGMENT] = ctx->Shader.CurrentFragmentProgram;
-
- for (i = 0; i < MESA_SHADER_TYPES; i++) {
- struct gl_shader *sh;
-
- if (shProg[i] == NULL || shProg[i]->_Used
- || shProg[i]->_LinkedShaders[i] == NULL)
- continue;
-
- /* This is the first time this shader is being used.
- * Append shader's constants/uniforms to log file.
- *
- * The logic is a little odd here. We only want to log data for each
- * shader target that will actually be used, and we only want to log
- * it once. It's possible to have a program bound to the vertex
- * shader target that also supplied a fragment shader. If that
- * program isn't also bound to the fragment shader target we don't
- * want to log its fragment data.
- */
- sh = shProg[i]->_LinkedShaders[i];
- switch (sh->Type) {
- case GL_VERTEX_SHADER:
- _mesa_append_uniforms_to_file(sh, &shProg[i]->VertexProgram->Base);
- break;
-
- case GL_GEOMETRY_SHADER_ARB:
- _mesa_append_uniforms_to_file(sh,
- &shProg[i]->GeometryProgram->Base);
- break;
-
- case GL_FRAGMENT_SHADER:
- _mesa_append_uniforms_to_file(sh,
- &shProg[i]->FragmentProgram->Base);
- break;
- }
- }
-
- for (i = 0; i < MESA_SHADER_TYPES; i++) {
- if (shProg[i] != NULL)
- shProg[i]->_Used = GL_TRUE;
- }
- }
-#endif
-
- return GL_TRUE;
-}
-
-
-/*@}*/
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.3
+ *
+ * Copyright (C) 1999-2007 Brian Paul All Rights Reserved.
+ * Copyright (C) 2008 VMware, Inc. 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 context.c
+ * Mesa context/visual/framebuffer management functions.
+ * \author Brian Paul
+ */
+
+/**
+ * \mainpage Mesa Main Module
+ *
+ * \section MainIntroduction Introduction
+ *
+ * The Mesa Main module consists of all the files in the main/ directory.
+ * Among the features of this module are:
+ * <UL>
+ * <LI> Structures to represent most GL state </LI>
+ * <LI> State set/get functions </LI>
+ * <LI> Display lists </LI>
+ * <LI> Texture unit, object and image handling </LI>
+ * <LI> Matrix and attribute stacks </LI>
+ * </UL>
+ *
+ * Other modules are responsible for API dispatch, vertex transformation,
+ * point/line/triangle setup, rasterization, vertex array caching,
+ * vertex/fragment programs/shaders, etc.
+ *
+ *
+ * \section AboutDoxygen About Doxygen
+ *
+ * If you're viewing this information as Doxygen-generated HTML you'll
+ * see the documentation index at the top of this page.
+ *
+ * The first line lists the Mesa source code modules.
+ * The second line lists the indexes available for viewing the documentation
+ * for each module.
+ *
+ * Selecting the <b>Main page</b> link will display a summary of the module
+ * (this page).
+ *
+ * Selecting <b>Data Structures</b> will list all C structures.
+ *
+ * Selecting the <b>File List</b> link will list all the source files in
+ * the module.
+ * Selecting a filename will show a list of all functions defined in that file.
+ *
+ * Selecting the <b>Data Fields</b> link will display a list of all
+ * documented structure members.
+ *
+ * Selecting the <b>Globals</b> link will display a list
+ * of all functions, structures, global variables and macros in the module.
+ *
+ */
+
+
+#include "glheader.h"
+#include "mfeatures.h"
+#include "imports.h"
+#include "accum.h"
+#include "api_exec.h"
+#include "arrayobj.h"
+#include "attrib.h"
+#include "blend.h"
+#include "buffers.h"
+#include "bufferobj.h"
+#include "context.h"
+#include "cpuinfo.h"
+#include "debug.h"
+#include "depth.h"
+#include "dlist.h"
+#include "eval.h"
+#include "extensions.h"
+#include "fbobject.h"
+#include "feedback.h"
+#include "fog.h"
+#include "formats.h"
+#include "framebuffer.h"
+#include "hint.h"
+#include "hash.h"
+#include "light.h"
+#include "lines.h"
+#include "macros.h"
+#include "matrix.h"
+#include "multisample.h"
+#include "pixel.h"
+#include "pixelstore.h"
+#include "points.h"
+#include "polygon.h"
+#include "queryobj.h"
+#include "syncobj.h"
+#include "rastpos.h"
+#include "remap.h"
+#include "scissor.h"
+#include "shared.h"
+#include "shaderobj.h"
+#include "simple_list.h"
+#include "state.h"
+#include "stencil.h"
+#include "texcompress_s3tc.h"
+#include "texstate.h"
+#include "transformfeedback.h"
+#include "mtypes.h"
+#include "varray.h"
+#include "version.h"
+#include "viewport.h"
+#include "vtxfmt.h"
+#include "program/program.h"
+#include "program/prog_print.h"
+#if _HAVE_FULL_GL
+#include "math/m_matrix.h"
+#endif
+#include "main/dispatch.h" /* for _gloffset_COUNT */
+
+#ifdef USE_SPARC_ASM
+#include "sparc/sparc.h"
+#endif
+
+#include "glsl_parser_extras.h"
+#include <stdbool.h>
+
+
+#ifndef MESA_VERBOSE
+int MESA_VERBOSE = 0;
+#endif
+
+#ifndef MESA_DEBUG_FLAGS
+int MESA_DEBUG_FLAGS = 0;
+#endif
+
+
+/* ubyte -> float conversion */
+GLfloat _mesa_ubyte_to_float_color_tab[256];
+
+
+
+/**
+ * Swap buffers notification callback.
+ *
+ * \param ctx GL context.
+ *
+ * Called by window system just before swapping buffers.
+ * We have to finish any pending rendering.
+ */
+void
+_mesa_notifySwapBuffers(struct gl_context *ctx)
+{
+ if (MESA_VERBOSE & VERBOSE_SWAPBUFFERS)
+ _mesa_debug(ctx, "SwapBuffers\n");
+ FLUSH_CURRENT( ctx, 0 );
+ if (ctx->Driver.Flush) {
+ ctx->Driver.Flush(ctx);
+ }
+}
+
+
+/**********************************************************************/
+/** \name GL Visual allocation/destruction */
+/**********************************************************************/
+/*@{*/
+
+/**
+ * Allocates a struct gl_config structure and initializes it via
+ * _mesa_initialize_visual().
+ *
+ * \param dbFlag double buffering
+ * \param stereoFlag stereo buffer
+ * \param depthBits requested bits per depth buffer value. Any value in [0, 32]
+ * is acceptable but the actual depth type will be GLushort or GLuint as
+ * needed.
+ * \param stencilBits requested minimum bits per stencil buffer value
+ * \param accumRedBits, accumGreenBits, accumBlueBits, accumAlphaBits number of bits per color component in accum buffer.
+ * \param indexBits number of bits per pixel if \p rgbFlag is GL_FALSE
+ * \param redBits number of bits per color component in frame buffer for RGB(A)
+ * mode. We always use 8 in core Mesa though.
+ * \param greenBits same as above.
+ * \param blueBits same as above.
+ * \param alphaBits same as above.
+ * \param numSamples not really used.
+ *
+ * \return pointer to new struct gl_config or NULL if requested parameters can't be
+ * met.
+ *
+ * \note Need to add params for level and numAuxBuffers (at least)
+ */
+struct gl_config *
+_mesa_create_visual( GLboolean dbFlag,
+ GLboolean stereoFlag,
+ GLint redBits,
+ GLint greenBits,
+ GLint blueBits,
+ GLint alphaBits,
+ GLint depthBits,
+ GLint stencilBits,
+ GLint accumRedBits,
+ GLint accumGreenBits,
+ GLint accumBlueBits,
+ GLint accumAlphaBits,
+ GLint numSamples )
+{
+ struct gl_config *vis = CALLOC_STRUCT(gl_config);
+ if (vis) {
+ if (!_mesa_initialize_visual(vis, dbFlag, stereoFlag,
+ redBits, greenBits, blueBits, alphaBits,
+ depthBits, stencilBits,
+ accumRedBits, accumGreenBits,
+ accumBlueBits, accumAlphaBits,
+ numSamples)) {
+ free(vis);
+ return NULL;
+ }
+ }
+ return vis;
+}
+
+
+/**
+ * Makes some sanity checks and fills in the fields of the struct
+ * gl_config object with the given parameters. If the caller needs to
+ * set additional fields, he should just probably init the whole
+ * gl_config object himself.
+ *
+ * \return GL_TRUE on success, or GL_FALSE on failure.
+ *
+ * \sa _mesa_create_visual() above for the parameter description.
+ */
+GLboolean
+_mesa_initialize_visual( struct gl_config *vis,
+ GLboolean dbFlag,
+ GLboolean stereoFlag,
+ GLint redBits,
+ GLint greenBits,
+ GLint blueBits,
+ GLint alphaBits,
+ GLint depthBits,
+ GLint stencilBits,
+ GLint accumRedBits,
+ GLint accumGreenBits,
+ GLint accumBlueBits,
+ GLint accumAlphaBits,
+ GLint numSamples )
+{
+ assert(vis);
+
+ if (depthBits < 0 || depthBits > 32) {
+ return GL_FALSE;
+ }
+ if (stencilBits < 0 || stencilBits > STENCIL_BITS) {
+ return GL_FALSE;
+ }
+ assert(accumRedBits >= 0);
+ assert(accumGreenBits >= 0);
+ assert(accumBlueBits >= 0);
+ assert(accumAlphaBits >= 0);
+
+ vis->rgbMode = GL_TRUE;
+ vis->doubleBufferMode = dbFlag;
+ vis->stereoMode = stereoFlag;
+
+ vis->redBits = redBits;
+ vis->greenBits = greenBits;
+ vis->blueBits = blueBits;
+ vis->alphaBits = alphaBits;
+ vis->rgbBits = redBits + greenBits + blueBits;
+
+ vis->indexBits = 0;
+ vis->depthBits = depthBits;
+ vis->stencilBits = stencilBits;
+
+ vis->accumRedBits = accumRedBits;
+ vis->accumGreenBits = accumGreenBits;
+ vis->accumBlueBits = accumBlueBits;
+ vis->accumAlphaBits = accumAlphaBits;
+
+ vis->haveAccumBuffer = accumRedBits > 0;
+ vis->haveDepthBuffer = depthBits > 0;
+ vis->haveStencilBuffer = stencilBits > 0;
+
+ vis->numAuxBuffers = 0;
+ vis->level = 0;
+ vis->sampleBuffers = numSamples > 0 ? 1 : 0;
+ vis->samples = numSamples;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Destroy a visual and free its memory.
+ *
+ * \param vis visual.
+ *
+ * Frees the visual structure.
+ */
+void
+_mesa_destroy_visual( struct gl_config *vis )
+{
+ free(vis);
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name Context allocation, initialization, destroying
+ *
+ * The purpose of the most initialization functions here is to provide the
+ * default state values according to the OpenGL specification.
+ */
+/**********************************************************************/
+/*@{*/
+
+
+/**
+ * This is lame. gdb only seems to recognize enum types that are
+ * actually used somewhere. We want to be able to print/use enum
+ * values such as TEXTURE_2D_INDEX in gdb. But we don't actually use
+ * the gl_texture_index type anywhere. Thus, this lame function.
+ */
+static void
+dummy_enum_func(void)
+{
+ gl_buffer_index bi = BUFFER_FRONT_LEFT;
+ gl_face_index fi = FACE_POS_X;
+ gl_frag_attrib fa = FRAG_ATTRIB_WPOS;
+ gl_frag_result fr = FRAG_RESULT_DEPTH;
+ gl_texture_index ti = TEXTURE_2D_ARRAY_INDEX;
+ gl_vert_attrib va = VERT_ATTRIB_POS;
+ gl_vert_result vr = VERT_RESULT_HPOS;
+ gl_geom_attrib ga = GEOM_ATTRIB_POSITION;
+ gl_geom_result gr = GEOM_RESULT_POS;
+
+ (void) bi;
+ (void) fi;
+ (void) fa;
+ (void) fr;
+ (void) ti;
+ (void) va;
+ (void) vr;
+ (void) ga;
+ (void) gr;
+}
+
+
+/**
+ * One-time initialization mutex lock.
+ *
+ * \sa Used by one_time_init().
+ */
+_glthread_DECLARE_STATIC_MUTEX(OneTimeLock);
+
+
+
+/**
+ * Calls all the various one-time-init functions in Mesa.
+ *
+ * While holding a global mutex lock, calls several initialization functions,
+ * and sets the glapi callbacks if the \c MESA_DEBUG environment variable is
+ * defined.
+ *
+ * \sa _math_init().
+ */
+static void
+one_time_init( struct gl_context *ctx )
+{
+ static GLbitfield api_init_mask = 0x0;
+
+ _glthread_LOCK_MUTEX(OneTimeLock);
+
+ /* truly one-time init */
+ if (!api_init_mask) {
+ GLuint i;
+
+ /* do some implementation tests */
+ assert( sizeof(GLbyte) == 1 );
+ assert( sizeof(GLubyte) == 1 );
+ assert( sizeof(GLshort) == 2 );
+ assert( sizeof(GLushort) == 2 );
+ assert( sizeof(GLint) == 4 );
+ assert( sizeof(GLuint) == 4 );
+
+ _mesa_get_cpu_features();
+
+ _mesa_init_sqrt_table();
+
+ /* context dependence is never a one-time thing... */
+ _mesa_init_get_hash(ctx);
+
+ for (i = 0; i < 256; i++) {
+ _mesa_ubyte_to_float_color_tab[i] = (float) i / 255.0F;
+ }
+
+#if defined(DEBUG) && defined(__DATE__) && defined(__TIME__)
+ if (MESA_VERBOSE != 0) {
+ _mesa_debug(ctx, "Mesa %s DEBUG build %s %s\n",
+ MESA_VERSION_STRING, __DATE__, __TIME__);
+ }
+#endif
+
+#ifdef DEBUG
+ _mesa_test_formats();
+#endif
+ }
+
+ /* per-API one-time init */
+ if (!(api_init_mask & (1 << ctx->API))) {
+ /*
+ * This is fine as ES does not use the remap table, but it may not be
+ * future-proof. We cannot always initialize the remap table because
+ * when an app is linked to libGLES*, there are not enough dynamic
+ * entries.
+ */
+ if (ctx->API == API_OPENGL)
+ _mesa_init_remap_table();
+ }
+
+ api_init_mask |= 1 << ctx->API;
+
+ _glthread_UNLOCK_MUTEX(OneTimeLock);
+
+ /* Hopefully atexit() is widely available. If not, we may need some
+ * #ifdef tests here.
+ */
+ atexit(_mesa_destroy_shader_compiler);
+
+ dummy_enum_func();
+}
+
+
+/**
+ * Initialize fields of gl_current_attrib (aka ctx->Current.*)
+ */
+static void
+_mesa_init_current(struct gl_context *ctx)
+{
+ GLuint i;
+
+ /* Init all to (0,0,0,1) */
+ for (i = 0; i < Elements(ctx->Current.Attrib); i++) {
+ ASSIGN_4V( ctx->Current.Attrib[i], 0.0, 0.0, 0.0, 1.0 );
+ }
+
+ /* redo special cases: */
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_WEIGHT], 1.0, 0.0, 0.0, 0.0 );
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_NORMAL], 0.0, 0.0, 1.0, 1.0 );
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR0], 1.0, 1.0, 1.0, 1.0 );
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR1], 0.0, 0.0, 0.0, 1.0 );
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_COLOR_INDEX], 1.0, 0.0, 0.0, 1.0 );
+ ASSIGN_4V( ctx->Current.Attrib[VERT_ATTRIB_EDGEFLAG], 1.0, 0.0, 0.0, 1.0 );
+}
+
+
+/**
+ * Init vertex/fragment/geometry program limits.
+ * Important: drivers should override these with actual limits.
+ */
+static void
+init_program_limits(GLenum type, struct gl_program_constants *prog)
+{
+ prog->MaxInstructions = MAX_PROGRAM_INSTRUCTIONS;
+ prog->MaxAluInstructions = MAX_PROGRAM_INSTRUCTIONS;
+ prog->MaxTexInstructions = MAX_PROGRAM_INSTRUCTIONS;
+ prog->MaxTexIndirections = MAX_PROGRAM_INSTRUCTIONS;
+ prog->MaxTemps = MAX_PROGRAM_TEMPS;
+ prog->MaxEnvParams = MAX_PROGRAM_ENV_PARAMS;
+ prog->MaxLocalParams = MAX_PROGRAM_LOCAL_PARAMS;
+ prog->MaxUniformComponents = 4 * MAX_UNIFORMS;
+
+ switch (type) {
+ case GL_VERTEX_PROGRAM_ARB:
+ prog->MaxParameters = MAX_VERTEX_PROGRAM_PARAMS;
+ prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
+ prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
+ break;
+ case GL_FRAGMENT_PROGRAM_ARB:
+ prog->MaxParameters = MAX_NV_FRAGMENT_PROGRAM_PARAMS;
+ prog->MaxAttribs = MAX_NV_FRAGMENT_PROGRAM_INPUTS;
+ prog->MaxAddressRegs = MAX_FRAGMENT_PROGRAM_ADDRESS_REGS;
+ break;
+ case MESA_GEOMETRY_PROGRAM:
+ prog->MaxParameters = MAX_NV_VERTEX_PROGRAM_PARAMS;
+ prog->MaxAttribs = MAX_NV_VERTEX_PROGRAM_INPUTS;
+ prog->MaxAddressRegs = MAX_VERTEX_PROGRAM_ADDRESS_REGS;
+
+ prog->MaxGeometryTextureImageUnits = MAX_GEOMETRY_TEXTURE_IMAGE_UNITS;
+ prog->MaxGeometryVaryingComponents = MAX_GEOMETRY_VARYING_COMPONENTS;
+ prog->MaxVertexVaryingComponents = MAX_VERTEX_VARYING_COMPONENTS;
+ prog->MaxGeometryUniformComponents = MAX_GEOMETRY_UNIFORM_COMPONENTS;
+ prog->MaxGeometryOutputVertices = MAX_GEOMETRY_OUTPUT_VERTICES;
+ prog->MaxGeometryTotalOutputComponents = MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS;
+ break;
+ default:
+ assert(0 && "Bad program type in init_program_limits()");
+ }
+
+ /* Set the native limits to zero. This implies that there is no native
+ * support for shaders. Let the drivers fill in the actual values.
+ */
+ prog->MaxNativeInstructions = 0;
+ prog->MaxNativeAluInstructions = 0;
+ prog->MaxNativeTexInstructions = 0;
+ prog->MaxNativeTexIndirections = 0;
+ prog->MaxNativeAttribs = 0;
+ prog->MaxNativeTemps = 0;
+ prog->MaxNativeAddressRegs = 0;
+ prog->MaxNativeParameters = 0;
+
+ /* Set GLSL datatype range/precision info assuming IEEE float values.
+ * Drivers should override these defaults as needed.
+ */
+ prog->MediumFloat.RangeMin = 127;
+ prog->MediumFloat.RangeMax = 127;
+ prog->MediumFloat.Precision = 23;
+ prog->LowFloat = prog->HighFloat = prog->MediumFloat;
+
+ /* Assume ints are stored as floats for now, since this is the least-common
+ * denominator. The OpenGL ES spec implies (page 132) that the precision
+ * of integer types should be 0. Practically speaking, IEEE
+ * single-precision floating point values can only store integers in the
+ * range [-0x01000000, 0x01000000] without loss of precision.
+ */
+ prog->MediumInt.RangeMin = 24;
+ prog->MediumInt.RangeMax = 24;
+ prog->MediumInt.Precision = 0;
+ prog->LowInt = prog->HighInt = prog->MediumInt;
+}
+
+
+/**
+ * Initialize fields of gl_constants (aka ctx->Const.*).
+ * Use defaults from config.h. The device drivers will often override
+ * some of these values (such as number of texture units).
+ */
+static void
+_mesa_init_constants(struct gl_context *ctx)
+{
+ assert(ctx);
+
+ /* Constants, may be overriden (usually only reduced) by device drivers */
+ ctx->Const.MaxTextureMbytes = MAX_TEXTURE_MBYTES;
+ ctx->Const.MaxTextureLevels = MAX_TEXTURE_LEVELS;
+ ctx->Const.Max3DTextureLevels = MAX_3D_TEXTURE_LEVELS;
+ ctx->Const.MaxCubeTextureLevels = MAX_CUBE_TEXTURE_LEVELS;
+ ctx->Const.MaxTextureRectSize = MAX_TEXTURE_RECT_SIZE;
+ ctx->Const.MaxArrayTextureLayers = MAX_ARRAY_TEXTURE_LAYERS;
+ ctx->Const.MaxTextureCoordUnits = MAX_TEXTURE_COORD_UNITS;
+ ctx->Const.MaxTextureImageUnits = MAX_TEXTURE_IMAGE_UNITS;
+ ctx->Const.MaxTextureUnits = MIN2(ctx->Const.MaxTextureCoordUnits,
+ ctx->Const.MaxTextureImageUnits);
+ ctx->Const.MaxTextureMaxAnisotropy = MAX_TEXTURE_MAX_ANISOTROPY;
+ ctx->Const.MaxTextureLodBias = MAX_TEXTURE_LOD_BIAS;
+ ctx->Const.MaxArrayLockSize = MAX_ARRAY_LOCK_SIZE;
+ ctx->Const.SubPixelBits = SUB_PIXEL_BITS;
+ ctx->Const.MinPointSize = MIN_POINT_SIZE;
+ ctx->Const.MaxPointSize = MAX_POINT_SIZE;
+ ctx->Const.MinPointSizeAA = MIN_POINT_SIZE;
+ ctx->Const.MaxPointSizeAA = MAX_POINT_SIZE;
+ ctx->Const.PointSizeGranularity = (GLfloat) POINT_SIZE_GRANULARITY;
+ ctx->Const.MinLineWidth = MIN_LINE_WIDTH;
+ ctx->Const.MaxLineWidth = MAX_LINE_WIDTH;
+ ctx->Const.MinLineWidthAA = MIN_LINE_WIDTH;
+ ctx->Const.MaxLineWidthAA = MAX_LINE_WIDTH;
+ ctx->Const.LineWidthGranularity = (GLfloat) LINE_WIDTH_GRANULARITY;
+ ctx->Const.MaxColorTableSize = MAX_COLOR_TABLE_SIZE;
+ ctx->Const.MaxClipPlanes = MAX_CLIP_PLANES;
+ ctx->Const.MaxLights = MAX_LIGHTS;
+ ctx->Const.MaxShininess = 128.0;
+ ctx->Const.MaxSpotExponent = 128.0;
+ ctx->Const.MaxViewportWidth = MAX_WIDTH;
+ ctx->Const.MaxViewportHeight = MAX_HEIGHT;
+#if FEATURE_ARB_vertex_program
+ init_program_limits(GL_VERTEX_PROGRAM_ARB, &ctx->Const.VertexProgram);
+#endif
+#if FEATURE_ARB_fragment_program
+ init_program_limits(GL_FRAGMENT_PROGRAM_ARB, &ctx->Const.FragmentProgram);
+#endif
+#if FEATURE_ARB_geometry_shader4
+ init_program_limits(MESA_GEOMETRY_PROGRAM, &ctx->Const.GeometryProgram);
+#endif
+ ctx->Const.MaxProgramMatrices = MAX_PROGRAM_MATRICES;
+ ctx->Const.MaxProgramMatrixStackDepth = MAX_PROGRAM_MATRIX_STACK_DEPTH;
+
+ /* CheckArrayBounds is overriden by drivers/x11 for X server */
+ ctx->Const.CheckArrayBounds = GL_FALSE;
+
+ /* GL_ARB_draw_buffers */
+ ctx->Const.MaxDrawBuffers = MAX_DRAW_BUFFERS;
+
+#if FEATURE_EXT_framebuffer_object
+ ctx->Const.MaxColorAttachments = MAX_COLOR_ATTACHMENTS;
+ ctx->Const.MaxRenderbufferSize = MAX_WIDTH;
+#endif
+
+#if FEATURE_ARB_vertex_shader
+ ctx->Const.MaxVertexTextureImageUnits = MAX_VERTEX_TEXTURE_IMAGE_UNITS;
+ ctx->Const.MaxCombinedTextureImageUnits = MAX_COMBINED_TEXTURE_IMAGE_UNITS;
+ ctx->Const.MaxVarying = MAX_VARYING;
+#endif
+
+ /* Shading language version */
+ if (ctx->API == API_OPENGL) {
+ ctx->Const.GLSLVersion = 120;
+ }
+ else if (ctx->API == API_OPENGLES2) {
+ ctx->Const.GLSLVersion = 100;
+ }
+ else if (ctx->API == API_OPENGLES) {
+ ctx->Const.GLSLVersion = 0; /* GLSL not supported */
+ }
+
+ /* GL_ARB_framebuffer_object */
+ ctx->Const.MaxSamples = 0;
+
+ /* GL_ARB_sync */
+ ctx->Const.MaxServerWaitTimeout = (GLuint64) ~0;
+
+ /* GL_ATI_envmap_bumpmap */
+ ctx->Const.SupportedBumpUnits = SUPPORTED_ATI_BUMP_UNITS;
+
+ /* GL_EXT_provoking_vertex */
+ ctx->Const.QuadsFollowProvokingVertexConvention = GL_TRUE;
+
+ /* GL_EXT_transform_feedback */
+ ctx->Const.MaxTransformFeedbackSeparateAttribs = MAX_FEEDBACK_ATTRIBS;
+ ctx->Const.MaxTransformFeedbackSeparateComponents = 4 * MAX_FEEDBACK_ATTRIBS;
+ ctx->Const.MaxTransformFeedbackInterleavedComponents = 4 * MAX_FEEDBACK_ATTRIBS;
+
+ /* GL 3.2: hard-coded for now: */
+ ctx->Const.ProfileMask = GL_CONTEXT_COMPATIBILITY_PROFILE_BIT;
+
+ /** GL_EXT_gpu_shader4 */
+ ctx->Const.MinProgramTexelOffset = -8;
+ ctx->Const.MaxProgramTexelOffset = 7;
+}
+
+
+/**
+ * Do some sanity checks on the limits/constants for the given context.
+ * Only called the first time a context is bound.
+ */
+static void
+check_context_limits(struct gl_context *ctx)
+{
+ /* check that we don't exceed the size of various bitfields */
+ assert(VERT_RESULT_MAX <=
+ (8 * sizeof(ctx->VertexProgram._Current->Base.OutputsWritten)));
+ assert(FRAG_ATTRIB_MAX <=
+ (8 * sizeof(ctx->FragmentProgram._Current->Base.InputsRead)));
+
+ assert(MAX_COMBINED_TEXTURE_IMAGE_UNITS <= 8 * sizeof(GLbitfield));
+
+ /* shader-related checks */
+ assert(ctx->Const.FragmentProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
+ assert(ctx->Const.VertexProgram.MaxLocalParams <= MAX_PROGRAM_LOCAL_PARAMS);
+
+ assert(MAX_NV_FRAGMENT_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
+ assert(MAX_NV_VERTEX_PROGRAM_TEMPS <= MAX_PROGRAM_TEMPS);
+ assert(MAX_NV_VERTEX_PROGRAM_INPUTS <= VERT_ATTRIB_MAX);
+ assert(MAX_NV_VERTEX_PROGRAM_OUTPUTS <= VERT_RESULT_MAX);
+
+ /* Texture unit checks */
+ assert(ctx->Const.MaxTextureImageUnits > 0);
+ assert(ctx->Const.MaxTextureImageUnits <= MAX_TEXTURE_IMAGE_UNITS);
+ assert(ctx->Const.MaxTextureCoordUnits > 0);
+ assert(ctx->Const.MaxTextureCoordUnits <= MAX_TEXTURE_COORD_UNITS);
+ assert(ctx->Const.MaxTextureUnits > 0);
+ assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_IMAGE_UNITS);
+ assert(ctx->Const.MaxTextureUnits <= MAX_TEXTURE_COORD_UNITS);
+ assert(ctx->Const.MaxTextureUnits == MIN2(ctx->Const.MaxTextureImageUnits,
+ ctx->Const.MaxTextureCoordUnits));
+ assert(ctx->Const.MaxCombinedTextureImageUnits > 0);
+ assert(ctx->Const.MaxCombinedTextureImageUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
+ assert(ctx->Const.MaxTextureCoordUnits <= MAX_COMBINED_TEXTURE_IMAGE_UNITS);
+ /* number of coord units cannot be greater than number of image units */
+ assert(ctx->Const.MaxTextureCoordUnits <= ctx->Const.MaxTextureImageUnits);
+
+
+ /* Texture size checks */
+ assert(ctx->Const.MaxTextureLevels <= MAX_TEXTURE_LEVELS);
+ assert(ctx->Const.Max3DTextureLevels <= MAX_3D_TEXTURE_LEVELS);
+ assert(ctx->Const.MaxCubeTextureLevels <= MAX_CUBE_TEXTURE_LEVELS);
+ assert(ctx->Const.MaxTextureRectSize <= MAX_TEXTURE_RECT_SIZE);
+
+ /* make sure largest texture image is <= MAX_WIDTH in size */
+ assert((1 << (ctx->Const.MaxTextureLevels - 1)) <= MAX_WIDTH);
+ assert((1 << (ctx->Const.MaxCubeTextureLevels - 1)) <= MAX_WIDTH);
+ assert((1 << (ctx->Const.Max3DTextureLevels - 1)) <= MAX_WIDTH);
+
+ /* Texture level checks */
+ assert(MAX_TEXTURE_LEVELS >= MAX_3D_TEXTURE_LEVELS);
+ assert(MAX_TEXTURE_LEVELS >= MAX_CUBE_TEXTURE_LEVELS);
+
+ /* Max texture size should be <= max viewport size (render to texture) */
+ assert((1 << (MAX_TEXTURE_LEVELS - 1)) <= MAX_WIDTH);
+
+ assert(ctx->Const.MaxViewportWidth <= MAX_WIDTH);
+ assert(ctx->Const.MaxViewportHeight <= MAX_WIDTH);
+
+ assert(ctx->Const.MaxDrawBuffers <= MAX_DRAW_BUFFERS);
+
+ /* if this fails, add more enum values to gl_buffer_index */
+ assert(BUFFER_COLOR0 + MAX_DRAW_BUFFERS <= BUFFER_COUNT);
+
+ /* XXX probably add more tests */
+}
+
+
+/**
+ * Initialize the attribute groups in a GL context.
+ *
+ * \param ctx GL context.
+ *
+ * Initializes all the attributes, calling the respective <tt>init*</tt>
+ * functions for the more complex data structures.
+ */
+static GLboolean
+init_attrib_groups(struct gl_context *ctx)
+{
+ assert(ctx);
+
+ /* Constants */
+ _mesa_init_constants( ctx );
+
+ /* Extensions */
+ _mesa_init_extensions( ctx );
+
+ /* Attribute Groups */
+ _mesa_init_accum( ctx );
+ _mesa_init_attrib( ctx );
+ _mesa_init_buffer_objects( ctx );
+ _mesa_init_color( ctx );
+ _mesa_init_current( ctx );
+ _mesa_init_depth( ctx );
+ _mesa_init_debug( ctx );
+ _mesa_init_display_list( ctx );
+ _mesa_init_eval( ctx );
+ _mesa_init_fbobjects( ctx );
+ _mesa_init_feedback( ctx );
+ _mesa_init_fog( ctx );
+ _mesa_init_hint( ctx );
+ _mesa_init_line( ctx );
+ _mesa_init_lighting( ctx );
+ _mesa_init_matrix( ctx );
+ _mesa_init_multisample( ctx );
+ _mesa_init_pixel( ctx );
+ _mesa_init_pixelstore( ctx );
+ _mesa_init_point( ctx );
+ _mesa_init_polygon( ctx );
+ _mesa_init_program( ctx );
+ _mesa_init_queryobj( ctx );
+ _mesa_init_sync( ctx );
+ _mesa_init_rastpos( ctx );
+ _mesa_init_scissor( ctx );
+ _mesa_init_shader_state( ctx );
+ _mesa_init_stencil( ctx );
+ _mesa_init_transform( ctx );
+ _mesa_init_transform_feedback( ctx );
+ _mesa_init_varray( ctx );
+ _mesa_init_viewport( ctx );
+
+ if (!_mesa_init_texture( ctx ))
+ return GL_FALSE;
+
+ _mesa_init_texture_s3tc( ctx );
+
+ /* Miscellaneous */
+ ctx->NewState = _NEW_ALL;
+ ctx->ErrorValue = (GLenum) GL_NO_ERROR;
+ ctx->varying_vp_inputs = ~0;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Update default objects in a GL context with respect to shared state.
+ *
+ * \param ctx GL context.
+ *
+ * Removes references to old default objects, (texture objects, program
+ * objects, etc.) and changes to reference those from the current shared
+ * state.
+ */
+static GLboolean
+update_default_objects(struct gl_context *ctx)
+{
+ assert(ctx);
+
+ _mesa_update_default_objects_program(ctx);
+ _mesa_update_default_objects_texture(ctx);
+ _mesa_update_default_objects_buffer_objects(ctx);
+
+ return GL_TRUE;
+}
+
+
+/**
+ * This is the default function we plug into all dispatch table slots
+ * This helps prevents a segfault when someone calls a GL function without
+ * first checking if the extension's supported.
+ */
+static int
+generic_nop(void)
+{
+ _mesa_warning(NULL, "User called no-op dispatch function (an unsupported extension function?)");
+ return 0;
+}
+
+
+/**
+ * Allocate and initialize a new dispatch table.
+ */
+struct _glapi_table *
+_mesa_alloc_dispatch_table(int size)
+{
+ /* Find the larger of Mesa's dispatch table and libGL's dispatch table.
+ * In practice, this'll be the same for stand-alone Mesa. But for DRI
+ * Mesa we do this to accomodate different versions of libGL and various
+ * DRI drivers.
+ */
+ GLint numEntries = MAX2(_glapi_get_dispatch_table_size(), _gloffset_COUNT);
+ struct _glapi_table *table;
+
+ /* should never happen, but just in case */
+ numEntries = MAX2(numEntries, size);
+
+ table = (struct _glapi_table *) malloc(numEntries * sizeof(_glapi_proc));
+ if (table) {
+ _glapi_proc *entry = (_glapi_proc *) table;
+ GLint i;
+ for (i = 0; i < numEntries; i++) {
+ entry[i] = (_glapi_proc) generic_nop;
+ }
+ }
+ return table;
+}
+
+
+/**
+ * Initialize a struct gl_context struct (rendering context).
+ *
+ * This includes allocating all the other structs and arrays which hang off of
+ * the context by pointers.
+ * Note that the driver needs to pass in its dd_function_table here since
+ * we need to at least call driverFunctions->NewTextureObject to create the
+ * default texture objects.
+ *
+ * Called by _mesa_create_context().
+ *
+ * Performs the imports and exports callback tables initialization, and
+ * miscellaneous one-time initializations. If no shared context is supplied one
+ * is allocated, and increase its reference count. Setups the GL API dispatch
+ * tables. Initialize the TNL module. Sets the maximum Z buffer depth.
+ * Finally queries the \c MESA_DEBUG and \c MESA_VERBOSE environment variables
+ * for debug flags.
+ *
+ * \param ctx the context to initialize
+ * \param api the GL API type to create the context for
+ * \param visual describes the visual attributes for this context
+ * \param share_list points to context to share textures, display lists,
+ * etc with, or NULL
+ * \param driverFunctions table of device driver functions for this context
+ * to use
+ * \param driverContext pointer to driver-specific context data
+ */
+GLboolean
+_mesa_initialize_context(struct gl_context *ctx,
+ gl_api api,
+ const struct gl_config *visual,
+ struct gl_context *share_list,
+ const struct dd_function_table *driverFunctions,
+ void *driverContext)
+{
+ struct gl_shared_state *shared;
+ int i;
+
+ /*ASSERT(driverContext);*/
+ assert(driverFunctions->NewTextureObject);
+ assert(driverFunctions->FreeTexImageData);
+
+ ctx->API = api;
+ ctx->Visual = *visual;
+ ctx->DrawBuffer = NULL;
+ ctx->ReadBuffer = NULL;
+ ctx->WinSysDrawBuffer = NULL;
+ ctx->WinSysReadBuffer = NULL;
+
+ /* misc one-time initializations */
+ one_time_init(ctx);
+
+ /* Plug in driver functions and context pointer here.
+ * This is important because when we call alloc_shared_state() below
+ * we'll call ctx->Driver.NewTextureObject() to create the default
+ * textures.
+ */
+ ctx->Driver = *driverFunctions;
+ ctx->DriverCtx = driverContext;
+
+ if (share_list) {
+ /* share state with another context */
+ shared = share_list->Shared;
+ }
+ else {
+ /* allocate new, unshared state */
+ shared = _mesa_alloc_shared_state(ctx);
+ if (!shared)
+ return GL_FALSE;
+ }
+
+ _glthread_LOCK_MUTEX(shared->Mutex);
+ ctx->Shared = shared;
+ shared->RefCount++;
+ _glthread_UNLOCK_MUTEX(shared->Mutex);
+
+ if (!init_attrib_groups( ctx )) {
+ _mesa_release_shared_state(ctx, ctx->Shared);
+ return GL_FALSE;
+ }
+
+#if FEATURE_dispatch
+ /* setup the API dispatch tables */
+ switch (ctx->API) {
+#if FEATURE_GL
+ case API_OPENGL:
+ ctx->Exec = _mesa_create_exec_table();
+ break;
+#endif
+#if FEATURE_ES1
+ case API_OPENGLES:
+ ctx->Exec = _mesa_create_exec_table_es1();
+ break;
+#endif
+#if FEATURE_ES2
+ case API_OPENGLES2:
+ ctx->Exec = _mesa_create_exec_table_es2();
+ break;
+#endif
+ default:
+ _mesa_problem(ctx, "unknown or unsupported API");
+ break;
+ }
+
+ if (!ctx->Exec) {
+ _mesa_release_shared_state(ctx, ctx->Shared);
+ return GL_FALSE;
+ }
+#endif
+ ctx->CurrentDispatch = ctx->Exec;
+
+ ctx->FragmentProgram._MaintainTexEnvProgram
+ = (_mesa_getenv("MESA_TEX_PROG") != NULL);
+
+ ctx->VertexProgram._MaintainTnlProgram
+ = (_mesa_getenv("MESA_TNL_PROG") != NULL);
+ if (ctx->VertexProgram._MaintainTnlProgram) {
+ /* this is required... */
+ ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
+ }
+
+ /* Mesa core handles all the formats that mesa core knows about.
+ * Drivers will want to override this list with just the formats
+ * they can handle, and confirm that appropriate fallbacks exist in
+ * _mesa_choose_tex_format().
+ */
+ memset(&ctx->TextureFormatSupported, GL_TRUE,
+ sizeof(ctx->TextureFormatSupported));
+
+ switch (ctx->API) {
+ case API_OPENGL:
+#if FEATURE_dlist
+ ctx->Save = _mesa_create_save_table();
+ if (!ctx->Save) {
+ _mesa_release_shared_state(ctx, ctx->Shared);
+ free(ctx->Exec);
+ return GL_FALSE;
+ }
+
+ _mesa_install_save_vtxfmt( ctx, &ctx->ListState.ListVtxfmt );
+#endif
+ break;
+ case API_OPENGLES:
+ /**
+ * GL_OES_texture_cube_map says
+ * "Initially all texture generation modes are set to REFLECTION_MAP_OES"
+ */
+ for (i = 0; i < MAX_TEXTURE_UNITS; i++) {
+ struct gl_texture_unit *texUnit = &ctx->Texture.Unit[i];
+ texUnit->GenS.Mode = GL_REFLECTION_MAP_NV;
+ texUnit->GenT.Mode = GL_REFLECTION_MAP_NV;
+ texUnit->GenR.Mode = GL_REFLECTION_MAP_NV;
+ texUnit->GenS._ModeBit = TEXGEN_REFLECTION_MAP_NV;
+ texUnit->GenT._ModeBit = TEXGEN_REFLECTION_MAP_NV;
+ texUnit->GenR._ModeBit = TEXGEN_REFLECTION_MAP_NV;
+ }
+ break;
+ case API_OPENGLES2:
+ ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
+ ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
+ ctx->Point.PointSprite = GL_TRUE; /* always on for ES 2.x */
+ break;
+ }
+
+ ctx->FirstTimeCurrent = GL_TRUE;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Allocate and initialize a struct gl_context structure.
+ * Note that the driver needs to pass in its dd_function_table here since
+ * we need to at least call driverFunctions->NewTextureObject to initialize
+ * the rendering context.
+ *
+ * \param api the GL API type to create the context for
+ * \param visual a struct gl_config pointer (we copy the struct contents)
+ * \param share_list another context to share display lists with or NULL
+ * \param driverFunctions points to the dd_function_table into which the
+ * driver has plugged in all its special functions.
+ * \param driverContext points to the device driver's private context state
+ *
+ * \return pointer to a new __struct gl_contextRec or NULL if error.
+ */
+struct gl_context *
+_mesa_create_context(gl_api api,
+ const struct gl_config *visual,
+ struct gl_context *share_list,
+ const struct dd_function_table *driverFunctions,
+ void *driverContext)
+{
+ struct gl_context *ctx;
+
+ ASSERT(visual);
+ /*ASSERT(driverContext);*/
+
+ ctx = (struct gl_context *) calloc(1, sizeof(struct gl_context));
+ if (!ctx)
+ return NULL;
+
+ if (_mesa_initialize_context(ctx, api, visual, share_list,
+ driverFunctions, driverContext)) {
+ return ctx;
+ }
+ else {
+ free(ctx);
+ return NULL;
+ }
+}
+
+
+/**
+ * Free the data associated with the given context.
+ *
+ * But doesn't free the struct gl_context struct itself.
+ *
+ * \sa _mesa_initialize_context() and init_attrib_groups().
+ */
+void
+_mesa_free_context_data( struct gl_context *ctx )
+{
+ if (!_mesa_get_current_context()){
+ /* No current context, but we may need one in order to delete
+ * texture objs, etc. So temporarily bind the context now.
+ */
+ _mesa_make_current(ctx, NULL, NULL);
+ }
+
+ /* unreference WinSysDraw/Read buffers */
+ _mesa_reference_framebuffer(&ctx->WinSysDrawBuffer, NULL);
+ _mesa_reference_framebuffer(&ctx->WinSysReadBuffer, NULL);
+ _mesa_reference_framebuffer(&ctx->DrawBuffer, NULL);
+ _mesa_reference_framebuffer(&ctx->ReadBuffer, NULL);
+
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram.Current, NULL);
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram, NULL);
+
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram.Current, NULL);
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram, NULL);
+
+ _mesa_free_attrib_data(ctx);
+ _mesa_free_buffer_objects(ctx);
+ _mesa_free_lighting_data( ctx );
+ _mesa_free_eval_data( ctx );
+ _mesa_free_texture_data( ctx );
+ _mesa_free_matrix_data( ctx );
+ _mesa_free_viewport_data( ctx );
+ _mesa_free_program_data(ctx);
+ _mesa_free_shader_state(ctx);
+ _mesa_free_queryobj_data(ctx);
+ _mesa_free_sync_data(ctx);
+ _mesa_free_varray_data(ctx);
+ _mesa_free_transform_feedback(ctx);
+
+ _mesa_delete_array_object(ctx, ctx->Array.DefaultArrayObj);
+
+#if FEATURE_ARB_pixel_buffer_object
+ _mesa_reference_buffer_object(ctx, &ctx->Pack.BufferObj, NULL);
+ _mesa_reference_buffer_object(ctx, &ctx->Unpack.BufferObj, NULL);
+ _mesa_reference_buffer_object(ctx, &ctx->DefaultPacking.BufferObj, NULL);
+#endif
+
+#if FEATURE_ARB_vertex_buffer_object
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ArrayBufferObj, NULL);
+ _mesa_reference_buffer_object(ctx, &ctx->Array.ElementArrayBufferObj, NULL);
+#endif
+
+ /* free dispatch tables */
+ free(ctx->Exec);
+ free(ctx->Save);
+
+ /* Shared context state (display lists, textures, etc) */
+ _mesa_release_shared_state( ctx, ctx->Shared );
+
+ /* needs to be after freeing shared state */
+ _mesa_free_display_list_data(ctx);
+
+ if (ctx->Extensions.String)
+ free((void *) ctx->Extensions.String);
+
+ if (ctx->VersionString)
+ free(ctx->VersionString);
+
+ /* unbind the context if it's currently bound */
+ if (ctx == _mesa_get_current_context()) {
+ _mesa_make_current(NULL, NULL, NULL);
+ }
+}
+
+
+/**
+ * Destroy a struct gl_context structure.
+ *
+ * \param ctx GL context.
+ *
+ * Calls _mesa_free_context_data() and frees the gl_context object itself.
+ */
+void
+_mesa_destroy_context( struct gl_context *ctx )
+{
+ if (ctx) {
+ _mesa_free_context_data(ctx);
+ free( (void *) ctx );
+ }
+}
+
+
+#if _HAVE_FULL_GL
+/**
+ * Copy attribute groups from one context to another.
+ *
+ * \param src source context
+ * \param dst destination context
+ * \param mask bitwise OR of GL_*_BIT flags
+ *
+ * According to the bits specified in \p mask, copies the corresponding
+ * attributes from \p src into \p dst. For many of the attributes a simple \c
+ * memcpy is not enough due to the existence of internal pointers in their data
+ * structures.
+ */
+void
+_mesa_copy_context( const struct gl_context *src, struct gl_context *dst, GLuint mask )
+{
+ if (mask & GL_ACCUM_BUFFER_BIT) {
+ /* OK to memcpy */
+ dst->Accum = src->Accum;
+ }
+ if (mask & GL_COLOR_BUFFER_BIT) {
+ /* OK to memcpy */
+ dst->Color = src->Color;
+ }
+ if (mask & GL_CURRENT_BIT) {
+ /* OK to memcpy */
+ dst->Current = src->Current;
+ }
+ if (mask & GL_DEPTH_BUFFER_BIT) {
+ /* OK to memcpy */
+ dst->Depth = src->Depth;
+ }
+ if (mask & GL_ENABLE_BIT) {
+ /* no op */
+ }
+ if (mask & GL_EVAL_BIT) {
+ /* OK to memcpy */
+ dst->Eval = src->Eval;
+ }
+ if (mask & GL_FOG_BIT) {
+ /* OK to memcpy */
+ dst->Fog = src->Fog;
+ }
+ if (mask & GL_HINT_BIT) {
+ /* OK to memcpy */
+ dst->Hint = src->Hint;
+ }
+ if (mask & GL_LIGHTING_BIT) {
+ GLuint i;
+ /* begin with memcpy */
+ dst->Light = src->Light;
+ /* fixup linked lists to prevent pointer insanity */
+ make_empty_list( &(dst->Light.EnabledList) );
+ for (i = 0; i < MAX_LIGHTS; i++) {
+ if (dst->Light.Light[i].Enabled) {
+ insert_at_tail(&(dst->Light.EnabledList), &(dst->Light.Light[i]));
+ }
+ }
+ }
+ if (mask & GL_LINE_BIT) {
+ /* OK to memcpy */
+ dst->Line = src->Line;
+ }
+ if (mask & GL_LIST_BIT) {
+ /* OK to memcpy */
+ dst->List = src->List;
+ }
+ if (mask & GL_PIXEL_MODE_BIT) {
+ /* OK to memcpy */
+ dst->Pixel = src->Pixel;
+ }
+ if (mask & GL_POINT_BIT) {
+ /* OK to memcpy */
+ dst->Point = src->Point;
+ }
+ if (mask & GL_POLYGON_BIT) {
+ /* OK to memcpy */
+ dst->Polygon = src->Polygon;
+ }
+ if (mask & GL_POLYGON_STIPPLE_BIT) {
+ /* Use loop instead of memcpy due to problem with Portland Group's
+ * C compiler. Reported by John Stone.
+ */
+ GLuint i;
+ for (i = 0; i < 32; i++) {
+ dst->PolygonStipple[i] = src->PolygonStipple[i];
+ }
+ }
+ if (mask & GL_SCISSOR_BIT) {
+ /* OK to memcpy */
+ dst->Scissor = src->Scissor;
+ }
+ if (mask & GL_STENCIL_BUFFER_BIT) {
+ /* OK to memcpy */
+ dst->Stencil = src->Stencil;
+ }
+ if (mask & GL_TEXTURE_BIT) {
+ /* Cannot memcpy because of pointers */
+ _mesa_copy_texture_state(src, dst);
+ }
+ if (mask & GL_TRANSFORM_BIT) {
+ /* OK to memcpy */
+ dst->Transform = src->Transform;
+ }
+ if (mask & GL_VIEWPORT_BIT) {
+ /* Cannot use memcpy, because of pointers in GLmatrix _WindowMap */
+ dst->Viewport.X = src->Viewport.X;
+ dst->Viewport.Y = src->Viewport.Y;
+ dst->Viewport.Width = src->Viewport.Width;
+ dst->Viewport.Height = src->Viewport.Height;
+ dst->Viewport.Near = src->Viewport.Near;
+ dst->Viewport.Far = src->Viewport.Far;
+ _math_matrix_copy(&dst->Viewport._WindowMap, &src->Viewport._WindowMap);
+ }
+
+ /* XXX FIXME: Call callbacks?
+ */
+ dst->NewState = _NEW_ALL;
+}
+#endif
+
+
+/**
+ * Check if the given context can render into the given framebuffer
+ * by checking visual attributes.
+ *
+ * Most of these tests could go away because Mesa is now pretty flexible
+ * in terms of mixing rendering contexts with framebuffers. As long
+ * as RGB vs. CI mode agree, we're probably good.
+ *
+ * \return GL_TRUE if compatible, GL_FALSE otherwise.
+ */
+static GLboolean
+check_compatible(const struct gl_context *ctx,
+ const struct gl_framebuffer *buffer)
+{
+ const struct gl_config *ctxvis = &ctx->Visual;
+ const struct gl_config *bufvis = &buffer->Visual;
+
+ if (buffer == _mesa_get_incomplete_framebuffer())
+ return GL_TRUE;
+
+#if 0
+ /* disabling this fixes the fgl_glxgears pbuffer demo */
+ if (ctxvis->doubleBufferMode && !bufvis->doubleBufferMode)
+ return GL_FALSE;
+#endif
+ if (ctxvis->stereoMode && !bufvis->stereoMode)
+ return GL_FALSE;
+ if (ctxvis->haveAccumBuffer && !bufvis->haveAccumBuffer)
+ return GL_FALSE;
+ if (ctxvis->haveDepthBuffer && !bufvis->haveDepthBuffer)
+ return GL_FALSE;
+ if (ctxvis->haveStencilBuffer && !bufvis->haveStencilBuffer)
+ return GL_FALSE;
+ if (ctxvis->redMask && ctxvis->redMask != bufvis->redMask)
+ return GL_FALSE;
+ if (ctxvis->greenMask && ctxvis->greenMask != bufvis->greenMask)
+ return GL_FALSE;
+ if (ctxvis->blueMask && ctxvis->blueMask != bufvis->blueMask)
+ return GL_FALSE;
+#if 0
+ /* disabled (see bug 11161) */
+ if (ctxvis->depthBits && ctxvis->depthBits != bufvis->depthBits)
+ return GL_FALSE;
+#endif
+ if (ctxvis->stencilBits && ctxvis->stencilBits != bufvis->stencilBits)
+ return GL_FALSE;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Do one-time initialization for the given framebuffer. Specifically,
+ * ask the driver for the window's current size and update the framebuffer
+ * object to match.
+ * Really, the device driver should totally take care of this.
+ */
+static void
+initialize_framebuffer_size(struct gl_context *ctx, struct gl_framebuffer *fb)
+{
+ GLuint width, height;
+ if (ctx->Driver.GetBufferSize) {
+ ctx->Driver.GetBufferSize(fb, &width, &height);
+ if (ctx->Driver.ResizeBuffers)
+ ctx->Driver.ResizeBuffers(ctx, fb, width, height);
+ fb->Initialized = GL_TRUE;
+ }
+}
+
+
+/**
+ * Check if the viewport/scissor size has not yet been initialized.
+ * Initialize the size if the given width and height are non-zero.
+ */
+void
+_mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height)
+{
+ if (!ctx->ViewportInitialized && width > 0 && height > 0) {
+ /* Note: set flag here, before calling _mesa_set_viewport(), to prevent
+ * potential infinite recursion.
+ */
+ ctx->ViewportInitialized = GL_TRUE;
+ _mesa_set_viewport(ctx, 0, 0, width, height);
+ _mesa_set_scissor(ctx, 0, 0, width, height);
+ }
+}
+
+
+/**
+ * Bind the given context to the given drawBuffer and readBuffer and
+ * make it the current context for the calling thread.
+ * We'll render into the drawBuffer and read pixels from the
+ * readBuffer (i.e. glRead/CopyPixels, glCopyTexImage, etc).
+ *
+ * We check that the context's and framebuffer's visuals are compatible
+ * and return immediately if they're not.
+ *
+ * \param newCtx the new GL context. If NULL then there will be no current GL
+ * context.
+ * \param drawBuffer the drawing framebuffer
+ * \param readBuffer the reading framebuffer
+ */
+GLboolean
+_mesa_make_current( struct gl_context *newCtx,
+ struct gl_framebuffer *drawBuffer,
+ struct gl_framebuffer *readBuffer )
+{
+ GET_CURRENT_CONTEXT(curCtx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(newCtx, "_mesa_make_current()\n");
+
+ /* Check that the context's and framebuffer's visuals are compatible.
+ */
+ if (newCtx && drawBuffer && newCtx->WinSysDrawBuffer != drawBuffer) {
+ if (!check_compatible(newCtx, drawBuffer)) {
+ _mesa_warning(newCtx,
+ "MakeCurrent: incompatible visuals for context and drawbuffer");
+ return GL_FALSE;
+ }
+ }
+ if (newCtx && readBuffer && newCtx->WinSysReadBuffer != readBuffer) {
+ if (!check_compatible(newCtx, readBuffer)) {
+ _mesa_warning(newCtx,
+ "MakeCurrent: incompatible visuals for context and readbuffer");
+ return GL_FALSE;
+ }
+ }
+
+ if (curCtx &&
+ (curCtx->WinSysDrawBuffer || curCtx->WinSysReadBuffer) && /* make sure this context is valid for flushing */
+ curCtx != newCtx)
+ _mesa_flush(curCtx);
+
+ /* We used to call _glapi_check_multithread() here. Now do it in drivers */
+ _glapi_set_context((void *) newCtx);
+ ASSERT(_mesa_get_current_context() == newCtx);
+
+ if (!newCtx) {
+ _glapi_set_dispatch(NULL); /* none current */
+ }
+ else {
+ _glapi_set_dispatch(newCtx->CurrentDispatch);
+
+ if (drawBuffer && readBuffer) {
+ /* TODO: check if newCtx and buffer's visual match??? */
+
+ ASSERT(drawBuffer->Name == 0);
+ ASSERT(readBuffer->Name == 0);
+ _mesa_reference_framebuffer(&newCtx->WinSysDrawBuffer, drawBuffer);
+ _mesa_reference_framebuffer(&newCtx->WinSysReadBuffer, readBuffer);
+
+ /*
+ * Only set the context's Draw/ReadBuffer fields if they're NULL
+ * or not bound to a user-created FBO.
+ */
+ if (!newCtx->DrawBuffer || newCtx->DrawBuffer->Name == 0) {
+ /* KW: merge conflict here, revisit.
+ */
+ /* fix up the fb fields - these will end up wrong otherwise
+ * if the DRIdrawable changes, and everything relies on them.
+ * This is a bit messy (same as needed in _mesa_BindFramebufferEXT)
+ */
+ unsigned int i;
+ GLenum buffers[MAX_DRAW_BUFFERS];
+
+ _mesa_reference_framebuffer(&newCtx->DrawBuffer, drawBuffer);
+
+ for(i = 0; i < newCtx->Const.MaxDrawBuffers; i++) {
+ buffers[i] = newCtx->Color.DrawBuffer[i];
+ }
+
+ _mesa_drawbuffers(newCtx, newCtx->Const.MaxDrawBuffers,
+ buffers, NULL);
+ }
+ if (!newCtx->ReadBuffer || newCtx->ReadBuffer->Name == 0) {
+ _mesa_reference_framebuffer(&newCtx->ReadBuffer, readBuffer);
+ }
+
+ /* XXX only set this flag if we're really changing the draw/read
+ * framebuffer bindings.
+ */
+ newCtx->NewState |= _NEW_BUFFERS;
+
+#if 1
+ /* We want to get rid of these lines: */
+
+#if _HAVE_FULL_GL
+ if (!drawBuffer->Initialized) {
+ initialize_framebuffer_size(newCtx, drawBuffer);
+ }
+ if (readBuffer != drawBuffer && !readBuffer->Initialized) {
+ initialize_framebuffer_size(newCtx, readBuffer);
+ }
+
+ _mesa_resizebuffers(newCtx);
+#endif
+
+#else
+ /* We want the drawBuffer and readBuffer to be initialized by
+ * the driver.
+ * This generally means the Width and Height match the actual
+ * window size and the renderbuffers (both hardware and software
+ * based) are allocated to match. The later can generally be
+ * done with a call to _mesa_resize_framebuffer().
+ *
+ * It's theoretically possible for a buffer to have zero width
+ * or height, but for now, assert check that the driver did what's
+ * expected of it.
+ */
+ ASSERT(drawBuffer->Width > 0);
+ ASSERT(drawBuffer->Height > 0);
+#endif
+
+ if (drawBuffer) {
+ _mesa_check_init_viewport(newCtx,
+ drawBuffer->Width, drawBuffer->Height);
+ }
+ }
+
+ if (newCtx->FirstTimeCurrent) {
+ _mesa_compute_version(newCtx);
+
+ newCtx->Extensions.String = _mesa_make_extension_string(newCtx);
+
+ check_context_limits(newCtx);
+
+ /* We can use this to help debug user's problems. Tell them to set
+ * the MESA_INFO env variable before running their app. Then the
+ * first time each context is made current we'll print some useful
+ * information.
+ */
+ if (_mesa_getenv("MESA_INFO")) {
+ _mesa_print_info();
+ }
+
+ newCtx->FirstTimeCurrent = GL_FALSE;
+ }
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Make context 'ctx' share the display lists, textures and programs
+ * that are associated with 'ctxToShare'.
+ * Any display lists, textures or programs associated with 'ctx' will
+ * be deleted if nobody else is sharing them.
+ */
+GLboolean
+_mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare)
+{
+ if (ctx && ctxToShare && ctx->Shared && ctxToShare->Shared) {
+ struct gl_shared_state *oldSharedState = ctx->Shared;
+
+ ctx->Shared = ctxToShare->Shared;
+
+ _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
+ ctx->Shared->RefCount++;
+ _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
+
+ update_default_objects(ctx);
+
+ _mesa_release_shared_state(ctx, oldSharedState);
+
+ return GL_TRUE;
+ }
+ else {
+ return GL_FALSE;
+ }
+}
+
+
+
+/**
+ * \return pointer to the current GL context for this thread.
+ *
+ * Calls _glapi_get_context(). This isn't the fastest way to get the current
+ * context. If you need speed, see the #GET_CURRENT_CONTEXT macro in
+ * context.h.
+ */
+struct gl_context *
+_mesa_get_current_context( void )
+{
+ return (struct gl_context *) _glapi_get_context();
+}
+
+
+/**
+ * Get context's current API dispatch table.
+ *
+ * It'll either be the immediate-mode execute dispatcher or the display list
+ * compile dispatcher.
+ *
+ * \param ctx GL context.
+ *
+ * \return pointer to dispatch_table.
+ *
+ * Simply returns __struct gl_contextRec::CurrentDispatch.
+ */
+struct _glapi_table *
+_mesa_get_dispatch(struct gl_context *ctx)
+{
+ return ctx->CurrentDispatch;
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name Miscellaneous functions */
+/**********************************************************************/
+/*@{*/
+
+/**
+ * Record an error.
+ *
+ * \param ctx GL context.
+ * \param error error code.
+ *
+ * Records the given error code and call the driver's dd_function_table::Error
+ * function if defined.
+ *
+ * \sa
+ * This is called via _mesa_error().
+ */
+void
+_mesa_record_error(struct gl_context *ctx, GLenum error)
+{
+ if (!ctx)
+ return;
+
+ if (ctx->ErrorValue == GL_NO_ERROR) {
+ ctx->ErrorValue = error;
+ }
+
+ /* Call device driver's error handler, if any. This is used on the Mac. */
+ if (ctx->Driver.Error) {
+ ctx->Driver.Error(ctx);
+ }
+}
+
+
+/**
+ * Flush commands and wait for completion.
+ */
+void
+_mesa_finish(struct gl_context *ctx)
+{
+ FLUSH_CURRENT( ctx, 0 );
+ if (ctx->Driver.Finish) {
+ ctx->Driver.Finish(ctx);
+ }
+}
+
+
+/**
+ * Flush commands.
+ */
+void
+_mesa_flush(struct gl_context *ctx)
+{
+ FLUSH_CURRENT( ctx, 0 );
+ if (ctx->Driver.Flush) {
+ ctx->Driver.Flush(ctx);
+ }
+}
+
+
+
+/**
+ * Execute glFinish().
+ *
+ * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
+ * dd_function_table::Finish driver callback, if not NULL.
+ */
+void GLAPIENTRY
+_mesa_Finish(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
+ _mesa_finish(ctx);
+}
+
+
+/**
+ * Execute glFlush().
+ *
+ * Calls the #ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH macro and the
+ * dd_function_table::Flush driver callback, if not NULL.
+ */
+void GLAPIENTRY
+_mesa_Flush(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
+ _mesa_flush(ctx);
+}
+
+
+/**
+ * Set mvp_with_dp4 flag. If a driver has a preference for DP4 over
+ * MUL/MAD, or vice versa, call this function to register that.
+ * Otherwise we default to MUL/MAD.
+ */
+void
+_mesa_set_mvp_with_dp4( struct gl_context *ctx,
+ GLboolean flag )
+{
+ ctx->mvp_with_dp4 = flag;
+}
+
+
+
+/**
+ * Prior to drawing anything with glBegin, glDrawArrays, etc. this function
+ * is called to see if it's valid to render. This involves checking that
+ * the current shader is valid and the framebuffer is complete.
+ * If an error is detected it'll be recorded here.
+ * \return GL_TRUE if OK to render, GL_FALSE if not
+ */
+GLboolean
+_mesa_valid_to_render(struct gl_context *ctx, const char *where)
+{
+ bool vert_from_glsl_shader = false;
+ bool geom_from_glsl_shader = false;
+ bool frag_from_glsl_shader = false;
+
+ /* This depends on having up to date derived state (shaders) */
+ if (ctx->NewState)
+ _mesa_update_state(ctx);
+
+ if (ctx->Shader.CurrentVertexProgram) {
+ vert_from_glsl_shader = true;
+
+ if (!ctx->Shader.CurrentVertexProgram->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(shader not linked)", where);
+ return GL_FALSE;
+ }
+#if 0 /* not normally enabled */
+ {
+ char errMsg[100];
+ if (!_mesa_validate_shader_program(ctx,
+ ctx->Shader.CurrentVertexProgram,
+ errMsg)) {
+ _mesa_warning(ctx, "Shader program %u is invalid: %s",
+ ctx->Shader.CurrentVertexProgram->Name, errMsg);
+ }
+ }
+#endif
+ }
+
+ if (ctx->Shader.CurrentGeometryProgram) {
+ geom_from_glsl_shader = true;
+
+ if (!ctx->Shader.CurrentGeometryProgram->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(shader not linked)", where);
+ return GL_FALSE;
+ }
+#if 0 /* not normally enabled */
+ {
+ char errMsg[100];
+ if (!_mesa_validate_shader_program(ctx,
+ ctx->Shader.CurrentGeometryProgram,
+ errMsg)) {
+ _mesa_warning(ctx, "Shader program %u is invalid: %s",
+ ctx->Shader.CurrentGeometryProgram->Name, errMsg);
+ }
+ }
+#endif
+ }
+
+ if (ctx->Shader.CurrentFragmentProgram) {
+ frag_from_glsl_shader = true;
+
+ if (!ctx->Shader.CurrentFragmentProgram->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(shader not linked)", where);
+ return GL_FALSE;
+ }
+#if 0 /* not normally enabled */
+ {
+ char errMsg[100];
+ if (!_mesa_validate_shader_program(ctx,
+ ctx->Shader.CurrentFragmentProgram,
+ errMsg)) {
+ _mesa_warning(ctx, "Shader program %u is invalid: %s",
+ ctx->Shader.CurrentFragmentProgram->Name, errMsg);
+ }
+ }
+#endif
+ }
+
+ /* Any shader stages that are not supplied by the GLSL shader and have
+ * assembly shaders enabled must now be validated.
+ */
+ if (!vert_from_glsl_shader
+ && ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(vertex program not valid)", where);
+ return GL_FALSE;
+ }
+
+ /* FINISHME: If GL_NV_geometry_program4 is ever supported, the current
+ * FINISHME: geometry program should validated here.
+ */
+ (void) geom_from_glsl_shader;
+
+ if (!frag_from_glsl_shader) {
+ if (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(fragment program not valid)", where);
+ return GL_FALSE;
+ }
+
+ /* If drawing to integer-valued color buffers, there must be an
+ * active fragment shader (GL_EXT_texture_integer).
+ */
+ if (ctx->DrawBuffer && ctx->DrawBuffer->_IntegerColor) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(integer format but no fragment shader)", where);
+ return GL_FALSE;
+ }
+ }
+
+ if (ctx->DrawBuffer->_Status != GL_FRAMEBUFFER_COMPLETE_EXT) {
+ _mesa_error(ctx, GL_INVALID_FRAMEBUFFER_OPERATION_EXT,
+ "%s(incomplete framebuffer)", where);
+ return GL_FALSE;
+ }
+
+#ifdef DEBUG
+ if (ctx->Shader.Flags & GLSL_LOG) {
+ struct gl_shader_program *shProg[MESA_SHADER_TYPES];
+ gl_shader_type i;
+
+ shProg[MESA_SHADER_VERTEX] = ctx->Shader.CurrentVertexProgram;
+ shProg[MESA_SHADER_GEOMETRY] = ctx->Shader.CurrentGeometryProgram;
+ shProg[MESA_SHADER_FRAGMENT] = ctx->Shader.CurrentFragmentProgram;
+
+ for (i = 0; i < MESA_SHADER_TYPES; i++) {
+ struct gl_shader *sh;
+
+ if (shProg[i] == NULL || shProg[i]->_Used
+ || shProg[i]->_LinkedShaders[i] == NULL)
+ continue;
+
+ /* This is the first time this shader is being used.
+ * Append shader's constants/uniforms to log file.
+ *
+ * The logic is a little odd here. We only want to log data for each
+ * shader target that will actually be used, and we only want to log
+ * it once. It's possible to have a program bound to the vertex
+ * shader target that also supplied a fragment shader. If that
+ * program isn't also bound to the fragment shader target we don't
+ * want to log its fragment data.
+ */
+ sh = shProg[i]->_LinkedShaders[i];
+ switch (sh->Type) {
+ case GL_VERTEX_SHADER:
+ _mesa_append_uniforms_to_file(sh, &shProg[i]->VertexProgram->Base);
+ break;
+
+ case GL_GEOMETRY_SHADER_ARB:
+ _mesa_append_uniforms_to_file(sh,
+ &shProg[i]->GeometryProgram->Base);
+ break;
+
+ case GL_FRAGMENT_SHADER:
+ _mesa_append_uniforms_to_file(sh,
+ &shProg[i]->FragmentProgram->Base);
+ break;
+ }
+ }
+
+ for (i = 0; i < MESA_SHADER_TYPES; i++) {
+ if (shProg[i] != NULL)
+ shProg[i]->_Used = GL_TRUE;
+ }
+ }
+#endif
+
+ return GL_TRUE;
+}
+
+
+/*@}*/
diff --git a/mesalib/src/mesa/main/context.h b/mesalib/src/mesa/main/context.h
index 4e391dde4..160e795f7 100644
--- a/mesalib/src/mesa/main/context.h
+++ b/mesalib/src/mesa/main/context.h
@@ -1,313 +1,313 @@
-/*
- * Mesa 3-D graphics library
- * Version: 6.5.1
- *
- * Copyright (C) 1999-2006 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 context.h
- * Mesa context and visual-related functions.
- *
- * There are three large Mesa data types/classes which are meant to be
- * used by device drivers:
- * - struct gl_context: this contains the Mesa rendering state
- * - struct gl_config: this describes the color buffer (RGB vs. ci), whether or not
- * there's a depth buffer, stencil buffer, etc.
- * - struct gl_framebuffer: contains pointers to the depth buffer, stencil buffer,
- * accum buffer and alpha buffers.
- *
- * These types should be encapsulated by corresponding device driver
- * data types. See xmesa.h and xmesaP.h for an example.
- *
- * In OOP terms, struct gl_context, struct gl_config, and struct gl_framebuffer are base classes
- * which the device driver must derive from.
- *
- * The following functions create and destroy these data types.
- */
-
-
-#ifndef CONTEXT_H
-#define CONTEXT_H
-
-
-#include "imports.h"
-#include "mtypes.h"
-
-
-struct _glapi_table;
-
-
-/** \name Visual-related functions */
-/*@{*/
-
-extern struct gl_config *
-_mesa_create_visual( GLboolean dbFlag,
- GLboolean stereoFlag,
- GLint redBits,
- GLint greenBits,
- GLint blueBits,
- GLint alphaBits,
- GLint depthBits,
- GLint stencilBits,
- GLint accumRedBits,
- GLint accumGreenBits,
- GLint accumBlueBits,
- GLint accumAlphaBits,
- GLint numSamples );
-
-extern GLboolean
-_mesa_initialize_visual( struct gl_config *v,
- GLboolean dbFlag,
- GLboolean stereoFlag,
- GLint redBits,
- GLint greenBits,
- GLint blueBits,
- GLint alphaBits,
- GLint depthBits,
- GLint stencilBits,
- GLint accumRedBits,
- GLint accumGreenBits,
- GLint accumBlueBits,
- GLint accumAlphaBits,
- GLint numSamples );
-
-extern void
-_mesa_destroy_visual( struct gl_config *vis );
-
-/*@}*/
-
-
-/** \name Context-related functions */
-/*@{*/
-
-extern GLboolean
-_mesa_initialize_context( struct gl_context *ctx,
- gl_api api,
- const struct gl_config *visual,
- struct gl_context *share_list,
- const struct dd_function_table *driverFunctions,
- void *driverContext );
-
-extern struct gl_context *
-_mesa_create_context(gl_api api,
- const struct gl_config *visual,
- struct gl_context *share_list,
- const struct dd_function_table *driverFunctions,
- void *driverContext);
-
-extern void
-_mesa_free_context_data( struct gl_context *ctx );
-
-extern void
-_mesa_destroy_context( struct gl_context *ctx );
-
-
-extern void
-_mesa_copy_context(const struct gl_context *src, struct gl_context *dst, GLuint mask);
-
-
-extern void
-_mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height);
-
-extern GLboolean
-_mesa_make_current( struct gl_context *ctx, struct gl_framebuffer *drawBuffer,
- struct gl_framebuffer *readBuffer );
-
-extern GLboolean
-_mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare);
-
-extern struct gl_context *
-_mesa_get_current_context(void);
-
-/*@}*/
-
-extern void
-_mesa_init_get_hash(struct gl_context *ctx);
-
-extern void
-_mesa_notifySwapBuffers(struct gl_context *gc);
-
-
-extern struct _glapi_table *
-_mesa_get_dispatch(struct gl_context *ctx);
-
-
-void
-_mesa_set_mvp_with_dp4( struct gl_context *ctx,
- GLboolean flag );
-
-
-extern GLboolean
-_mesa_valid_to_render(struct gl_context *ctx, const char *where);
-
-
-
-/** \name Miscellaneous */
-/*@{*/
-
-extern void
-_mesa_record_error( struct gl_context *ctx, GLenum error );
-
-
-extern void
-_mesa_finish(struct gl_context *ctx);
-
-extern void
-_mesa_flush(struct gl_context *ctx);
-
-
-extern void GLAPIENTRY
-_mesa_Finish( void );
-
-extern void GLAPIENTRY
-_mesa_Flush( void );
-
-/*@}*/
-
-
-/**
- * \name Macros for flushing buffered rendering commands before state changes,
- * checking if inside glBegin/glEnd, etc.
- */
-/*@{*/
-
-/**
- * Flush vertices.
- *
- * \param ctx GL context.
- * \param newstate new state.
- *
- * Checks if dd_function_table::NeedFlush is marked to flush stored vertices,
- * and calls dd_function_table::FlushVertices if so. Marks
- * __struct gl_contextRec::NewState with \p newstate.
- */
-#define FLUSH_VERTICES(ctx, newstate) \
-do { \
- if (MESA_VERBOSE & VERBOSE_STATE) \
- _mesa_debug(ctx, "FLUSH_VERTICES in %s\n", MESA_FUNCTION);\
- if (ctx->Driver.NeedFlush & FLUSH_STORED_VERTICES) \
- ctx->Driver.FlushVertices(ctx, FLUSH_STORED_VERTICES); \
- ctx->NewState |= newstate; \
-} while (0)
-
-/**
- * Flush current state.
- *
- * \param ctx GL context.
- * \param newstate new state.
- *
- * Checks if dd_function_table::NeedFlush is marked to flush current state,
- * and calls dd_function_table::FlushVertices if so. Marks
- * __struct gl_contextRec::NewState with \p newstate.
- */
-#define FLUSH_CURRENT(ctx, newstate) \
-do { \
- if (MESA_VERBOSE & VERBOSE_STATE) \
- _mesa_debug(ctx, "FLUSH_CURRENT in %s\n", MESA_FUNCTION); \
- if (ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT) \
- ctx->Driver.FlushVertices(ctx, FLUSH_UPDATE_CURRENT); \
- ctx->NewState |= newstate; \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair, with return value.
- *
- * \param ctx GL context.
- * \param retval value to return value in case the assertion fails.
- */
-#define ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, retval) \
-do { \
- if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) { \
- _mesa_error(ctx, GL_INVALID_OPERATION, "Inside glBegin/glEnd"); \
- return retval; \
- } \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair.
- *
- * \param ctx GL context.
- */
-#define ASSERT_OUTSIDE_BEGIN_END(ctx) \
-do { \
- if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) { \
- _mesa_error(ctx, GL_INVALID_OPERATION, "Inside glBegin/glEnd"); \
- return; \
- } \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair and flush the vertices.
- *
- * \param ctx GL context.
- */
-#define ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx) \
-do { \
- ASSERT_OUTSIDE_BEGIN_END(ctx); \
- FLUSH_VERTICES(ctx, 0); \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair and flush the vertices, with return value.
- *
- * \param ctx GL context.
- * \param retval value to return value in case the assertion fails.
- */
-#define ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH_WITH_RETVAL(ctx, retval) \
-do { \
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, retval); \
- FLUSH_VERTICES(ctx, 0); \
-} while (0)
-
-/*@}*/
-
-
-
-/**
- * Is the secondary color needed?
- */
-#define NEED_SECONDARY_COLOR(CTX) \
- (((CTX)->Light.Enabled && \
- (CTX)->Light.Model.ColorControl == GL_SEPARATE_SPECULAR_COLOR) \
- || (CTX)->Fog.ColorSumEnabled \
- || ((CTX)->VertexProgram._Current && \
- ((CTX)->VertexProgram._Current != (CTX)->VertexProgram._TnlProgram) && \
- ((CTX)->VertexProgram._Current->Base.InputsRead & VERT_BIT_COLOR1)) \
- || ((CTX)->FragmentProgram._Current && \
- ((CTX)->FragmentProgram._Current != (CTX)->FragmentProgram._TexEnvProgram) && \
- ((CTX)->FragmentProgram._Current->Base.InputsRead & FRAG_BIT_COL1)) \
- )
-
-
-/**
- * Is RGBA LogicOp enabled?
- */
-#define RGBA_LOGICOP_ENABLED(CTX) \
- ((CTX)->Color.ColorLogicOpEnabled || \
- ((CTX)->Color.BlendEnabled && (CTX)->Color.Blend[0].EquationRGB == GL_LOGIC_OP))
-
-
-#endif /* CONTEXT_H */
+/*
+ * Mesa 3-D graphics library
+ * Version: 6.5.1
+ *
+ * Copyright (C) 1999-2006 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 context.h
+ * Mesa context and visual-related functions.
+ *
+ * There are three large Mesa data types/classes which are meant to be
+ * used by device drivers:
+ * - struct gl_context: this contains the Mesa rendering state
+ * - struct gl_config: this describes the color buffer (RGB vs. ci), whether or not
+ * there's a depth buffer, stencil buffer, etc.
+ * - struct gl_framebuffer: contains pointers to the depth buffer, stencil buffer,
+ * accum buffer and alpha buffers.
+ *
+ * These types should be encapsulated by corresponding device driver
+ * data types. See xmesa.h and xmesaP.h for an example.
+ *
+ * In OOP terms, struct gl_context, struct gl_config, and struct gl_framebuffer are base classes
+ * which the device driver must derive from.
+ *
+ * The following functions create and destroy these data types.
+ */
+
+
+#ifndef CONTEXT_H
+#define CONTEXT_H
+
+
+#include "imports.h"
+#include "mtypes.h"
+
+
+struct _glapi_table;
+
+
+/** \name Visual-related functions */
+/*@{*/
+
+extern struct gl_config *
+_mesa_create_visual( GLboolean dbFlag,
+ GLboolean stereoFlag,
+ GLint redBits,
+ GLint greenBits,
+ GLint blueBits,
+ GLint alphaBits,
+ GLint depthBits,
+ GLint stencilBits,
+ GLint accumRedBits,
+ GLint accumGreenBits,
+ GLint accumBlueBits,
+ GLint accumAlphaBits,
+ GLint numSamples );
+
+extern GLboolean
+_mesa_initialize_visual( struct gl_config *v,
+ GLboolean dbFlag,
+ GLboolean stereoFlag,
+ GLint redBits,
+ GLint greenBits,
+ GLint blueBits,
+ GLint alphaBits,
+ GLint depthBits,
+ GLint stencilBits,
+ GLint accumRedBits,
+ GLint accumGreenBits,
+ GLint accumBlueBits,
+ GLint accumAlphaBits,
+ GLint numSamples );
+
+extern void
+_mesa_destroy_visual( struct gl_config *vis );
+
+/*@}*/
+
+
+/** \name Context-related functions */
+/*@{*/
+
+extern GLboolean
+_mesa_initialize_context( struct gl_context *ctx,
+ gl_api api,
+ const struct gl_config *visual,
+ struct gl_context *share_list,
+ const struct dd_function_table *driverFunctions,
+ void *driverContext );
+
+extern struct gl_context *
+_mesa_create_context(gl_api api,
+ const struct gl_config *visual,
+ struct gl_context *share_list,
+ const struct dd_function_table *driverFunctions,
+ void *driverContext);
+
+extern void
+_mesa_free_context_data( struct gl_context *ctx );
+
+extern void
+_mesa_destroy_context( struct gl_context *ctx );
+
+
+extern void
+_mesa_copy_context(const struct gl_context *src, struct gl_context *dst, GLuint mask);
+
+
+extern void
+_mesa_check_init_viewport(struct gl_context *ctx, GLuint width, GLuint height);
+
+extern GLboolean
+_mesa_make_current( struct gl_context *ctx, struct gl_framebuffer *drawBuffer,
+ struct gl_framebuffer *readBuffer );
+
+extern GLboolean
+_mesa_share_state(struct gl_context *ctx, struct gl_context *ctxToShare);
+
+extern struct gl_context *
+_mesa_get_current_context(void);
+
+/*@}*/
+
+extern void
+_mesa_init_get_hash(struct gl_context *ctx);
+
+extern void
+_mesa_notifySwapBuffers(struct gl_context *gc);
+
+
+extern struct _glapi_table *
+_mesa_get_dispatch(struct gl_context *ctx);
+
+
+void
+_mesa_set_mvp_with_dp4( struct gl_context *ctx,
+ GLboolean flag );
+
+
+extern GLboolean
+_mesa_valid_to_render(struct gl_context *ctx, const char *where);
+
+
+
+/** \name Miscellaneous */
+/*@{*/
+
+extern void
+_mesa_record_error( struct gl_context *ctx, GLenum error );
+
+
+extern void
+_mesa_finish(struct gl_context *ctx);
+
+extern void
+_mesa_flush(struct gl_context *ctx);
+
+
+extern void GLAPIENTRY
+_mesa_Finish( void );
+
+extern void GLAPIENTRY
+_mesa_Flush( void );
+
+/*@}*/
+
+
+/**
+ * \name Macros for flushing buffered rendering commands before state changes,
+ * checking if inside glBegin/glEnd, etc.
+ */
+/*@{*/
+
+/**
+ * Flush vertices.
+ *
+ * \param ctx GL context.
+ * \param newstate new state.
+ *
+ * Checks if dd_function_table::NeedFlush is marked to flush stored vertices,
+ * and calls dd_function_table::FlushVertices if so. Marks
+ * __struct gl_contextRec::NewState with \p newstate.
+ */
+#define FLUSH_VERTICES(ctx, newstate) \
+do { \
+ if (MESA_VERBOSE & VERBOSE_STATE) \
+ _mesa_debug(ctx, "FLUSH_VERTICES in %s\n", MESA_FUNCTION);\
+ if (ctx->Driver.NeedFlush & FLUSH_STORED_VERTICES) \
+ ctx->Driver.FlushVertices(ctx, FLUSH_STORED_VERTICES); \
+ ctx->NewState |= newstate; \
+} while (0)
+
+/**
+ * Flush current state.
+ *
+ * \param ctx GL context.
+ * \param newstate new state.
+ *
+ * Checks if dd_function_table::NeedFlush is marked to flush current state,
+ * and calls dd_function_table::FlushVertices if so. Marks
+ * __struct gl_contextRec::NewState with \p newstate.
+ */
+#define FLUSH_CURRENT(ctx, newstate) \
+do { \
+ if (MESA_VERBOSE & VERBOSE_STATE) \
+ _mesa_debug(ctx, "FLUSH_CURRENT in %s\n", MESA_FUNCTION); \
+ if (ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT) \
+ ctx->Driver.FlushVertices(ctx, FLUSH_UPDATE_CURRENT); \
+ ctx->NewState |= newstate; \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair, with return value.
+ *
+ * \param ctx GL context.
+ * \param retval value to return value in case the assertion fails.
+ */
+#define ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, retval) \
+do { \
+ if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) { \
+ _mesa_error(ctx, GL_INVALID_OPERATION, "Inside glBegin/glEnd"); \
+ return retval; \
+ } \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair.
+ *
+ * \param ctx GL context.
+ */
+#define ASSERT_OUTSIDE_BEGIN_END(ctx) \
+do { \
+ if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) { \
+ _mesa_error(ctx, GL_INVALID_OPERATION, "Inside glBegin/glEnd"); \
+ return; \
+ } \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair and flush the vertices.
+ *
+ * \param ctx GL context.
+ */
+#define ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx) \
+do { \
+ ASSERT_OUTSIDE_BEGIN_END(ctx); \
+ FLUSH_VERTICES(ctx, 0); \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair and flush the vertices, with return value.
+ *
+ * \param ctx GL context.
+ * \param retval value to return value in case the assertion fails.
+ */
+#define ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH_WITH_RETVAL(ctx, retval) \
+do { \
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, retval); \
+ FLUSH_VERTICES(ctx, 0); \
+} while (0)
+
+/*@}*/
+
+
+
+/**
+ * Is the secondary color needed?
+ */
+#define NEED_SECONDARY_COLOR(CTX) \
+ (((CTX)->Light.Enabled && \
+ (CTX)->Light.Model.ColorControl == GL_SEPARATE_SPECULAR_COLOR) \
+ || (CTX)->Fog.ColorSumEnabled \
+ || ((CTX)->VertexProgram._Current && \
+ ((CTX)->VertexProgram._Current != (CTX)->VertexProgram._TnlProgram) && \
+ ((CTX)->VertexProgram._Current->Base.InputsRead & VERT_BIT_COLOR1)) \
+ || ((CTX)->FragmentProgram._Current && \
+ ((CTX)->FragmentProgram._Current != (CTX)->FragmentProgram._TexEnvProgram) && \
+ ((CTX)->FragmentProgram._Current->Base.InputsRead & FRAG_BIT_COL1)) \
+ )
+
+
+/**
+ * Is RGBA LogicOp enabled?
+ */
+#define RGBA_LOGICOP_ENABLED(CTX) \
+ ((CTX)->Color.ColorLogicOpEnabled || \
+ ((CTX)->Color.BlendEnabled && (CTX)->Color.Blend[0].EquationRGB == GL_LOGIC_OP))
+
+
+#endif /* CONTEXT_H */
diff --git a/mesalib/src/mesa/main/depth.c b/mesalib/src/mesa/main/depth.c
index 52c69a6bc..d666ed5fe 100644
--- a/mesalib/src/mesa/main/depth.c
+++ b/mesalib/src/mesa/main/depth.c
@@ -1,174 +1,174 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.1
- *
- * Copyright (C) 1999-2007 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.
- */
-
-
-#include "glheader.h"
-#include "imports.h"
-#include "context.h"
-#include "depth.h"
-#include "enums.h"
-#include "macros.h"
-#include "mtypes.h"
-
-
-/**********************************************************************/
-/***** API Functions *****/
-/**********************************************************************/
-
-
-
-void GLAPIENTRY
-_mesa_ClearDepth( GLclampd depth )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glClearDepth(%f)\n", depth);
-
- depth = CLAMP( depth, 0.0, 1.0 );
-
- if (ctx->Depth.Clear == depth)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
- ctx->Depth.Clear = depth;
- if (ctx->Driver.ClearDepth)
- (*ctx->Driver.ClearDepth)( ctx, ctx->Depth.Clear );
-}
-
-
-void GLAPIENTRY
-_mesa_ClearDepthf( GLclampf depth )
-{
- _mesa_ClearDepth(depth);
-}
-
-
-void GLAPIENTRY
-_mesa_DepthFunc( GLenum func )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glDepthFunc %s\n", _mesa_lookup_enum_by_nr(func));
-
- switch (func) {
- case GL_LESS: /* (default) pass if incoming z < stored z */
- case GL_GEQUAL:
- case GL_LEQUAL:
- case GL_GREATER:
- case GL_NOTEQUAL:
- case GL_EQUAL:
- case GL_ALWAYS:
- case GL_NEVER:
- break;
- default:
- _mesa_error( ctx, GL_INVALID_ENUM, "glDepth.Func" );
- return;
- }
-
- if (ctx->Depth.Func == func)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
- ctx->Depth.Func = func;
-
- if (ctx->Driver.DepthFunc)
- ctx->Driver.DepthFunc( ctx, func );
-}
-
-
-
-void GLAPIENTRY
-_mesa_DepthMask( GLboolean flag )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glDepthMask %d\n", flag);
-
- /*
- * GL_TRUE indicates depth buffer writing is enabled (default)
- * GL_FALSE indicates depth buffer writing is disabled
- */
- if (ctx->Depth.Mask == flag)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
- ctx->Depth.Mask = flag;
-
- if (ctx->Driver.DepthMask)
- ctx->Driver.DepthMask( ctx, flag );
-}
-
-
-
-/**
- * Specified by the GL_EXT_depth_bounds_test extension.
- */
-void GLAPIENTRY
-_mesa_DepthBoundsEXT( GLclampd zmin, GLclampd zmax )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glDepthBounds(%f, %f)\n", zmin, zmax);
-
- if (zmin > zmax) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glDepthBoundsEXT(zmin > zmax)");
- return;
- }
-
- zmin = CLAMP(zmin, 0.0, 1.0);
- zmax = CLAMP(zmax, 0.0, 1.0);
-
- if (ctx->Depth.BoundsMin == zmin && ctx->Depth.BoundsMax == zmax)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
- ctx->Depth.BoundsMin = (GLfloat) zmin;
- ctx->Depth.BoundsMax = (GLfloat) zmax;
-}
-
-
-/**********************************************************************/
-/***** Initialization *****/
-/**********************************************************************/
-
-
-/**
- * Initialize the depth buffer attribute group in the given context.
- */
-void
-_mesa_init_depth(struct gl_context *ctx)
-{
- ctx->Depth.Test = GL_FALSE;
- ctx->Depth.Clear = 1.0;
- ctx->Depth.Func = GL_LESS;
- ctx->Depth.Mask = GL_TRUE;
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.1
+ *
+ * Copyright (C) 1999-2007 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.
+ */
+
+
+#include "glheader.h"
+#include "imports.h"
+#include "context.h"
+#include "depth.h"
+#include "enums.h"
+#include "macros.h"
+#include "mtypes.h"
+
+
+/**********************************************************************/
+/***** API Functions *****/
+/**********************************************************************/
+
+
+
+void GLAPIENTRY
+_mesa_ClearDepth( GLclampd depth )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glClearDepth(%f)\n", depth);
+
+ depth = CLAMP( depth, 0.0, 1.0 );
+
+ if (ctx->Depth.Clear == depth)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+ ctx->Depth.Clear = depth;
+ if (ctx->Driver.ClearDepth)
+ (*ctx->Driver.ClearDepth)( ctx, ctx->Depth.Clear );
+}
+
+
+void GLAPIENTRY
+_mesa_ClearDepthf( GLclampf depth )
+{
+ _mesa_ClearDepth(depth);
+}
+
+
+void GLAPIENTRY
+_mesa_DepthFunc( GLenum func )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glDepthFunc %s\n", _mesa_lookup_enum_by_nr(func));
+
+ switch (func) {
+ case GL_LESS: /* (default) pass if incoming z < stored z */
+ case GL_GEQUAL:
+ case GL_LEQUAL:
+ case GL_GREATER:
+ case GL_NOTEQUAL:
+ case GL_EQUAL:
+ case GL_ALWAYS:
+ case GL_NEVER:
+ break;
+ default:
+ _mesa_error( ctx, GL_INVALID_ENUM, "glDepth.Func" );
+ return;
+ }
+
+ if (ctx->Depth.Func == func)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+ ctx->Depth.Func = func;
+
+ if (ctx->Driver.DepthFunc)
+ ctx->Driver.DepthFunc( ctx, func );
+}
+
+
+
+void GLAPIENTRY
+_mesa_DepthMask( GLboolean flag )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glDepthMask %d\n", flag);
+
+ /*
+ * GL_TRUE indicates depth buffer writing is enabled (default)
+ * GL_FALSE indicates depth buffer writing is disabled
+ */
+ if (ctx->Depth.Mask == flag)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+ ctx->Depth.Mask = flag;
+
+ if (ctx->Driver.DepthMask)
+ ctx->Driver.DepthMask( ctx, flag );
+}
+
+
+
+/**
+ * Specified by the GL_EXT_depth_bounds_test extension.
+ */
+void GLAPIENTRY
+_mesa_DepthBoundsEXT( GLclampd zmin, GLclampd zmax )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glDepthBounds(%f, %f)\n", zmin, zmax);
+
+ if (zmin > zmax) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glDepthBoundsEXT(zmin > zmax)");
+ return;
+ }
+
+ zmin = CLAMP(zmin, 0.0, 1.0);
+ zmax = CLAMP(zmax, 0.0, 1.0);
+
+ if (ctx->Depth.BoundsMin == zmin && ctx->Depth.BoundsMax == zmax)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+ ctx->Depth.BoundsMin = (GLfloat) zmin;
+ ctx->Depth.BoundsMax = (GLfloat) zmax;
+}
+
+
+/**********************************************************************/
+/***** Initialization *****/
+/**********************************************************************/
+
+
+/**
+ * Initialize the depth buffer attribute group in the given context.
+ */
+void
+_mesa_init_depth(struct gl_context *ctx)
+{
+ ctx->Depth.Test = GL_FALSE;
+ ctx->Depth.Clear = 1.0;
+ ctx->Depth.Func = GL_LESS;
+ ctx->Depth.Mask = GL_TRUE;
+}
diff --git a/mesalib/src/mesa/main/dlist.c b/mesalib/src/mesa/main/dlist.c
index 8e904c778..569a7d9ca 100644
--- a/mesalib/src/mesa/main/dlist.c
+++ b/mesalib/src/mesa/main/dlist.c
@@ -1,10332 +1,10332 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.7
- *
- * Copyright (C) 1999-2008 Brian Paul All Rights Reserved.
- * Copyright (C) 2009 VMware, Inc. 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 dlist.c
- * Display lists management functions.
- */
-
-#include "glheader.h"
-#include "imports.h"
-#include "api_arrayelt.h"
-#include "api_exec.h"
-#include "api_loopback.h"
-#if FEATURE_ATI_fragment_shader
-#include "atifragshader.h"
-#endif
-#include "config.h"
-#include "mfeatures.h"
-#if FEATURE_ARB_vertex_buffer_object
-#include "bufferobj.h"
-#endif
-#include "arrayobj.h"
-#include "context.h"
-#include "dlist.h"
-#include "enums.h"
-#include "eval.h"
-#include "framebuffer.h"
-#include "glapi/glapi.h"
-#include "hash.h"
-#include "image.h"
-#include "light.h"
-#include "macros.h"
-#include "pack.h"
-#include "queryobj.h"
-#include "teximage.h"
-#include "mtypes.h"
-#include "varray.h"
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
-#include "arbprogram.h"
-#endif
-#if FEATURE_NV_vertex_program || FEATURE_NV_fragment_program
-#include "nvprogram.h"
-#endif
-
-#include "math/m_matrix.h"
-
-#include "main/dispatch.h"
-
-
-
-/**
- * Other parts of Mesa (such as the VBO module) can plug into the display
- * list system. This structure describes new display list instructions.
- */
-struct gl_list_instruction
-{
- GLuint Size;
- void (*Execute)( struct gl_context *ctx, void *data );
- void (*Destroy)( struct gl_context *ctx, void *data );
- void (*Print)( struct gl_context *ctx, void *data );
-};
-
-
-#define MAX_DLIST_EXT_OPCODES 16
-
-/**
- * Used by device drivers to hook new commands into display lists.
- */
-struct gl_list_extensions
-{
- struct gl_list_instruction Opcode[MAX_DLIST_EXT_OPCODES];
- GLuint NumOpcodes;
-};
-
-
-
-/**
- * Flush vertices.
- *
- * \param ctx GL context.
- *
- * Checks if dd_function_table::SaveNeedFlush is marked to flush
- * stored (save) vertices, and calls
- * dd_function_table::SaveFlushVertices if so.
- */
-#define SAVE_FLUSH_VERTICES(ctx) \
-do { \
- if (ctx->Driver.SaveNeedFlush) \
- ctx->Driver.SaveFlushVertices(ctx); \
-} while (0)
-
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair, with return value.
- *
- * \param ctx GL context.
- * \param retval value to return value in case the assertion fails.
- */
-#define ASSERT_OUTSIDE_SAVE_BEGIN_END_WITH_RETVAL(ctx, retval) \
-do { \
- if (ctx->Driver.CurrentSavePrimitive <= GL_POLYGON || \
- ctx->Driver.CurrentSavePrimitive == PRIM_INSIDE_UNKNOWN_PRIM) { \
- _mesa_compile_error( ctx, GL_INVALID_OPERATION, "begin/end" ); \
- return retval; \
- } \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair.
- *
- * \param ctx GL context.
- */
-#define ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx) \
-do { \
- if (ctx->Driver.CurrentSavePrimitive <= GL_POLYGON || \
- ctx->Driver.CurrentSavePrimitive == PRIM_INSIDE_UNKNOWN_PRIM) { \
- _mesa_compile_error( ctx, GL_INVALID_OPERATION, "begin/end" ); \
- return; \
- } \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair and flush the vertices.
- *
- * \param ctx GL context.
- */
-#define ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx) \
-do { \
- ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx); \
- SAVE_FLUSH_VERTICES(ctx); \
-} while (0)
-
-/**
- * Macro to assert that the API call was made outside the
- * glBegin()/glEnd() pair and flush the vertices, with return value.
- *
- * \param ctx GL context.
- * \param retval value to return value in case the assertion fails.
- */
-#define ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH_WITH_RETVAL(ctx, retval)\
-do { \
- ASSERT_OUTSIDE_SAVE_BEGIN_END_WITH_RETVAL(ctx, retval); \
- SAVE_FLUSH_VERTICES(ctx); \
-} while (0)
-
-
-
-/**
- * Display list opcodes.
- *
- * The fact that these identifiers are assigned consecutive
- * integer values starting at 0 is very important, see InstSize array usage)
- */
-typedef enum
-{
- OPCODE_INVALID = -1, /* Force signed enum */
- OPCODE_ACCUM,
- OPCODE_ALPHA_FUNC,
- OPCODE_BIND_TEXTURE,
- OPCODE_BITMAP,
- OPCODE_BLEND_COLOR,
- OPCODE_BLEND_EQUATION,
- OPCODE_BLEND_EQUATION_SEPARATE,
- OPCODE_BLEND_FUNC_SEPARATE,
-
- OPCODE_BLEND_EQUATION_I,
- OPCODE_BLEND_EQUATION_SEPARATE_I,
- OPCODE_BLEND_FUNC_I,
- OPCODE_BLEND_FUNC_SEPARATE_I,
-
- OPCODE_CALL_LIST,
- OPCODE_CALL_LIST_OFFSET,
- OPCODE_CLEAR,
- OPCODE_CLEAR_ACCUM,
- OPCODE_CLEAR_COLOR,
- OPCODE_CLEAR_DEPTH,
- OPCODE_CLEAR_INDEX,
- OPCODE_CLEAR_STENCIL,
- OPCODE_CLEAR_BUFFER_IV,
- OPCODE_CLEAR_BUFFER_UIV,
- OPCODE_CLEAR_BUFFER_FV,
- OPCODE_CLEAR_BUFFER_FI,
- OPCODE_CLIP_PLANE,
- OPCODE_COLOR_MASK,
- OPCODE_COLOR_MASK_INDEXED,
- OPCODE_COLOR_MATERIAL,
- OPCODE_COLOR_TABLE,
- OPCODE_COLOR_TABLE_PARAMETER_FV,
- OPCODE_COLOR_TABLE_PARAMETER_IV,
- OPCODE_COLOR_SUB_TABLE,
- OPCODE_CONVOLUTION_FILTER_1D,
- OPCODE_CONVOLUTION_FILTER_2D,
- OPCODE_CONVOLUTION_PARAMETER_I,
- OPCODE_CONVOLUTION_PARAMETER_IV,
- OPCODE_CONVOLUTION_PARAMETER_F,
- OPCODE_CONVOLUTION_PARAMETER_FV,
- OPCODE_COPY_COLOR_SUB_TABLE,
- OPCODE_COPY_COLOR_TABLE,
- OPCODE_COPY_PIXELS,
- OPCODE_COPY_TEX_IMAGE1D,
- OPCODE_COPY_TEX_IMAGE2D,
- OPCODE_COPY_TEX_SUB_IMAGE1D,
- OPCODE_COPY_TEX_SUB_IMAGE2D,
- OPCODE_COPY_TEX_SUB_IMAGE3D,
- OPCODE_CULL_FACE,
- OPCODE_DEPTH_FUNC,
- OPCODE_DEPTH_MASK,
- OPCODE_DEPTH_RANGE,
- OPCODE_DISABLE,
- OPCODE_DISABLE_INDEXED,
- OPCODE_DRAW_BUFFER,
- OPCODE_DRAW_PIXELS,
- OPCODE_ENABLE,
- OPCODE_ENABLE_INDEXED,
- OPCODE_EVALMESH1,
- OPCODE_EVALMESH2,
- OPCODE_FOG,
- OPCODE_FRONT_FACE,
- OPCODE_FRUSTUM,
- OPCODE_HINT,
- OPCODE_HISTOGRAM,
- OPCODE_INDEX_MASK,
- OPCODE_INIT_NAMES,
- OPCODE_LIGHT,
- OPCODE_LIGHT_MODEL,
- OPCODE_LINE_STIPPLE,
- OPCODE_LINE_WIDTH,
- OPCODE_LIST_BASE,
- OPCODE_LOAD_IDENTITY,
- OPCODE_LOAD_MATRIX,
- OPCODE_LOAD_NAME,
- OPCODE_LOGIC_OP,
- OPCODE_MAP1,
- OPCODE_MAP2,
- OPCODE_MAPGRID1,
- OPCODE_MAPGRID2,
- OPCODE_MATRIX_MODE,
- OPCODE_MIN_MAX,
- OPCODE_MULT_MATRIX,
- OPCODE_ORTHO,
- OPCODE_PASSTHROUGH,
- OPCODE_PIXEL_MAP,
- OPCODE_PIXEL_TRANSFER,
- OPCODE_PIXEL_ZOOM,
- OPCODE_POINT_SIZE,
- OPCODE_POINT_PARAMETERS,
- OPCODE_POLYGON_MODE,
- OPCODE_POLYGON_STIPPLE,
- OPCODE_POLYGON_OFFSET,
- OPCODE_POP_ATTRIB,
- OPCODE_POP_MATRIX,
- OPCODE_POP_NAME,
- OPCODE_PRIORITIZE_TEXTURE,
- OPCODE_PUSH_ATTRIB,
- OPCODE_PUSH_MATRIX,
- OPCODE_PUSH_NAME,
- OPCODE_RASTER_POS,
- OPCODE_READ_BUFFER,
- OPCODE_RESET_HISTOGRAM,
- OPCODE_RESET_MIN_MAX,
- OPCODE_ROTATE,
- OPCODE_SCALE,
- OPCODE_SCISSOR,
- OPCODE_SELECT_TEXTURE_SGIS,
- OPCODE_SELECT_TEXTURE_COORD_SET,
- OPCODE_SHADE_MODEL,
- OPCODE_STENCIL_FUNC,
- OPCODE_STENCIL_MASK,
- OPCODE_STENCIL_OP,
- OPCODE_TEXENV,
- OPCODE_TEXGEN,
- OPCODE_TEXPARAMETER,
- OPCODE_TEX_IMAGE1D,
- OPCODE_TEX_IMAGE2D,
- OPCODE_TEX_IMAGE3D,
- OPCODE_TEX_SUB_IMAGE1D,
- OPCODE_TEX_SUB_IMAGE2D,
- OPCODE_TEX_SUB_IMAGE3D,
- OPCODE_TRANSLATE,
- OPCODE_VIEWPORT,
- OPCODE_WINDOW_POS,
- /* GL_ARB_multitexture */
- OPCODE_ACTIVE_TEXTURE,
- /* GL_ARB_texture_compression */
- OPCODE_COMPRESSED_TEX_IMAGE_1D,
- OPCODE_COMPRESSED_TEX_IMAGE_2D,
- OPCODE_COMPRESSED_TEX_IMAGE_3D,
- OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D,
- OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D,
- OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D,
- /* GL_ARB_multisample */
- OPCODE_SAMPLE_COVERAGE,
- /* GL_ARB_window_pos */
- OPCODE_WINDOW_POS_ARB,
- /* GL_NV_vertex_program */
- OPCODE_BIND_PROGRAM_NV,
- OPCODE_EXECUTE_PROGRAM_NV,
- OPCODE_REQUEST_RESIDENT_PROGRAMS_NV,
- OPCODE_LOAD_PROGRAM_NV,
- OPCODE_TRACK_MATRIX_NV,
- /* GL_NV_fragment_program */
- OPCODE_PROGRAM_LOCAL_PARAMETER_ARB,
- OPCODE_PROGRAM_NAMED_PARAMETER_NV,
- /* GL_EXT_stencil_two_side */
- OPCODE_ACTIVE_STENCIL_FACE_EXT,
- /* GL_EXT_depth_bounds_test */
- OPCODE_DEPTH_BOUNDS_EXT,
- /* GL_ARB_vertex/fragment_program */
- OPCODE_PROGRAM_STRING_ARB,
- OPCODE_PROGRAM_ENV_PARAMETER_ARB,
- /* GL_ARB_occlusion_query */
- OPCODE_BEGIN_QUERY_ARB,
- OPCODE_END_QUERY_ARB,
- /* GL_ARB_draw_buffers */
- OPCODE_DRAW_BUFFERS_ARB,
- /* GL_ATI_fragment_shader */
- OPCODE_TEX_BUMP_PARAMETER_ATI,
- /* GL_ATI_fragment_shader */
- OPCODE_BIND_FRAGMENT_SHADER_ATI,
- OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI,
- /* OpenGL 2.0 */
- OPCODE_STENCIL_FUNC_SEPARATE,
- OPCODE_STENCIL_OP_SEPARATE,
- OPCODE_STENCIL_MASK_SEPARATE,
-
- /* GL_ARB_shader_objects */
- OPCODE_USE_PROGRAM,
- OPCODE_UNIFORM_1F,
- OPCODE_UNIFORM_2F,
- OPCODE_UNIFORM_3F,
- OPCODE_UNIFORM_4F,
- OPCODE_UNIFORM_1FV,
- OPCODE_UNIFORM_2FV,
- OPCODE_UNIFORM_3FV,
- OPCODE_UNIFORM_4FV,
- OPCODE_UNIFORM_1I,
- OPCODE_UNIFORM_2I,
- OPCODE_UNIFORM_3I,
- OPCODE_UNIFORM_4I,
- OPCODE_UNIFORM_1IV,
- OPCODE_UNIFORM_2IV,
- OPCODE_UNIFORM_3IV,
- OPCODE_UNIFORM_4IV,
- OPCODE_UNIFORM_MATRIX22,
- OPCODE_UNIFORM_MATRIX33,
- OPCODE_UNIFORM_MATRIX44,
- OPCODE_UNIFORM_MATRIX23,
- OPCODE_UNIFORM_MATRIX32,
- OPCODE_UNIFORM_MATRIX24,
- OPCODE_UNIFORM_MATRIX42,
- OPCODE_UNIFORM_MATRIX34,
- OPCODE_UNIFORM_MATRIX43,
-
- /* OpenGL 3.0 */
- OPCODE_UNIFORM_1UI,
- OPCODE_UNIFORM_2UI,
- OPCODE_UNIFORM_3UI,
- OPCODE_UNIFORM_4UI,
- OPCODE_UNIFORM_1UIV,
- OPCODE_UNIFORM_2UIV,
- OPCODE_UNIFORM_3UIV,
- OPCODE_UNIFORM_4UIV,
-
- /* GL_EXT_framebuffer_blit */
- OPCODE_BLIT_FRAMEBUFFER,
-
- /* Vertex attributes -- fallback for when optimized display
- * list build isn't active.
- */
- OPCODE_ATTR_1F_NV,
- OPCODE_ATTR_2F_NV,
- OPCODE_ATTR_3F_NV,
- OPCODE_ATTR_4F_NV,
- OPCODE_ATTR_1F_ARB,
- OPCODE_ATTR_2F_ARB,
- OPCODE_ATTR_3F_ARB,
- OPCODE_ATTR_4F_ARB,
- OPCODE_MATERIAL,
- OPCODE_BEGIN,
- OPCODE_END,
- OPCODE_RECTF,
- OPCODE_EVAL_C1,
- OPCODE_EVAL_C2,
- OPCODE_EVAL_P1,
- OPCODE_EVAL_P2,
-
- /* GL_EXT_provoking_vertex */
- OPCODE_PROVOKING_VERTEX,
-
- /* GL_EXT_transform_feedback */
- OPCODE_BEGIN_TRANSFORM_FEEDBACK,
- OPCODE_END_TRANSFORM_FEEDBACK,
-
- /* GL_EXT_texture_integer */
- OPCODE_CLEARCOLOR_I,
- OPCODE_CLEARCOLOR_UI,
- OPCODE_TEXPARAMETER_I,
- OPCODE_TEXPARAMETER_UI,
-
- /* GL_EXT_separate_shader_objects */
- OPCODE_ACTIVE_PROGRAM_EXT,
- OPCODE_USE_SHADER_PROGRAM_EXT,
-
- /* GL_ARB_instanced_arrays */
- OPCODE_VERTEX_ATTRIB_DIVISOR,
-
- /* The following three are meta instructions */
- OPCODE_ERROR, /* raise compiled-in error */
- OPCODE_CONTINUE,
- OPCODE_END_OF_LIST,
- OPCODE_EXT_0
-} OpCode;
-
-
-
-/**
- * Display list node.
- *
- * Display list instructions are stored as sequences of "nodes". Nodes
- * are allocated in blocks. Each block has BLOCK_SIZE nodes. Blocks
- * are linked together with a pointer.
- *
- * Each instruction in the display list is stored as a sequence of
- * contiguous nodes in memory.
- * Each node is the union of a variety of data types.
- */
-union gl_dlist_node
-{
- OpCode opcode;
- GLboolean b;
- GLbitfield bf;
- GLubyte ub;
- GLshort s;
- GLushort us;
- GLint i;
- GLuint ui;
- GLenum e;
- GLfloat f;
- GLvoid *data;
- void *next; /* If prev node's opcode==OPCODE_CONTINUE */
-};
-
-
-typedef union gl_dlist_node Node;
-
-
-/**
- * How many nodes to allocate at a time.
- *
- * \note Reduced now that we hold vertices etc. elsewhere.
- */
-#define BLOCK_SIZE 256
-
-
-
-/**
- * Number of nodes of storage needed for each instruction.
- * Sizes for dynamically allocated opcodes are stored in the context struct.
- */
-static GLuint InstSize[OPCODE_END_OF_LIST + 1];
-
-
-#if FEATURE_dlist
-
-
-void mesa_print_display_list(GLuint list);
-
-
-/**********************************************************************/
-/***** Private *****/
-/**********************************************************************/
-
-
-/**
- * Make an empty display list. This is used by glGenLists() to
- * reserve display list IDs.
- */
-static struct gl_display_list *
-make_list(GLuint name, GLuint count)
-{
- struct gl_display_list *dlist = CALLOC_STRUCT(gl_display_list);
- dlist->Name = name;
- dlist->Head = (Node *) malloc(sizeof(Node) * count);
- dlist->Head[0].opcode = OPCODE_END_OF_LIST;
- return dlist;
-}
-
-
-/**
- * Lookup function to just encapsulate casting.
- */
-static INLINE struct gl_display_list *
-lookup_list(struct gl_context *ctx, GLuint list)
-{
- return (struct gl_display_list *)
- _mesa_HashLookup(ctx->Shared->DisplayList, list);
-}
-
-
-/** Is the given opcode an extension code? */
-static INLINE GLboolean
-is_ext_opcode(OpCode opcode)
-{
- return (opcode >= OPCODE_EXT_0);
-}
-
-
-/** Destroy an extended opcode instruction */
-static GLint
-ext_opcode_destroy(struct gl_context *ctx, Node *node)
-{
- const GLint i = node[0].opcode - OPCODE_EXT_0;
- GLint step;
- ctx->ListExt->Opcode[i].Destroy(ctx, &node[1]);
- step = ctx->ListExt->Opcode[i].Size;
- return step;
-}
-
-
-/** Execute an extended opcode instruction */
-static GLint
-ext_opcode_execute(struct gl_context *ctx, Node *node)
-{
- const GLint i = node[0].opcode - OPCODE_EXT_0;
- GLint step;
- ctx->ListExt->Opcode[i].Execute(ctx, &node[1]);
- step = ctx->ListExt->Opcode[i].Size;
- return step;
-}
-
-
-/** Print an extended opcode instruction */
-static GLint
-ext_opcode_print(struct gl_context *ctx, Node *node)
-{
- const GLint i = node[0].opcode - OPCODE_EXT_0;
- GLint step;
- ctx->ListExt->Opcode[i].Print(ctx, &node[1]);
- step = ctx->ListExt->Opcode[i].Size;
- return step;
-}
-
-
-/**
- * Delete the named display list, but don't remove from hash table.
- * \param dlist - display list pointer
- */
-void
-_mesa_delete_list(struct gl_context *ctx, struct gl_display_list *dlist)
-{
- Node *n, *block;
- GLboolean done;
-
- n = block = dlist->Head;
-
- done = block ? GL_FALSE : GL_TRUE;
- while (!done) {
- const OpCode opcode = n[0].opcode;
-
- /* check for extension opcodes first */
- if (is_ext_opcode(opcode)) {
- n += ext_opcode_destroy(ctx, n);
- }
- else {
- switch (opcode) {
- /* for some commands, we need to free malloc'd memory */
- case OPCODE_MAP1:
- free(n[6].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_MAP2:
- free(n[10].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_DRAW_PIXELS:
- free(n[5].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_BITMAP:
- free(n[7].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COLOR_TABLE:
- free(n[6].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COLOR_SUB_TABLE:
- free(n[6].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_CONVOLUTION_FILTER_1D:
- free(n[6].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_CONVOLUTION_FILTER_2D:
- free(n[7].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_POLYGON_STIPPLE:
- free(n[1].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_IMAGE1D:
- free(n[8].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_IMAGE2D:
- free(n[9].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_IMAGE3D:
- free(n[10].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_SUB_IMAGE1D:
- free(n[7].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_SUB_IMAGE2D:
- free(n[9].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_TEX_SUB_IMAGE3D:
- free(n[11].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_1D:
- free(n[7].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_2D:
- free(n[8].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_3D:
- free(n[9].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D:
- free(n[7].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D:
- free(n[9].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D:
- free(n[11].data);
- n += InstSize[n[0].opcode];
- break;
-#if FEATURE_NV_vertex_program
- case OPCODE_LOAD_PROGRAM_NV:
- free(n[4].data); /* program string */
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_REQUEST_RESIDENT_PROGRAMS_NV:
- free(n[2].data); /* array of program ids */
- n += InstSize[n[0].opcode];
- break;
-#endif
-#if FEATURE_NV_fragment_program
- case OPCODE_PROGRAM_NAMED_PARAMETER_NV:
- free(n[3].data); /* parameter name */
- n += InstSize[n[0].opcode];
- break;
-#endif
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
- case OPCODE_PROGRAM_STRING_ARB:
- free(n[4].data); /* program string */
- n += InstSize[n[0].opcode];
- break;
-#endif
- case OPCODE_UNIFORM_1FV:
- case OPCODE_UNIFORM_2FV:
- case OPCODE_UNIFORM_3FV:
- case OPCODE_UNIFORM_4FV:
- case OPCODE_UNIFORM_1IV:
- case OPCODE_UNIFORM_2IV:
- case OPCODE_UNIFORM_3IV:
- case OPCODE_UNIFORM_4IV:
- case OPCODE_UNIFORM_1UIV:
- case OPCODE_UNIFORM_2UIV:
- case OPCODE_UNIFORM_3UIV:
- case OPCODE_UNIFORM_4UIV:
- free(n[3].data);
- n += InstSize[n[0].opcode];
- break;
- case OPCODE_UNIFORM_MATRIX22:
- case OPCODE_UNIFORM_MATRIX33:
- case OPCODE_UNIFORM_MATRIX44:
- case OPCODE_UNIFORM_MATRIX24:
- case OPCODE_UNIFORM_MATRIX42:
- case OPCODE_UNIFORM_MATRIX23:
- case OPCODE_UNIFORM_MATRIX32:
- case OPCODE_UNIFORM_MATRIX34:
- case OPCODE_UNIFORM_MATRIX43:
- free(n[4].data);
- n += InstSize[n[0].opcode];
- break;
-
- case OPCODE_CONTINUE:
- n = (Node *) n[1].next;
- free(block);
- block = n;
- break;
- case OPCODE_END_OF_LIST:
- free(block);
- done = GL_TRUE;
- break;
- default:
- /* Most frequent case */
- n += InstSize[n[0].opcode];
- break;
- }
- }
- }
-
- free(dlist);
-}
-
-
-/**
- * Destroy a display list and remove from hash table.
- * \param list - display list number
- */
-static void
-destroy_list(struct gl_context *ctx, GLuint list)
-{
- struct gl_display_list *dlist;
-
- if (list == 0)
- return;
-
- dlist = lookup_list(ctx, list);
- if (!dlist)
- return;
-
- _mesa_delete_list(ctx, dlist);
- _mesa_HashRemove(ctx->Shared->DisplayList, list);
-}
-
-
-/*
- * Translate the nth element of list from <type> to GLint.
- */
-static GLint
-translate_id(GLsizei n, GLenum type, const GLvoid * list)
-{
- GLbyte *bptr;
- GLubyte *ubptr;
- GLshort *sptr;
- GLushort *usptr;
- GLint *iptr;
- GLuint *uiptr;
- GLfloat *fptr;
-
- switch (type) {
- case GL_BYTE:
- bptr = (GLbyte *) list;
- return (GLint) bptr[n];
- case GL_UNSIGNED_BYTE:
- ubptr = (GLubyte *) list;
- return (GLint) ubptr[n];
- case GL_SHORT:
- sptr = (GLshort *) list;
- return (GLint) sptr[n];
- case GL_UNSIGNED_SHORT:
- usptr = (GLushort *) list;
- return (GLint) usptr[n];
- case GL_INT:
- iptr = (GLint *) list;
- return iptr[n];
- case GL_UNSIGNED_INT:
- uiptr = (GLuint *) list;
- return (GLint) uiptr[n];
- case GL_FLOAT:
- fptr = (GLfloat *) list;
- return (GLint) FLOORF(fptr[n]);
- case GL_2_BYTES:
- ubptr = ((GLubyte *) list) + 2 * n;
- return (GLint) ubptr[0] * 256
- + (GLint) ubptr[1];
- case GL_3_BYTES:
- ubptr = ((GLubyte *) list) + 3 * n;
- return (GLint) ubptr[0] * 65536
- + (GLint) ubptr[1] * 256
- + (GLint) ubptr[2];
- case GL_4_BYTES:
- ubptr = ((GLubyte *) list) + 4 * n;
- return (GLint) ubptr[0] * 16777216
- + (GLint) ubptr[1] * 65536
- + (GLint) ubptr[2] * 256
- + (GLint) ubptr[3];
- default:
- return 0;
- }
-}
-
-
-
-
-/**********************************************************************/
-/***** Public *****/
-/**********************************************************************/
-
-/**
- * Wrapper for _mesa_unpack_image() that handles pixel buffer objects.
- * If we run out of memory, GL_OUT_OF_MEMORY will be recorded.
- */
-static GLvoid *
-unpack_image(struct gl_context *ctx, GLuint dimensions,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid * pixels,
- const struct gl_pixelstore_attrib *unpack)
-{
- if (!_mesa_is_bufferobj(unpack->BufferObj)) {
- /* no PBO */
- GLvoid *image = _mesa_unpack_image(dimensions, width, height, depth,
- format, type, pixels, unpack);
- if (pixels && !image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "display list construction");
- }
- return image;
- }
- else if (_mesa_validate_pbo_access(dimensions, unpack, width, height, depth,
- format, type, pixels)) {
- const GLubyte *map, *src;
- GLvoid *image;
-
- map = (GLubyte *)
- ctx->Driver.MapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
- GL_READ_ONLY_ARB, unpack->BufferObj);
- if (!map) {
- /* unable to map src buffer! */
- _mesa_error(ctx, GL_INVALID_OPERATION, "unable to map PBO");
- return NULL;
- }
-
- src = ADD_POINTERS(map, pixels);
- image = _mesa_unpack_image(dimensions, width, height, depth,
- format, type, src, unpack);
-
- ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
- unpack->BufferObj);
-
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "display list construction");
- }
- return image;
- }
- /* bad access! */
- return NULL;
-}
-
-
-/**
- * Allocate space for a display list instruction (opcode + payload space).
- * \param opcode the instruction opcode (OPCODE_* value)
- * \param bytes instruction payload size (not counting opcode)
- * \return pointer to allocated memory (the opcode space)
- */
-static Node *
-dlist_alloc(struct gl_context *ctx, OpCode opcode, GLuint bytes)
-{
- const GLuint numNodes = 1 + (bytes + sizeof(Node) - 1) / sizeof(Node);
- Node *n;
-
- if (opcode < (GLuint) OPCODE_EXT_0) {
- if (InstSize[opcode] == 0) {
- /* save instruction size now */
- InstSize[opcode] = numNodes;
- }
- else {
- /* make sure instruction size agrees */
- ASSERT(numNodes == InstSize[opcode]);
- }
- }
-
- if (ctx->ListState.CurrentPos + numNodes + 2 > BLOCK_SIZE) {
- /* This block is full. Allocate a new block and chain to it */
- Node *newblock;
- n = ctx->ListState.CurrentBlock + ctx->ListState.CurrentPos;
- n[0].opcode = OPCODE_CONTINUE;
- newblock = (Node *) malloc(sizeof(Node) * BLOCK_SIZE);
- if (!newblock) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "Building display list");
- return NULL;
- }
- n[1].next = (Node *) newblock;
- ctx->ListState.CurrentBlock = newblock;
- ctx->ListState.CurrentPos = 0;
- }
-
- n = ctx->ListState.CurrentBlock + ctx->ListState.CurrentPos;
- ctx->ListState.CurrentPos += numNodes;
-
- n[0].opcode = opcode;
-
- return n;
-}
-
-
-
-/**
- * Allocate space for a display list instruction. Used by callers outside
- * this file for things like VBO vertex data.
- *
- * \param opcode the instruction opcode (OPCODE_* value)
- * \param bytes instruction size in bytes, not counting opcode.
- * \return pointer to the usable data area (not including the internal
- * opcode).
- */
-void *
-_mesa_dlist_alloc(struct gl_context *ctx, GLuint opcode, GLuint bytes)
-{
- Node *n = dlist_alloc(ctx, (OpCode) opcode, bytes);
- if (n)
- return n + 1; /* return pointer to payload area, after opcode */
- else
- return NULL;
-}
-
-
-/**
- * This function allows modules and drivers to get their own opcodes
- * for extending display list functionality.
- * \param ctx the rendering context
- * \param size number of bytes for storing the new display list command
- * \param execute function to execute the new display list command
- * \param destroy function to destroy the new display list command
- * \param print function to print the new display list command
- * \return the new opcode number or -1 if error
- */
-GLint
-_mesa_dlist_alloc_opcode(struct gl_context *ctx,
- GLuint size,
- void (*execute) (struct gl_context *, void *),
- void (*destroy) (struct gl_context *, void *),
- void (*print) (struct gl_context *, void *))
-{
- if (ctx->ListExt->NumOpcodes < MAX_DLIST_EXT_OPCODES) {
- const GLuint i = ctx->ListExt->NumOpcodes++;
- ctx->ListExt->Opcode[i].Size =
- 1 + (size + sizeof(Node) - 1) / sizeof(Node);
- ctx->ListExt->Opcode[i].Execute = execute;
- ctx->ListExt->Opcode[i].Destroy = destroy;
- ctx->ListExt->Opcode[i].Print = print;
- return i + OPCODE_EXT_0;
- }
- return -1;
-}
-
-
-/**
- * Allocate space for a display list instruction. The space is basically
- * an array of Nodes where node[0] holds the opcode, node[1] is the first
- * function parameter, node[2] is the second parameter, etc.
- *
- * \param opcode one of OPCODE_x
- * \param nparams number of function parameters
- * \return pointer to start of instruction space
- */
-static INLINE Node *
-alloc_instruction(struct gl_context *ctx, OpCode opcode, GLuint nparams)
-{
- return dlist_alloc(ctx, opcode, nparams * sizeof(Node));
-}
-
-
-
-/*
- * Display List compilation functions
- */
-static void GLAPIENTRY
-save_Accum(GLenum op, GLfloat value)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ACCUM, 2);
- if (n) {
- n[1].e = op;
- n[2].f = value;
- }
- if (ctx->ExecuteFlag) {
- CALL_Accum(ctx->Exec, (op, value));
- }
-}
-
-
-static void GLAPIENTRY
-save_AlphaFunc(GLenum func, GLclampf ref)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ALPHA_FUNC, 2);
- if (n) {
- n[1].e = func;
- n[2].f = (GLfloat) ref;
- }
- if (ctx->ExecuteFlag) {
- CALL_AlphaFunc(ctx->Exec, (func, ref));
- }
-}
-
-
-static void GLAPIENTRY
-save_BindTexture(GLenum target, GLuint texture)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BIND_TEXTURE, 2);
- if (n) {
- n[1].e = target;
- n[2].ui = texture;
- }
- if (ctx->ExecuteFlag) {
- CALL_BindTexture(ctx->Exec, (target, texture));
- }
-}
-
-
-static void GLAPIENTRY
-save_Bitmap(GLsizei width, GLsizei height,
- GLfloat xorig, GLfloat yorig,
- GLfloat xmove, GLfloat ymove, const GLubyte * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BITMAP, 7);
- if (n) {
- n[1].i = (GLint) width;
- n[2].i = (GLint) height;
- n[3].f = xorig;
- n[4].f = yorig;
- n[5].f = xmove;
- n[6].f = ymove;
- n[7].data = _mesa_unpack_bitmap(width, height, pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_Bitmap(ctx->Exec, (width, height,
- xorig, yorig, xmove, ymove, pixels));
- }
-}
-
-
-static void GLAPIENTRY
-save_BlendEquation(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendEquation(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_BlendEquationSeparateEXT(GLenum modeRGB, GLenum modeA)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_SEPARATE, 2);
- if (n) {
- n[1].e = modeRGB;
- n[2].e = modeA;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendEquationSeparateEXT(ctx->Exec, (modeRGB, modeA));
- }
-}
-
-
-static void GLAPIENTRY
-save_BlendFuncSeparateEXT(GLenum sfactorRGB, GLenum dfactorRGB,
- GLenum sfactorA, GLenum dfactorA)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE, 4);
- if (n) {
- n[1].e = sfactorRGB;
- n[2].e = dfactorRGB;
- n[3].e = sfactorA;
- n[4].e = dfactorA;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendFuncSeparateEXT(ctx->Exec,
- (sfactorRGB, dfactorRGB, sfactorA, dfactorA));
- }
-}
-
-
-static void GLAPIENTRY
-save_BlendFunc(GLenum srcfactor, GLenum dstfactor)
-{
- save_BlendFuncSeparateEXT(srcfactor, dstfactor, srcfactor, dstfactor);
-}
-
-
-static void GLAPIENTRY
-save_BlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_COLOR, 4);
- if (n) {
- n[1].f = red;
- n[2].f = green;
- n[3].f = blue;
- n[4].f = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendColor(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-/* GL_ARB_draw_buffers_blend */
-static void GLAPIENTRY
-save_BlendFuncSeparatei(GLuint buf, GLenum sfactorRGB, GLenum dfactorRGB,
- GLenum sfactorA, GLenum dfactorA)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE_I, 5);
- if (n) {
- n[1].ui = buf;
- n[2].e = sfactorRGB;
- n[3].e = dfactorRGB;
- n[4].e = sfactorA;
- n[5].e = dfactorA;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendFuncSeparateiARB(ctx->Exec, (buf, sfactorRGB, dfactorRGB,
- sfactorA, dfactorA));
- }
-}
-
-/* GL_ARB_draw_buffers_blend */
-static void GLAPIENTRY
-save_BlendFunci(GLuint buf, GLenum sfactor, GLenum dfactor)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE_I, 3);
- if (n) {
- n[1].ui = buf;
- n[2].e = sfactor;
- n[3].e = dfactor;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendFunciARB(ctx->Exec, (buf, sfactor, dfactor));
- }
-}
-
-/* GL_ARB_draw_buffers_blend */
-static void GLAPIENTRY
-save_BlendEquationi(GLuint buf, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_I, 2);
- if (n) {
- n[1].ui = buf;
- n[2].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendEquationiARB(ctx->Exec, (buf, mode));
- }
-}
-
-/* GL_ARB_draw_buffers_blend */
-static void GLAPIENTRY
-save_BlendEquationSeparatei(GLuint buf, GLenum modeRGB, GLenum modeA)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_SEPARATE_I, 3);
- if (n) {
- n[1].ui = buf;
- n[2].e = modeRGB;
- n[3].e = modeA;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlendEquationSeparateiARB(ctx->Exec, (buf, modeRGB, modeA));
- }
-}
-
-
-static void invalidate_saved_current_state( struct gl_context *ctx )
-{
- GLint i;
-
- for (i = 0; i < VERT_ATTRIB_MAX; i++)
- ctx->ListState.ActiveAttribSize[i] = 0;
-
- for (i = 0; i < MAT_ATTRIB_MAX; i++)
- ctx->ListState.ActiveMaterialSize[i] = 0;
-
- memset(&ctx->ListState.Current, 0, sizeof ctx->ListState.Current);
-
- ctx->Driver.CurrentSavePrimitive = PRIM_UNKNOWN;
-}
-
-static void GLAPIENTRY
-save_CallList(GLuint list)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
-
- n = alloc_instruction(ctx, OPCODE_CALL_LIST, 1);
- if (n) {
- n[1].ui = list;
- }
-
- /* After this, we don't know what state we're in. Invalidate all
- * cached information previously gathered:
- */
- invalidate_saved_current_state( ctx );
-
- if (ctx->ExecuteFlag) {
- _mesa_CallList(list);
- }
-}
-
-
-static void GLAPIENTRY
-save_CallLists(GLsizei num, GLenum type, const GLvoid * lists)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint i;
- GLboolean typeErrorFlag;
-
- SAVE_FLUSH_VERTICES(ctx);
-
- switch (type) {
- case GL_BYTE:
- case GL_UNSIGNED_BYTE:
- case GL_SHORT:
- case GL_UNSIGNED_SHORT:
- case GL_INT:
- case GL_UNSIGNED_INT:
- case GL_FLOAT:
- case GL_2_BYTES:
- case GL_3_BYTES:
- case GL_4_BYTES:
- typeErrorFlag = GL_FALSE;
- break;
- default:
- typeErrorFlag = GL_TRUE;
- }
-
- for (i = 0; i < num; i++) {
- GLint list = translate_id(i, type, lists);
- Node *n = alloc_instruction(ctx, OPCODE_CALL_LIST_OFFSET, 2);
- if (n) {
- n[1].i = list;
- n[2].b = typeErrorFlag;
- }
- }
-
- /* After this, we don't know what state we're in. Invalidate all
- * cached information previously gathered:
- */
- invalidate_saved_current_state( ctx );
-
- if (ctx->ExecuteFlag) {
- CALL_CallLists(ctx->Exec, (num, type, lists));
- }
-}
-
-
-static void GLAPIENTRY
-save_Clear(GLbitfield mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR, 1);
- if (n) {
- n[1].bf = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_Clear(ctx->Exec, (mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint *value)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_IV, 6);
- if (n) {
- n[1].e = buffer;
- n[2].i = drawbuffer;
- n[3].i = value[0];
- if (buffer == GL_COLOR) {
- n[4].i = value[1];
- n[5].i = value[2];
- n[6].i = value[3];
- }
- else {
- n[4].i = 0;
- n[5].i = 0;
- n[6].i = 0;
- }
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ClearBufferiv(ctx->Exec, (buffer, drawbuffer, value));*/
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint *value)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_UIV, 6);
- if (n) {
- n[1].e = buffer;
- n[2].i = drawbuffer;
- n[3].ui = value[0];
- if (buffer == GL_COLOR) {
- n[4].ui = value[1];
- n[5].ui = value[2];
- n[6].ui = value[3];
- }
- else {
- n[4].ui = 0;
- n[5].ui = 0;
- n[6].ui = 0;
- }
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ClearBufferuiv(ctx->Exec, (buffer, drawbuffer, value));*/
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat *value)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_FV, 6);
- if (n) {
- n[1].e = buffer;
- n[2].i = drawbuffer;
- n[3].f = value[0];
- if (buffer == GL_COLOR) {
- n[4].f = value[1];
- n[5].f = value[2];
- n[6].f = value[3];
- }
- else {
- n[4].f = 0.0F;
- n[5].f = 0.0F;
- n[6].f = 0.0F;
- }
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ClearBufferuiv(ctx->Exec, (buffer, drawbuffer, value));*/
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearBufferfi(GLenum buffer, GLint drawbuffer,
- GLfloat depth, GLint stencil)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_FI, 4);
- if (n) {
- n[1].e = buffer;
- n[2].i = drawbuffer;
- n[3].f = depth;
- n[4].i = stencil;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ClearBufferfi(ctx->Exec, (buffer, drawbuffer, depth, stencil));*/
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearAccum(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_ACCUM, 4);
- if (n) {
- n[1].f = red;
- n[2].f = green;
- n[3].f = blue;
- n[4].f = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearAccum(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_COLOR, 4);
- if (n) {
- n[1].f = red;
- n[2].f = green;
- n[3].f = blue;
- n[4].f = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearColor(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearDepth(GLclampd depth)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_DEPTH, 1);
- if (n) {
- n[1].f = (GLfloat) depth;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearDepth(ctx->Exec, (depth));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearIndex(GLfloat c)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_INDEX, 1);
- if (n) {
- n[1].f = c;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearIndex(ctx->Exec, (c));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClearStencil(GLint s)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEAR_STENCIL, 1);
- if (n) {
- n[1].i = s;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearStencil(ctx->Exec, (s));
- }
-}
-
-
-static void GLAPIENTRY
-save_ClipPlane(GLenum plane, const GLdouble * equ)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLIP_PLANE, 5);
- if (n) {
- n[1].e = plane;
- n[2].f = (GLfloat) equ[0];
- n[3].f = (GLfloat) equ[1];
- n[4].f = (GLfloat) equ[2];
- n[5].f = (GLfloat) equ[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_ClipPlane(ctx->Exec, (plane, equ));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_ColorMask(GLboolean red, GLboolean green,
- GLboolean blue, GLboolean alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COLOR_MASK, 4);
- if (n) {
- n[1].b = red;
- n[2].b = green;
- n[3].b = blue;
- n[4].b = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_ColorMask(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-
-static void GLAPIENTRY
-save_ColorMaskIndexed(GLuint buf, GLboolean red, GLboolean green,
- GLboolean blue, GLboolean alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COLOR_MASK_INDEXED, 5);
- if (n) {
- n[1].ui = buf;
- n[2].b = red;
- n[3].b = green;
- n[4].b = blue;
- n[5].b = alpha;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ColorMaskIndexedEXT(ctx->Exec, (buf, red, green, blue, alpha));*/
- }
-}
-
-
-static void GLAPIENTRY
-save_ColorMaterial(GLenum face, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_COLOR_MATERIAL, 2);
- if (n) {
- n[1].e = face;
- n[2].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_ColorMaterial(ctx->Exec, (face, mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_ColorTable(GLenum target, GLenum internalFormat,
- GLsizei width, GLenum format, GLenum type,
- const GLvoid * table)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (_mesa_is_proxy_texture(target)) {
- /* execute immediately */
- CALL_ColorTable(ctx->Exec, (target, internalFormat, width,
- format, type, table));
- }
- else {
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COLOR_TABLE, 6);
- if (n) {
- n[1].e = target;
- n[2].e = internalFormat;
- n[3].i = width;
- n[4].e = format;
- n[5].e = type;
- n[6].data = unpack_image(ctx, 1, width, 1, 1, format, type, table,
- &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_ColorTable(ctx->Exec, (target, internalFormat, width,
- format, type, table));
- }
- }
-}
-
-
-
-static void GLAPIENTRY
-save_ColorTableParameterfv(GLenum target, GLenum pname,
- const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_COLOR_TABLE_PARAMETER_FV, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].f = params[0];
- if (pname == GL_COLOR_TABLE_SGI ||
- pname == GL_POST_CONVOLUTION_COLOR_TABLE_SGI ||
- pname == GL_TEXTURE_COLOR_TABLE_SGI) {
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- }
-
- if (ctx->ExecuteFlag) {
- CALL_ColorTableParameterfv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ColorTableParameteriv(GLenum target, GLenum pname, const GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_COLOR_TABLE_PARAMETER_IV, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].i = params[0];
- if (pname == GL_COLOR_TABLE_SGI ||
- pname == GL_POST_CONVOLUTION_COLOR_TABLE_SGI ||
- pname == GL_TEXTURE_COLOR_TABLE_SGI) {
- n[4].i = params[1];
- n[5].i = params[2];
- n[6].i = params[3];
- }
- }
-
- if (ctx->ExecuteFlag) {
- CALL_ColorTableParameteriv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_ColorSubTable(GLenum target, GLsizei start, GLsizei count,
- GLenum format, GLenum type, const GLvoid * table)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COLOR_SUB_TABLE, 6);
- if (n) {
- n[1].e = target;
- n[2].i = start;
- n[3].i = count;
- n[4].e = format;
- n[5].e = type;
- n[6].data = unpack_image(ctx, 1, count, 1, 1, format, type, table,
- &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_ColorSubTable(ctx->Exec,
- (target, start, count, format, type, table));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyColorSubTable(GLenum target, GLsizei start,
- GLint x, GLint y, GLsizei width)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_COLOR_SUB_TABLE, 5);
- if (n) {
- n[1].e = target;
- n[2].i = start;
- n[3].i = x;
- n[4].i = y;
- n[5].i = width;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyColorSubTable(ctx->Exec, (target, start, x, y, width));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyColorTable(GLenum target, GLenum internalformat,
- GLint x, GLint y, GLsizei width)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_COLOR_TABLE, 5);
- if (n) {
- n[1].e = target;
- n[2].e = internalformat;
- n[3].i = x;
- n[4].i = y;
- n[5].i = width;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyColorTable(ctx->Exec, (target, internalformat, x, y, width));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionFilter1D(GLenum target, GLenum internalFormat, GLsizei width,
- GLenum format, GLenum type, const GLvoid * filter)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_FILTER_1D, 6);
- if (n) {
- n[1].e = target;
- n[2].e = internalFormat;
- n[3].i = width;
- n[4].e = format;
- n[5].e = type;
- n[6].data = unpack_image(ctx, 1, width, 1, 1, format, type, filter,
- &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionFilter1D(ctx->Exec, (target, internalFormat, width,
- format, type, filter));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionFilter2D(GLenum target, GLenum internalFormat,
- GLsizei width, GLsizei height, GLenum format,
- GLenum type, const GLvoid * filter)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_FILTER_2D, 7);
- if (n) {
- n[1].e = target;
- n[2].e = internalFormat;
- n[3].i = width;
- n[4].i = height;
- n[5].e = format;
- n[6].e = type;
- n[7].data = unpack_image(ctx, 2, width, height, 1, format, type, filter,
- &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionFilter2D(ctx->Exec,
- (target, internalFormat, width, height, format,
- type, filter));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionParameteri(GLenum target, GLenum pname, GLint param)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_I, 3);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].i = param;
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionParameteri(ctx->Exec, (target, pname, param));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionParameteriv(GLenum target, GLenum pname, const GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_IV, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].i = params[0];
- if (pname == GL_CONVOLUTION_BORDER_COLOR ||
- pname == GL_CONVOLUTION_FILTER_SCALE ||
- pname == GL_CONVOLUTION_FILTER_BIAS) {
- n[4].i = params[1];
- n[5].i = params[2];
- n[6].i = params[3];
- }
- else {
- n[4].i = n[5].i = n[6].i = 0;
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionParameteriv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionParameterf(GLenum target, GLenum pname, GLfloat param)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_F, 3);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].f = param;
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionParameterf(ctx->Exec, (target, pname, param));
- }
-}
-
-
-static void GLAPIENTRY
-save_ConvolutionParameterfv(GLenum target, GLenum pname,
- const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_FV, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].f = params[0];
- if (pname == GL_CONVOLUTION_BORDER_COLOR ||
- pname == GL_CONVOLUTION_FILTER_SCALE ||
- pname == GL_CONVOLUTION_FILTER_BIAS) {
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- else {
- n[4].f = n[5].f = n[6].f = 0.0F;
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_ConvolutionParameterfv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_PIXELS, 5);
- if (n) {
- n[1].i = x;
- n[2].i = y;
- n[3].i = (GLint) width;
- n[4].i = (GLint) height;
- n[5].e = type;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyPixels(ctx->Exec, (x, y, width, height, type));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_CopyTexImage1D(GLenum target, GLint level, GLenum internalformat,
- GLint x, GLint y, GLsizei width, GLint border)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_TEX_IMAGE1D, 7);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].e = internalformat;
- n[4].i = x;
- n[5].i = y;
- n[6].i = width;
- n[7].i = border;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyTexImage1D(ctx->Exec, (target, level, internalformat,
- x, y, width, border));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyTexImage2D(GLenum target, GLint level,
- GLenum internalformat,
- GLint x, GLint y, GLsizei width,
- GLsizei height, GLint border)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_TEX_IMAGE2D, 8);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].e = internalformat;
- n[4].i = x;
- n[5].i = y;
- n[6].i = width;
- n[7].i = height;
- n[8].i = border;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyTexImage2D(ctx->Exec, (target, level, internalformat,
- x, y, width, height, border));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_CopyTexSubImage1D(GLenum target, GLint level,
- GLint xoffset, GLint x, GLint y, GLsizei width)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE1D, 6);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = x;
- n[5].i = y;
- n[6].i = width;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyTexSubImage1D(ctx->Exec,
- (target, level, xoffset, x, y, width));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyTexSubImage2D(GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLint x, GLint y, GLsizei width, GLint height)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE2D, 8);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = x;
- n[6].i = y;
- n[7].i = width;
- n[8].i = height;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyTexSubImage2D(ctx->Exec, (target, level, xoffset, yoffset,
- x, y, width, height));
- }
-}
-
-
-static void GLAPIENTRY
-save_CopyTexSubImage3D(GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint x, GLint y, GLsizei width, GLint height)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE3D, 9);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = zoffset;
- n[6].i = x;
- n[7].i = y;
- n[8].i = width;
- n[9].i = height;
- }
- if (ctx->ExecuteFlag) {
- CALL_CopyTexSubImage3D(ctx->Exec, (target, level,
- xoffset, yoffset, zoffset,
- x, y, width, height));
- }
-}
-
-
-static void GLAPIENTRY
-save_CullFace(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CULL_FACE, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_CullFace(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_DepthFunc(GLenum func)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DEPTH_FUNC, 1);
- if (n) {
- n[1].e = func;
- }
- if (ctx->ExecuteFlag) {
- CALL_DepthFunc(ctx->Exec, (func));
- }
-}
-
-
-static void GLAPIENTRY
-save_DepthMask(GLboolean mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DEPTH_MASK, 1);
- if (n) {
- n[1].b = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_DepthMask(ctx->Exec, (mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_DepthRange(GLclampd nearval, GLclampd farval)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DEPTH_RANGE, 2);
- if (n) {
- n[1].f = (GLfloat) nearval;
- n[2].f = (GLfloat) farval;
- }
- if (ctx->ExecuteFlag) {
- CALL_DepthRange(ctx->Exec, (nearval, farval));
- }
-}
-
-
-static void GLAPIENTRY
-save_Disable(GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DISABLE, 1);
- if (n) {
- n[1].e = cap;
- }
- if (ctx->ExecuteFlag) {
- CALL_Disable(ctx->Exec, (cap));
- }
-}
-
-
-static void GLAPIENTRY
-save_DisableIndexed(GLuint index, GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DISABLE_INDEXED, 2);
- if (n) {
- n[1].ui = index;
- n[2].e = cap;
- }
- if (ctx->ExecuteFlag) {
- CALL_DisableIndexedEXT(ctx->Exec, (index, cap));
- }
-}
-
-
-static void GLAPIENTRY
-save_DrawBuffer(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DRAW_BUFFER, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_DrawBuffer(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_DrawPixels(GLsizei width, GLsizei height,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_DRAW_PIXELS, 5);
- if (n) {
- n[1].i = width;
- n[2].i = height;
- n[3].e = format;
- n[4].e = type;
- n[5].data = unpack_image(ctx, 2, width, height, 1, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_DrawPixels(ctx->Exec, (width, height, format, type, pixels));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_Enable(GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ENABLE, 1);
- if (n) {
- n[1].e = cap;
- }
- if (ctx->ExecuteFlag) {
- CALL_Enable(ctx->Exec, (cap));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_EnableIndexed(GLuint index, GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ENABLE_INDEXED, 2);
- if (n) {
- n[1].ui = index;
- n[2].e = cap;
- }
- if (ctx->ExecuteFlag) {
- CALL_EnableIndexedEXT(ctx->Exec, (index, cap));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_EvalMesh1(GLenum mode, GLint i1, GLint i2)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_EVALMESH1, 3);
- if (n) {
- n[1].e = mode;
- n[2].i = i1;
- n[3].i = i2;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalMesh1(ctx->Exec, (mode, i1, i2));
- }
-}
-
-
-static void GLAPIENTRY
-save_EvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_EVALMESH2, 5);
- if (n) {
- n[1].e = mode;
- n[2].i = i1;
- n[3].i = i2;
- n[4].i = j1;
- n[5].i = j2;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalMesh2(ctx->Exec, (mode, i1, i2, j1, j2));
- }
-}
-
-
-
-
-static void GLAPIENTRY
-save_Fogfv(GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_FOG, 5);
- if (n) {
- n[1].e = pname;
- n[2].f = params[0];
- n[3].f = params[1];
- n[4].f = params[2];
- n[5].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_Fogfv(ctx->Exec, (pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_Fogf(GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_Fogfv(pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_Fogiv(GLenum pname, const GLint *params)
-{
- GLfloat p[4];
- switch (pname) {
- case GL_FOG_MODE:
- case GL_FOG_DENSITY:
- case GL_FOG_START:
- case GL_FOG_END:
- case GL_FOG_INDEX:
- p[0] = (GLfloat) *params;
- p[1] = 0.0f;
- p[2] = 0.0f;
- p[3] = 0.0f;
- break;
- case GL_FOG_COLOR:
- p[0] = INT_TO_FLOAT(params[0]);
- p[1] = INT_TO_FLOAT(params[1]);
- p[2] = INT_TO_FLOAT(params[2]);
- p[3] = INT_TO_FLOAT(params[3]);
- break;
- default:
- /* Error will be caught later in gl_Fogfv */
- ASSIGN_4V(p, 0.0F, 0.0F, 0.0F, 0.0F);
- }
- save_Fogfv(pname, p);
-}
-
-
-static void GLAPIENTRY
-save_Fogi(GLenum pname, GLint param)
-{
- GLint parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0;
- save_Fogiv(pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_FrontFace(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_FRONT_FACE, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_FrontFace(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_Frustum(GLdouble left, GLdouble right,
- GLdouble bottom, GLdouble top, GLdouble nearval, GLdouble farval)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_FRUSTUM, 6);
- if (n) {
- n[1].f = (GLfloat) left;
- n[2].f = (GLfloat) right;
- n[3].f = (GLfloat) bottom;
- n[4].f = (GLfloat) top;
- n[5].f = (GLfloat) nearval;
- n[6].f = (GLfloat) farval;
- }
- if (ctx->ExecuteFlag) {
- CALL_Frustum(ctx->Exec, (left, right, bottom, top, nearval, farval));
- }
-}
-
-
-static void GLAPIENTRY
-save_Hint(GLenum target, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_HINT, 2);
- if (n) {
- n[1].e = target;
- n[2].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_Hint(ctx->Exec, (target, mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_Histogram(GLenum target, GLsizei width, GLenum internalFormat,
- GLboolean sink)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_HISTOGRAM, 4);
- if (n) {
- n[1].e = target;
- n[2].i = width;
- n[3].e = internalFormat;
- n[4].b = sink;
- }
- if (ctx->ExecuteFlag) {
- CALL_Histogram(ctx->Exec, (target, width, internalFormat, sink));
- }
-}
-
-
-static void GLAPIENTRY
-save_IndexMask(GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_INDEX_MASK, 1);
- if (n) {
- n[1].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_IndexMask(ctx->Exec, (mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_InitNames(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_INIT_NAMES, 0);
- if (ctx->ExecuteFlag) {
- CALL_InitNames(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_Lightfv(GLenum light, GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LIGHT, 6);
- if (n) {
- GLint i, nParams;
- n[1].e = light;
- n[2].e = pname;
- switch (pname) {
- case GL_AMBIENT:
- nParams = 4;
- break;
- case GL_DIFFUSE:
- nParams = 4;
- break;
- case GL_SPECULAR:
- nParams = 4;
- break;
- case GL_POSITION:
- nParams = 4;
- break;
- case GL_SPOT_DIRECTION:
- nParams = 3;
- break;
- case GL_SPOT_EXPONENT:
- nParams = 1;
- break;
- case GL_SPOT_CUTOFF:
- nParams = 1;
- break;
- case GL_CONSTANT_ATTENUATION:
- nParams = 1;
- break;
- case GL_LINEAR_ATTENUATION:
- nParams = 1;
- break;
- case GL_QUADRATIC_ATTENUATION:
- nParams = 1;
- break;
- default:
- nParams = 0;
- }
- for (i = 0; i < nParams; i++) {
- n[3 + i].f = params[i];
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_Lightfv(ctx->Exec, (light, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_Lightf(GLenum light, GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_Lightfv(light, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_Lightiv(GLenum light, GLenum pname, const GLint *params)
-{
- GLfloat fparam[4];
- switch (pname) {
- case GL_AMBIENT:
- case GL_DIFFUSE:
- case GL_SPECULAR:
- fparam[0] = INT_TO_FLOAT(params[0]);
- fparam[1] = INT_TO_FLOAT(params[1]);
- fparam[2] = INT_TO_FLOAT(params[2]);
- fparam[3] = INT_TO_FLOAT(params[3]);
- break;
- case GL_POSITION:
- fparam[0] = (GLfloat) params[0];
- fparam[1] = (GLfloat) params[1];
- fparam[2] = (GLfloat) params[2];
- fparam[3] = (GLfloat) params[3];
- break;
- case GL_SPOT_DIRECTION:
- fparam[0] = (GLfloat) params[0];
- fparam[1] = (GLfloat) params[1];
- fparam[2] = (GLfloat) params[2];
- break;
- case GL_SPOT_EXPONENT:
- case GL_SPOT_CUTOFF:
- case GL_CONSTANT_ATTENUATION:
- case GL_LINEAR_ATTENUATION:
- case GL_QUADRATIC_ATTENUATION:
- fparam[0] = (GLfloat) params[0];
- break;
- default:
- /* error will be caught later in gl_Lightfv */
- ;
- }
- save_Lightfv(light, pname, fparam);
-}
-
-
-static void GLAPIENTRY
-save_Lighti(GLenum light, GLenum pname, GLint param)
-{
- GLint parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0;
- save_Lightiv(light, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_LightModelfv(GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LIGHT_MODEL, 5);
- if (n) {
- n[1].e = pname;
- n[2].f = params[0];
- n[3].f = params[1];
- n[4].f = params[2];
- n[5].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_LightModelfv(ctx->Exec, (pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_LightModelf(GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_LightModelfv(pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_LightModeliv(GLenum pname, const GLint *params)
-{
- GLfloat fparam[4];
- switch (pname) {
- case GL_LIGHT_MODEL_AMBIENT:
- fparam[0] = INT_TO_FLOAT(params[0]);
- fparam[1] = INT_TO_FLOAT(params[1]);
- fparam[2] = INT_TO_FLOAT(params[2]);
- fparam[3] = INT_TO_FLOAT(params[3]);
- break;
- case GL_LIGHT_MODEL_LOCAL_VIEWER:
- case GL_LIGHT_MODEL_TWO_SIDE:
- case GL_LIGHT_MODEL_COLOR_CONTROL:
- fparam[0] = (GLfloat) params[0];
- fparam[1] = 0.0F;
- fparam[2] = 0.0F;
- fparam[3] = 0.0F;
- break;
- default:
- /* Error will be caught later in gl_LightModelfv */
- ASSIGN_4V(fparam, 0.0F, 0.0F, 0.0F, 0.0F);
- }
- save_LightModelfv(pname, fparam);
-}
-
-
-static void GLAPIENTRY
-save_LightModeli(GLenum pname, GLint param)
-{
- GLint parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0;
- save_LightModeliv(pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_LineStipple(GLint factor, GLushort pattern)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LINE_STIPPLE, 2);
- if (n) {
- n[1].i = factor;
- n[2].us = pattern;
- }
- if (ctx->ExecuteFlag) {
- CALL_LineStipple(ctx->Exec, (factor, pattern));
- }
-}
-
-
-static void GLAPIENTRY
-save_LineWidth(GLfloat width)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LINE_WIDTH, 1);
- if (n) {
- n[1].f = width;
- }
- if (ctx->ExecuteFlag) {
- CALL_LineWidth(ctx->Exec, (width));
- }
-}
-
-
-static void GLAPIENTRY
-save_ListBase(GLuint base)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LIST_BASE, 1);
- if (n) {
- n[1].ui = base;
- }
- if (ctx->ExecuteFlag) {
- CALL_ListBase(ctx->Exec, (base));
- }
-}
-
-
-static void GLAPIENTRY
-save_LoadIdentity(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_LOAD_IDENTITY, 0);
- if (ctx->ExecuteFlag) {
- CALL_LoadIdentity(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_LoadMatrixf(const GLfloat * m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LOAD_MATRIX, 16);
- if (n) {
- GLuint i;
- for (i = 0; i < 16; i++) {
- n[1 + i].f = m[i];
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_LoadMatrixf(ctx->Exec, (m));
- }
-}
-
-
-static void GLAPIENTRY
-save_LoadMatrixd(const GLdouble * m)
-{
- GLfloat f[16];
- GLint i;
- for (i = 0; i < 16; i++) {
- f[i] = (GLfloat) m[i];
- }
- save_LoadMatrixf(f);
-}
-
-
-static void GLAPIENTRY
-save_LoadName(GLuint name)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LOAD_NAME, 1);
- if (n) {
- n[1].ui = name;
- }
- if (ctx->ExecuteFlag) {
- CALL_LoadName(ctx->Exec, (name));
- }
-}
-
-
-static void GLAPIENTRY
-save_LogicOp(GLenum opcode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_LOGIC_OP, 1);
- if (n) {
- n[1].e = opcode;
- }
- if (ctx->ExecuteFlag) {
- CALL_LogicOp(ctx->Exec, (opcode));
- }
-}
-
-
-static void GLAPIENTRY
-save_Map1d(GLenum target, GLdouble u1, GLdouble u2, GLint stride,
- GLint order, const GLdouble * points)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAP1, 6);
- if (n) {
- GLfloat *pnts = _mesa_copy_map_points1d(target, stride, order, points);
- n[1].e = target;
- n[2].f = (GLfloat) u1;
- n[3].f = (GLfloat) u2;
- n[4].i = _mesa_evaluator_components(target); /* stride */
- n[5].i = order;
- n[6].data = (void *) pnts;
- }
- if (ctx->ExecuteFlag) {
- CALL_Map1d(ctx->Exec, (target, u1, u2, stride, order, points));
- }
-}
-
-static void GLAPIENTRY
-save_Map1f(GLenum target, GLfloat u1, GLfloat u2, GLint stride,
- GLint order, const GLfloat * points)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAP1, 6);
- if (n) {
- GLfloat *pnts = _mesa_copy_map_points1f(target, stride, order, points);
- n[1].e = target;
- n[2].f = u1;
- n[3].f = u2;
- n[4].i = _mesa_evaluator_components(target); /* stride */
- n[5].i = order;
- n[6].data = (void *) pnts;
- }
- if (ctx->ExecuteFlag) {
- CALL_Map1f(ctx->Exec, (target, u1, u2, stride, order, points));
- }
-}
-
-
-static void GLAPIENTRY
-save_Map2d(GLenum target,
- GLdouble u1, GLdouble u2, GLint ustride, GLint uorder,
- GLdouble v1, GLdouble v2, GLint vstride, GLint vorder,
- const GLdouble * points)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAP2, 10);
- if (n) {
- GLfloat *pnts = _mesa_copy_map_points2d(target, ustride, uorder,
- vstride, vorder, points);
- n[1].e = target;
- n[2].f = (GLfloat) u1;
- n[3].f = (GLfloat) u2;
- n[4].f = (GLfloat) v1;
- n[5].f = (GLfloat) v2;
- /* XXX verify these strides are correct */
- n[6].i = _mesa_evaluator_components(target) * vorder; /*ustride */
- n[7].i = _mesa_evaluator_components(target); /*vstride */
- n[8].i = uorder;
- n[9].i = vorder;
- n[10].data = (void *) pnts;
- }
- if (ctx->ExecuteFlag) {
- CALL_Map2d(ctx->Exec, (target,
- u1, u2, ustride, uorder,
- v1, v2, vstride, vorder, points));
- }
-}
-
-
-static void GLAPIENTRY
-save_Map2f(GLenum target,
- GLfloat u1, GLfloat u2, GLint ustride, GLint uorder,
- GLfloat v1, GLfloat v2, GLint vstride, GLint vorder,
- const GLfloat * points)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAP2, 10);
- if (n) {
- GLfloat *pnts = _mesa_copy_map_points2f(target, ustride, uorder,
- vstride, vorder, points);
- n[1].e = target;
- n[2].f = u1;
- n[3].f = u2;
- n[4].f = v1;
- n[5].f = v2;
- /* XXX verify these strides are correct */
- n[6].i = _mesa_evaluator_components(target) * vorder; /*ustride */
- n[7].i = _mesa_evaluator_components(target); /*vstride */
- n[8].i = uorder;
- n[9].i = vorder;
- n[10].data = (void *) pnts;
- }
- if (ctx->ExecuteFlag) {
- CALL_Map2f(ctx->Exec, (target, u1, u2, ustride, uorder,
- v1, v2, vstride, vorder, points));
- }
-}
-
-
-static void GLAPIENTRY
-save_MapGrid1f(GLint un, GLfloat u1, GLfloat u2)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAPGRID1, 3);
- if (n) {
- n[1].i = un;
- n[2].f = u1;
- n[3].f = u2;
- }
- if (ctx->ExecuteFlag) {
- CALL_MapGrid1f(ctx->Exec, (un, u1, u2));
- }
-}
-
-
-static void GLAPIENTRY
-save_MapGrid1d(GLint un, GLdouble u1, GLdouble u2)
-{
- save_MapGrid1f(un, (GLfloat) u1, (GLfloat) u2);
-}
-
-
-static void GLAPIENTRY
-save_MapGrid2f(GLint un, GLfloat u1, GLfloat u2,
- GLint vn, GLfloat v1, GLfloat v2)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MAPGRID2, 6);
- if (n) {
- n[1].i = un;
- n[2].f = u1;
- n[3].f = u2;
- n[4].i = vn;
- n[5].f = v1;
- n[6].f = v2;
- }
- if (ctx->ExecuteFlag) {
- CALL_MapGrid2f(ctx->Exec, (un, u1, u2, vn, v1, v2));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_MapGrid2d(GLint un, GLdouble u1, GLdouble u2,
- GLint vn, GLdouble v1, GLdouble v2)
-{
- save_MapGrid2f(un, (GLfloat) u1, (GLfloat) u2,
- vn, (GLfloat) v1, (GLfloat) v2);
-}
-
-
-static void GLAPIENTRY
-save_MatrixMode(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MATRIX_MODE, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_MatrixMode(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_Minmax(GLenum target, GLenum internalFormat, GLboolean sink)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MIN_MAX, 3);
- if (n) {
- n[1].e = target;
- n[2].e = internalFormat;
- n[3].b = sink;
- }
- if (ctx->ExecuteFlag) {
- CALL_Minmax(ctx->Exec, (target, internalFormat, sink));
- }
-}
-
-
-static void GLAPIENTRY
-save_MultMatrixf(const GLfloat * m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_MULT_MATRIX, 16);
- if (n) {
- GLuint i;
- for (i = 0; i < 16; i++) {
- n[1 + i].f = m[i];
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_MultMatrixf(ctx->Exec, (m));
- }
-}
-
-
-static void GLAPIENTRY
-save_MultMatrixd(const GLdouble * m)
-{
- GLfloat f[16];
- GLint i;
- for (i = 0; i < 16; i++) {
- f[i] = (GLfloat) m[i];
- }
- save_MultMatrixf(f);
-}
-
-
-static void GLAPIENTRY
-save_NewList(GLuint name, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- /* It's an error to call this function while building a display list */
- _mesa_error(ctx, GL_INVALID_OPERATION, "glNewList");
- (void) name;
- (void) mode;
-}
-
-
-
-static void GLAPIENTRY
-save_Ortho(GLdouble left, GLdouble right,
- GLdouble bottom, GLdouble top, GLdouble nearval, GLdouble farval)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ORTHO, 6);
- if (n) {
- n[1].f = (GLfloat) left;
- n[2].f = (GLfloat) right;
- n[3].f = (GLfloat) bottom;
- n[4].f = (GLfloat) top;
- n[5].f = (GLfloat) nearval;
- n[6].f = (GLfloat) farval;
- }
- if (ctx->ExecuteFlag) {
- CALL_Ortho(ctx->Exec, (left, right, bottom, top, nearval, farval));
- }
-}
-
-
-static void GLAPIENTRY
-save_PixelMapfv(GLenum map, GLint mapsize, const GLfloat *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PIXEL_MAP, 3);
- if (n) {
- n[1].e = map;
- n[2].i = mapsize;
- n[3].data = (void *) malloc(mapsize * sizeof(GLfloat));
- memcpy(n[3].data, (void *) values, mapsize * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_PixelMapfv(ctx->Exec, (map, mapsize, values));
- }
-}
-
-
-static void GLAPIENTRY
-save_PixelMapuiv(GLenum map, GLint mapsize, const GLuint *values)
-{
- GLfloat fvalues[MAX_PIXEL_MAP_TABLE];
- GLint i;
- if (map == GL_PIXEL_MAP_I_TO_I || map == GL_PIXEL_MAP_S_TO_S) {
- for (i = 0; i < mapsize; i++) {
- fvalues[i] = (GLfloat) values[i];
- }
- }
- else {
- for (i = 0; i < mapsize; i++) {
- fvalues[i] = UINT_TO_FLOAT(values[i]);
- }
- }
- save_PixelMapfv(map, mapsize, fvalues);
-}
-
-
-static void GLAPIENTRY
-save_PixelMapusv(GLenum map, GLint mapsize, const GLushort *values)
-{
- GLfloat fvalues[MAX_PIXEL_MAP_TABLE];
- GLint i;
- if (map == GL_PIXEL_MAP_I_TO_I || map == GL_PIXEL_MAP_S_TO_S) {
- for (i = 0; i < mapsize; i++) {
- fvalues[i] = (GLfloat) values[i];
- }
- }
- else {
- for (i = 0; i < mapsize; i++) {
- fvalues[i] = USHORT_TO_FLOAT(values[i]);
- }
- }
- save_PixelMapfv(map, mapsize, fvalues);
-}
-
-
-static void GLAPIENTRY
-save_PixelTransferf(GLenum pname, GLfloat param)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PIXEL_TRANSFER, 2);
- if (n) {
- n[1].e = pname;
- n[2].f = param;
- }
- if (ctx->ExecuteFlag) {
- CALL_PixelTransferf(ctx->Exec, (pname, param));
- }
-}
-
-
-static void GLAPIENTRY
-save_PixelTransferi(GLenum pname, GLint param)
-{
- save_PixelTransferf(pname, (GLfloat) param);
-}
-
-
-static void GLAPIENTRY
-save_PixelZoom(GLfloat xfactor, GLfloat yfactor)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PIXEL_ZOOM, 2);
- if (n) {
- n[1].f = xfactor;
- n[2].f = yfactor;
- }
- if (ctx->ExecuteFlag) {
- CALL_PixelZoom(ctx->Exec, (xfactor, yfactor));
- }
-}
-
-
-static void GLAPIENTRY
-save_PointParameterfvEXT(GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_POINT_PARAMETERS, 4);
- if (n) {
- n[1].e = pname;
- n[2].f = params[0];
- n[3].f = params[1];
- n[4].f = params[2];
- }
- if (ctx->ExecuteFlag) {
- CALL_PointParameterfvEXT(ctx->Exec, (pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_PointParameterfEXT(GLenum pname, GLfloat param)
-{
- GLfloat parray[3];
- parray[0] = param;
- parray[1] = parray[2] = 0.0F;
- save_PointParameterfvEXT(pname, parray);
-}
-
-static void GLAPIENTRY
-save_PointParameteriNV(GLenum pname, GLint param)
-{
- GLfloat parray[3];
- parray[0] = (GLfloat) param;
- parray[1] = parray[2] = 0.0F;
- save_PointParameterfvEXT(pname, parray);
-}
-
-static void GLAPIENTRY
-save_PointParameterivNV(GLenum pname, const GLint * param)
-{
- GLfloat parray[3];
- parray[0] = (GLfloat) param[0];
- parray[1] = parray[2] = 0.0F;
- save_PointParameterfvEXT(pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_PointSize(GLfloat size)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_POINT_SIZE, 1);
- if (n) {
- n[1].f = size;
- }
- if (ctx->ExecuteFlag) {
- CALL_PointSize(ctx->Exec, (size));
- }
-}
-
-
-static void GLAPIENTRY
-save_PolygonMode(GLenum face, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_POLYGON_MODE, 2);
- if (n) {
- n[1].e = face;
- n[2].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_PolygonMode(ctx->Exec, (face, mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_PolygonStipple(const GLubyte * pattern)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_POLYGON_STIPPLE, 1);
- if (n) {
- n[1].data = unpack_image(ctx, 2, 32, 32, 1, GL_COLOR_INDEX, GL_BITMAP,
- pattern, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_PolygonStipple(ctx->Exec, ((GLubyte *) pattern));
- }
-}
-
-
-static void GLAPIENTRY
-save_PolygonOffset(GLfloat factor, GLfloat units)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_POLYGON_OFFSET, 2);
- if (n) {
- n[1].f = factor;
- n[2].f = units;
- }
- if (ctx->ExecuteFlag) {
- CALL_PolygonOffset(ctx->Exec, (factor, units));
- }
-}
-
-
-static void GLAPIENTRY
-save_PolygonOffsetEXT(GLfloat factor, GLfloat bias)
-{
- GET_CURRENT_CONTEXT(ctx);
- /* XXX mult by DepthMaxF here??? */
- save_PolygonOffset(factor, ctx->DrawBuffer->_DepthMaxF * bias);
-}
-
-
-static void GLAPIENTRY
-save_PopAttrib(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_POP_ATTRIB, 0);
- if (ctx->ExecuteFlag) {
- CALL_PopAttrib(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_PopMatrix(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_POP_MATRIX, 0);
- if (ctx->ExecuteFlag) {
- CALL_PopMatrix(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_PopName(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_POP_NAME, 0);
- if (ctx->ExecuteFlag) {
- CALL_PopName(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_PrioritizeTextures(GLsizei num, const GLuint * textures,
- const GLclampf * priorities)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint i;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- for (i = 0; i < num; i++) {
- Node *n;
- n = alloc_instruction(ctx, OPCODE_PRIORITIZE_TEXTURE, 2);
- if (n) {
- n[1].ui = textures[i];
- n[2].f = priorities[i];
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_PrioritizeTextures(ctx->Exec, (num, textures, priorities));
- }
-}
-
-
-static void GLAPIENTRY
-save_PushAttrib(GLbitfield mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PUSH_ATTRIB, 1);
- if (n) {
- n[1].bf = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_PushAttrib(ctx->Exec, (mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_PushMatrix(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_PUSH_MATRIX, 0);
- if (ctx->ExecuteFlag) {
- CALL_PushMatrix(ctx->Exec, ());
- }
-}
-
-
-static void GLAPIENTRY
-save_PushName(GLuint name)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PUSH_NAME, 1);
- if (n) {
- n[1].ui = name;
- }
- if (ctx->ExecuteFlag) {
- CALL_PushName(ctx->Exec, (name));
- }
-}
-
-
-static void GLAPIENTRY
-save_RasterPos4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_RASTER_POS, 4);
- if (n) {
- n[1].f = x;
- n[2].f = y;
- n[3].f = z;
- n[4].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_RasterPos4f(ctx->Exec, (x, y, z, w));
- }
-}
-
-static void GLAPIENTRY
-save_RasterPos2d(GLdouble x, GLdouble y)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2f(GLfloat x, GLfloat y)
-{
- save_RasterPos4f(x, y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2i(GLint x, GLint y)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2s(GLshort x, GLshort y)
-{
- save_RasterPos4f(x, y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3d(GLdouble x, GLdouble y, GLdouble z)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3f(GLfloat x, GLfloat y, GLfloat z)
-{
- save_RasterPos4f(x, y, z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3i(GLint x, GLint y, GLint z)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3s(GLshort x, GLshort y, GLshort z)
-{
- save_RasterPos4f(x, y, z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
-}
-
-static void GLAPIENTRY
-save_RasterPos4i(GLint x, GLint y, GLint z, GLint w)
-{
- save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
-}
-
-static void GLAPIENTRY
-save_RasterPos4s(GLshort x, GLshort y, GLshort z, GLshort w)
-{
- save_RasterPos4f(x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_RasterPos2dv(const GLdouble * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2fv(const GLfloat * v)
-{
- save_RasterPos4f(v[0], v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2iv(const GLint * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos2sv(const GLshort * v)
-{
- save_RasterPos4f(v[0], v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3dv(const GLdouble * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3fv(const GLfloat * v)
-{
- save_RasterPos4f(v[0], v[1], v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3iv(const GLint * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos3sv(const GLshort * v)
-{
- save_RasterPos4f(v[0], v[1], v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_RasterPos4dv(const GLdouble * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1],
- (GLfloat) v[2], (GLfloat) v[3]);
-}
-
-static void GLAPIENTRY
-save_RasterPos4fv(const GLfloat * v)
-{
- save_RasterPos4f(v[0], v[1], v[2], v[3]);
-}
-
-static void GLAPIENTRY
-save_RasterPos4iv(const GLint * v)
-{
- save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1],
- (GLfloat) v[2], (GLfloat) v[3]);
-}
-
-static void GLAPIENTRY
-save_RasterPos4sv(const GLshort * v)
-{
- save_RasterPos4f(v[0], v[1], v[2], v[3]);
-}
-
-
-static void GLAPIENTRY
-save_PassThrough(GLfloat token)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PASSTHROUGH, 1);
- if (n) {
- n[1].f = token;
- }
- if (ctx->ExecuteFlag) {
- CALL_PassThrough(ctx->Exec, (token));
- }
-}
-
-
-static void GLAPIENTRY
-save_ReadBuffer(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_READ_BUFFER, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_ReadBuffer(ctx->Exec, (mode));
- }
-}
-
-
-static void GLAPIENTRY
-save_ResetHistogram(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_RESET_HISTOGRAM, 1);
- if (n) {
- n[1].e = target;
- }
- if (ctx->ExecuteFlag) {
- CALL_ResetHistogram(ctx->Exec, (target));
- }
-}
-
-
-static void GLAPIENTRY
-save_ResetMinmax(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_RESET_MIN_MAX, 1);
- if (n) {
- n[1].e = target;
- }
- if (ctx->ExecuteFlag) {
- CALL_ResetMinmax(ctx->Exec, (target));
- }
-}
-
-
-static void GLAPIENTRY
-save_Rotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ROTATE, 4);
- if (n) {
- n[1].f = angle;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- }
- if (ctx->ExecuteFlag) {
- CALL_Rotatef(ctx->Exec, (angle, x, y, z));
- }
-}
-
-
-static void GLAPIENTRY
-save_Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
-{
- save_Rotatef((GLfloat) angle, (GLfloat) x, (GLfloat) y, (GLfloat) z);
-}
-
-
-static void GLAPIENTRY
-save_Scalef(GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_SCALE, 3);
- if (n) {
- n[1].f = x;
- n[2].f = y;
- n[3].f = z;
- }
- if (ctx->ExecuteFlag) {
- CALL_Scalef(ctx->Exec, (x, y, z));
- }
-}
-
-
-static void GLAPIENTRY
-save_Scaled(GLdouble x, GLdouble y, GLdouble z)
-{
- save_Scalef((GLfloat) x, (GLfloat) y, (GLfloat) z);
-}
-
-
-static void GLAPIENTRY
-save_Scissor(GLint x, GLint y, GLsizei width, GLsizei height)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_SCISSOR, 4);
- if (n) {
- n[1].i = x;
- n[2].i = y;
- n[3].i = width;
- n[4].i = height;
- }
- if (ctx->ExecuteFlag) {
- CALL_Scissor(ctx->Exec, (x, y, width, height));
- }
-}
-
-
-static void GLAPIENTRY
-save_ShadeModel(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx);
-
- if (ctx->ExecuteFlag) {
- CALL_ShadeModel(ctx->Exec, (mode));
- }
-
- if (ctx->ListState.Current.ShadeModel == mode)
- return;
-
- SAVE_FLUSH_VERTICES(ctx);
-
- /* Only save the value if we know the statechange will take effect:
- */
- if (ctx->Driver.CurrentSavePrimitive == PRIM_OUTSIDE_BEGIN_END)
- ctx->ListState.Current.ShadeModel = mode;
-
- n = alloc_instruction(ctx, OPCODE_SHADE_MODEL, 1);
- if (n) {
- n[1].e = mode;
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilFunc(GLenum func, GLint ref, GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC, 3);
- if (n) {
- n[1].e = func;
- n[2].i = ref;
- n[3].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilFunc(ctx->Exec, (func, ref, mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilMask(GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_MASK, 1);
- if (n) {
- n[1].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilMask(ctx->Exec, (mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilOp(GLenum fail, GLenum zfail, GLenum zpass)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_OP, 3);
- if (n) {
- n[1].e = fail;
- n[2].e = zfail;
- n[3].e = zpass;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilOp(ctx->Exec, (fail, zfail, zpass));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
- if (n) {
- n[1].e = face;
- n[2].e = func;
- n[3].i = ref;
- n[4].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilFuncSeparate(ctx->Exec, (face, func, ref, mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, GLint ref,
- GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- /* GL_FRONT */
- n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
- if (n) {
- n[1].e = GL_FRONT;
- n[2].e = frontfunc;
- n[3].i = ref;
- n[4].ui = mask;
- }
- /* GL_BACK */
- n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
- if (n) {
- n[1].e = GL_BACK;
- n[2].e = backfunc;
- n[3].i = ref;
- n[4].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilFuncSeparate(ctx->Exec, (GL_FRONT, frontfunc, ref, mask));
- CALL_StencilFuncSeparate(ctx->Exec, (GL_BACK, backfunc, ref, mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilMaskSeparate(GLenum face, GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_MASK_SEPARATE, 2);
- if (n) {
- n[1].e = face;
- n[2].ui = mask;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilMaskSeparate(ctx->Exec, (face, mask));
- }
-}
-
-
-static void GLAPIENTRY
-save_StencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_STENCIL_OP_SEPARATE, 4);
- if (n) {
- n[1].e = face;
- n[2].e = fail;
- n[3].e = zfail;
- n[4].e = zpass;
- }
- if (ctx->ExecuteFlag) {
- CALL_StencilOpSeparate(ctx->Exec, (face, fail, zfail, zpass));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexEnvfv(GLenum target, GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEXENV, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- if (pname == GL_TEXTURE_ENV_COLOR) {
- n[3].f = params[0];
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- else {
- n[3].f = params[0];
- n[4].f = n[5].f = n[6].f = 0.0F;
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_TexEnvfv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexEnvf(GLenum target, GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = (GLfloat) param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_TexEnvfv(target, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_TexEnvi(GLenum target, GLenum pname, GLint param)
-{
- GLfloat p[4];
- p[0] = (GLfloat) param;
- p[1] = p[2] = p[3] = 0.0F;
- save_TexEnvfv(target, pname, p);
-}
-
-
-static void GLAPIENTRY
-save_TexEnviv(GLenum target, GLenum pname, const GLint * param)
-{
- GLfloat p[4];
- if (pname == GL_TEXTURE_ENV_COLOR) {
- p[0] = INT_TO_FLOAT(param[0]);
- p[1] = INT_TO_FLOAT(param[1]);
- p[2] = INT_TO_FLOAT(param[2]);
- p[3] = INT_TO_FLOAT(param[3]);
- }
- else {
- p[0] = (GLfloat) param[0];
- p[1] = p[2] = p[3] = 0.0F;
- }
- save_TexEnvfv(target, pname, p);
-}
-
-
-static void GLAPIENTRY
-save_TexGenfv(GLenum coord, GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEXGEN, 6);
- if (n) {
- n[1].e = coord;
- n[2].e = pname;
- n[3].f = params[0];
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_TexGenfv(ctx->Exec, (coord, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexGeniv(GLenum coord, GLenum pname, const GLint *params)
-{
- GLfloat p[4];
- p[0] = (GLfloat) params[0];
- p[1] = (GLfloat) params[1];
- p[2] = (GLfloat) params[2];
- p[3] = (GLfloat) params[3];
- save_TexGenfv(coord, pname, p);
-}
-
-
-static void GLAPIENTRY
-save_TexGend(GLenum coord, GLenum pname, GLdouble param)
-{
- GLfloat parray[4];
- parray[0] = (GLfloat) param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_TexGenfv(coord, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_TexGendv(GLenum coord, GLenum pname, const GLdouble *params)
-{
- GLfloat p[4];
- p[0] = (GLfloat) params[0];
- p[1] = (GLfloat) params[1];
- p[2] = (GLfloat) params[2];
- p[3] = (GLfloat) params[3];
- save_TexGenfv(coord, pname, p);
-}
-
-
-static void GLAPIENTRY
-save_TexGenf(GLenum coord, GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_TexGenfv(coord, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_TexGeni(GLenum coord, GLenum pname, GLint param)
-{
- GLint parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0;
- save_TexGeniv(coord, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_TexParameterfv(GLenum target, GLenum pname, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEXPARAMETER, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].f = params[0];
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_TexParameterfv(ctx->Exec, (target, pname, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexParameterf(GLenum target, GLenum pname, GLfloat param)
-{
- GLfloat parray[4];
- parray[0] = param;
- parray[1] = parray[2] = parray[3] = 0.0F;
- save_TexParameterfv(target, pname, parray);
-}
-
-
-static void GLAPIENTRY
-save_TexParameteri(GLenum target, GLenum pname, GLint param)
-{
- GLfloat fparam[4];
- fparam[0] = (GLfloat) param;
- fparam[1] = fparam[2] = fparam[3] = 0.0F;
- save_TexParameterfv(target, pname, fparam);
-}
-
-
-static void GLAPIENTRY
-save_TexParameteriv(GLenum target, GLenum pname, const GLint *params)
-{
- GLfloat fparam[4];
- fparam[0] = (GLfloat) params[0];
- fparam[1] = fparam[2] = fparam[3] = 0.0F;
- save_TexParameterfv(target, pname, fparam);
-}
-
-
-static void GLAPIENTRY
-save_TexImage1D(GLenum target,
- GLint level, GLint components,
- GLsizei width, GLint border,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_1D) {
- /* don't compile, execute immediately */
- CALL_TexImage1D(ctx->Exec, (target, level, components, width,
- border, format, type, pixels));
- }
- else {
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEX_IMAGE1D, 8);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = components;
- n[4].i = (GLint) width;
- n[5].i = border;
- n[6].e = format;
- n[7].e = type;
- n[8].data = unpack_image(ctx, 1, width, 1, 1, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexImage1D(ctx->Exec, (target, level, components, width,
- border, format, type, pixels));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_TexImage2D(GLenum target,
- GLint level, GLint components,
- GLsizei width, GLsizei height, GLint border,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_2D) {
- /* don't compile, execute immediately */
- CALL_TexImage2D(ctx->Exec, (target, level, components, width,
- height, border, format, type, pixels));
- }
- else {
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEX_IMAGE2D, 9);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = components;
- n[4].i = (GLint) width;
- n[5].i = (GLint) height;
- n[6].i = border;
- n[7].e = format;
- n[8].e = type;
- n[9].data = unpack_image(ctx, 2, width, height, 1, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexImage2D(ctx->Exec, (target, level, components, width,
- height, border, format, type, pixels));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_TexImage3D(GLenum target,
- GLint level, GLint internalFormat,
- GLsizei width, GLsizei height, GLsizei depth,
- GLint border,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_3D) {
- /* don't compile, execute immediately */
- CALL_TexImage3D(ctx->Exec, (target, level, internalFormat, width,
- height, depth, border, format, type,
- pixels));
- }
- else {
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEX_IMAGE3D, 10);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = (GLint) internalFormat;
- n[4].i = (GLint) width;
- n[5].i = (GLint) height;
- n[6].i = (GLint) depth;
- n[7].i = border;
- n[8].e = format;
- n[9].e = type;
- n[10].data = unpack_image(ctx, 3, width, height, depth, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexImage3D(ctx->Exec, (target, level, internalFormat, width,
- height, depth, border, format, type,
- pixels));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_TexSubImage1D(GLenum target, GLint level, GLint xoffset,
- GLsizei width, GLenum format, GLenum type,
- const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE1D, 7);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = (GLint) width;
- n[5].e = format;
- n[6].e = type;
- n[7].data = unpack_image(ctx, 1, width, 1, 1, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexSubImage1D(ctx->Exec, (target, level, xoffset, width,
- format, type, pixels));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexSubImage2D(GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLsizei width, GLsizei height,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE2D, 9);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = (GLint) width;
- n[6].i = (GLint) height;
- n[7].e = format;
- n[8].e = type;
- n[9].data = unpack_image(ctx, 2, width, height, 1, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexSubImage2D(ctx->Exec, (target, level, xoffset, yoffset,
- width, height, format, type, pixels));
- }
-}
-
-
-static void GLAPIENTRY
-save_TexSubImage3D(GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE3D, 11);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = zoffset;
- n[6].i = (GLint) width;
- n[7].i = (GLint) height;
- n[8].i = (GLint) depth;
- n[9].e = format;
- n[10].e = type;
- n[11].data = unpack_image(ctx, 3, width, height, depth, format, type,
- pixels, &ctx->Unpack);
- }
- if (ctx->ExecuteFlag) {
- CALL_TexSubImage3D(ctx->Exec, (target, level,
- xoffset, yoffset, zoffset,
- width, height, depth, format, type,
- pixels));
- }
-}
-
-
-static void GLAPIENTRY
-save_Translatef(GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TRANSLATE, 3);
- if (n) {
- n[1].f = x;
- n[2].f = y;
- n[3].f = z;
- }
- if (ctx->ExecuteFlag) {
- CALL_Translatef(ctx->Exec, (x, y, z));
- }
-}
-
-
-static void GLAPIENTRY
-save_Translated(GLdouble x, GLdouble y, GLdouble z)
-{
- save_Translatef((GLfloat) x, (GLfloat) y, (GLfloat) z);
-}
-
-
-
-static void GLAPIENTRY
-save_Viewport(GLint x, GLint y, GLsizei width, GLsizei height)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_VIEWPORT, 4);
- if (n) {
- n[1].i = x;
- n[2].i = y;
- n[3].i = (GLint) width;
- n[4].i = (GLint) height;
- }
- if (ctx->ExecuteFlag) {
- CALL_Viewport(ctx->Exec, (x, y, width, height));
- }
-}
-
-
-static void GLAPIENTRY
-save_WindowPos4fMESA(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_WINDOW_POS, 4);
- if (n) {
- n[1].f = x;
- n[2].f = y;
- n[3].f = z;
- n[4].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_WindowPos4fMESA(ctx->Exec, (x, y, z, w));
- }
-}
-
-static void GLAPIENTRY
-save_WindowPos2dMESA(GLdouble x, GLdouble y)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2fMESA(GLfloat x, GLfloat y)
-{
- save_WindowPos4fMESA(x, y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2iMESA(GLint x, GLint y)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2sMESA(GLshort x, GLshort y)
-{
- save_WindowPos4fMESA(x, y, 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3dMESA(GLdouble x, GLdouble y, GLdouble z)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3fMESA(GLfloat x, GLfloat y, GLfloat z)
-{
- save_WindowPos4fMESA(x, y, z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3iMESA(GLint x, GLint y, GLint z)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3sMESA(GLshort x, GLshort y, GLshort z)
-{
- save_WindowPos4fMESA(x, y, z, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos4dMESA(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
-}
-
-static void GLAPIENTRY
-save_WindowPos4iMESA(GLint x, GLint y, GLint z, GLint w)
-{
- save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
-}
-
-static void GLAPIENTRY
-save_WindowPos4sMESA(GLshort x, GLshort y, GLshort z, GLshort w)
-{
- save_WindowPos4fMESA(x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_WindowPos2dvMESA(const GLdouble * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2fvMESA(const GLfloat * v)
-{
- save_WindowPos4fMESA(v[0], v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2ivMESA(const GLint * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos2svMESA(const GLshort * v)
-{
- save_WindowPos4fMESA(v[0], v[1], 0.0F, 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3dvMESA(const GLdouble * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3fvMESA(const GLfloat * v)
-{
- save_WindowPos4fMESA(v[0], v[1], v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3ivMESA(const GLint * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos3svMESA(const GLshort * v)
-{
- save_WindowPos4fMESA(v[0], v[1], v[2], 1.0F);
-}
-
-static void GLAPIENTRY
-save_WindowPos4dvMESA(const GLdouble * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1],
- (GLfloat) v[2], (GLfloat) v[3]);
-}
-
-static void GLAPIENTRY
-save_WindowPos4fvMESA(const GLfloat * v)
-{
- save_WindowPos4fMESA(v[0], v[1], v[2], v[3]);
-}
-
-static void GLAPIENTRY
-save_WindowPos4ivMESA(const GLint * v)
-{
- save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1],
- (GLfloat) v[2], (GLfloat) v[3]);
-}
-
-static void GLAPIENTRY
-save_WindowPos4svMESA(const GLshort * v)
-{
- save_WindowPos4fMESA(v[0], v[1], v[2], v[3]);
-}
-
-
-
-/* GL_ARB_multitexture */
-static void GLAPIENTRY
-save_ActiveTextureARB(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ACTIVE_TEXTURE, 1);
- if (n) {
- n[1].e = target;
- }
- if (ctx->ExecuteFlag) {
- CALL_ActiveTextureARB(ctx->Exec, (target));
- }
-}
-
-
-/* GL_ARB_transpose_matrix */
-
-static void GLAPIENTRY
-save_LoadTransposeMatrixdARB(const GLdouble m[16])
-{
- GLfloat tm[16];
- _math_transposefd(tm, m);
- save_LoadMatrixf(tm);
-}
-
-
-static void GLAPIENTRY
-save_LoadTransposeMatrixfARB(const GLfloat m[16])
-{
- GLfloat tm[16];
- _math_transposef(tm, m);
- save_LoadMatrixf(tm);
-}
-
-
-static void GLAPIENTRY
-save_MultTransposeMatrixdARB(const GLdouble m[16])
-{
- GLfloat tm[16];
- _math_transposefd(tm, m);
- save_MultMatrixf(tm);
-}
-
-
-static void GLAPIENTRY
-save_MultTransposeMatrixfARB(const GLfloat m[16])
-{
- GLfloat tm[16];
- _math_transposef(tm, m);
- save_MultMatrixf(tm);
-}
-
-
-/* GL_ARB_texture_compression */
-static void GLAPIENTRY
-save_CompressedTexImage1DARB(GLenum target, GLint level,
- GLenum internalFormat, GLsizei width,
- GLint border, GLsizei imageSize,
- const GLvoid * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_1D) {
- /* don't compile, execute immediately */
- CALL_CompressedTexImage1DARB(ctx->Exec, (target, level, internalFormat,
- width, border, imageSize,
- data));
- }
- else {
- Node *n;
- GLvoid *image;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage1DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_1D, 7);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].e = internalFormat;
- n[4].i = (GLint) width;
- n[5].i = border;
- n[6].i = imageSize;
- n[7].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexImage1DARB(ctx->Exec,
- (target, level, internalFormat, width,
- border, imageSize, data));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_CompressedTexImage2DARB(GLenum target, GLint level,
- GLenum internalFormat, GLsizei width,
- GLsizei height, GLint border, GLsizei imageSize,
- const GLvoid * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_2D) {
- /* don't compile, execute immediately */
- CALL_CompressedTexImage2DARB(ctx->Exec, (target, level, internalFormat,
- width, height, border,
- imageSize, data));
- }
- else {
- Node *n;
- GLvoid *image;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage2DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_2D, 8);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].e = internalFormat;
- n[4].i = (GLint) width;
- n[5].i = (GLint) height;
- n[6].i = border;
- n[7].i = imageSize;
- n[8].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexImage2DARB(ctx->Exec,
- (target, level, internalFormat, width,
- height, border, imageSize, data));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_CompressedTexImage3DARB(GLenum target, GLint level,
- GLenum internalFormat, GLsizei width,
- GLsizei height, GLsizei depth, GLint border,
- GLsizei imageSize, const GLvoid * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (target == GL_PROXY_TEXTURE_3D) {
- /* don't compile, execute immediately */
- CALL_CompressedTexImage3DARB(ctx->Exec, (target, level, internalFormat,
- width, height, depth, border,
- imageSize, data));
- }
- else {
- Node *n;
- GLvoid *image;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage3DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_3D, 9);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].e = internalFormat;
- n[4].i = (GLint) width;
- n[5].i = (GLint) height;
- n[6].i = (GLint) depth;
- n[7].i = border;
- n[8].i = imageSize;
- n[9].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexImage3DARB(ctx->Exec,
- (target, level, internalFormat, width,
- height, depth, border, imageSize,
- data));
- }
- }
-}
-
-
-static void GLAPIENTRY
-save_CompressedTexSubImage1DARB(GLenum target, GLint level, GLint xoffset,
- GLsizei width, GLenum format,
- GLsizei imageSize, const GLvoid * data)
-{
- Node *n;
- GLvoid *image;
-
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage1DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D, 7);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = (GLint) width;
- n[5].e = format;
- n[6].i = imageSize;
- n[7].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexSubImage1DARB(ctx->Exec, (target, level, xoffset,
- width, format, imageSize,
- data));
- }
-}
-
-
-static void GLAPIENTRY
-save_CompressedTexSubImage2DARB(GLenum target, GLint level, GLint xoffset,
- GLint yoffset, GLsizei width, GLsizei height,
- GLenum format, GLsizei imageSize,
- const GLvoid * data)
-{
- Node *n;
- GLvoid *image;
-
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage2DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D, 9);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = (GLint) width;
- n[6].i = (GLint) height;
- n[7].e = format;
- n[8].i = imageSize;
- n[9].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexSubImage2DARB(ctx->Exec,
- (target, level, xoffset, yoffset, width,
- height, format, imageSize, data));
- }
-}
-
-
-static void GLAPIENTRY
-save_CompressedTexSubImage3DARB(GLenum target, GLint level, GLint xoffset,
- GLint yoffset, GLint zoffset, GLsizei width,
- GLsizei height, GLsizei depth, GLenum format,
- GLsizei imageSize, const GLvoid * data)
-{
- Node *n;
- GLvoid *image;
-
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- /* make copy of image */
- image = malloc(imageSize);
- if (!image) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage3DARB");
- return;
- }
- memcpy(image, data, imageSize);
- n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D, 11);
- if (n) {
- n[1].e = target;
- n[2].i = level;
- n[3].i = xoffset;
- n[4].i = yoffset;
- n[5].i = zoffset;
- n[6].i = (GLint) width;
- n[7].i = (GLint) height;
- n[8].i = (GLint) depth;
- n[9].e = format;
- n[10].i = imageSize;
- n[11].data = image;
- }
- else if (image) {
- free(image);
- }
- if (ctx->ExecuteFlag) {
- CALL_CompressedTexSubImage3DARB(ctx->Exec,
- (target, level, xoffset, yoffset,
- zoffset, width, height, depth, format,
- imageSize, data));
- }
-}
-
-
-/* GL_ARB_multisample */
-static void GLAPIENTRY
-save_SampleCoverageARB(GLclampf value, GLboolean invert)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_SAMPLE_COVERAGE, 2);
- if (n) {
- n[1].f = value;
- n[2].b = invert;
- }
- if (ctx->ExecuteFlag) {
- CALL_SampleCoverageARB(ctx->Exec, (value, invert));
- }
-}
-
-
-/*
- * GL_NV_vertex_program
- */
-#if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
-static void GLAPIENTRY
-save_BindProgramNV(GLenum target, GLuint id)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BIND_PROGRAM_NV, 2);
- if (n) {
- n[1].e = target;
- n[2].ui = id;
- }
- if (ctx->ExecuteFlag) {
- CALL_BindProgramNV(ctx->Exec, (target, id));
- }
-}
-
-static void GLAPIENTRY
-save_ProgramEnvParameter4fARB(GLenum target, GLuint index,
- GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROGRAM_ENV_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = x;
- n[4].f = y;
- n[5].f = z;
- n[6].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramEnvParameter4fARB(ctx->Exec, (target, index, x, y, z, w));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramEnvParameter4fvARB(GLenum target, GLuint index,
- const GLfloat *params)
-{
- save_ProgramEnvParameter4fARB(target, index, params[0], params[1],
- params[2], params[3]);
-}
-
-
-static void GLAPIENTRY
-save_ProgramEnvParameters4fvEXT(GLenum target, GLuint index, GLsizei count,
- const GLfloat * params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- if (count > 0) {
- GLint i;
- const GLfloat * p = params;
-
- for (i = 0 ; i < count ; i++) {
- n = alloc_instruction(ctx, OPCODE_PROGRAM_ENV_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = p[0];
- n[4].f = p[1];
- n[5].f = p[2];
- n[6].f = p[3];
- p += 4;
- }
- }
- }
-
- if (ctx->ExecuteFlag) {
- CALL_ProgramEnvParameters4fvEXT(ctx->Exec, (target, index, count, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramEnvParameter4dARB(GLenum target, GLuint index,
- GLdouble x, GLdouble y, GLdouble z, GLdouble w)
-{
- save_ProgramEnvParameter4fARB(target, index,
- (GLfloat) x,
- (GLfloat) y, (GLfloat) z, (GLfloat) w);
-}
-
-
-static void GLAPIENTRY
-save_ProgramEnvParameter4dvARB(GLenum target, GLuint index,
- const GLdouble *params)
-{
- save_ProgramEnvParameter4fARB(target, index,
- (GLfloat) params[0],
- (GLfloat) params[1],
- (GLfloat) params[2], (GLfloat) params[3]);
-}
-
-#endif /* FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program || FEATURE_NV_vertex_program */
-
-#if FEATURE_NV_vertex_program
-static void GLAPIENTRY
-save_ExecuteProgramNV(GLenum target, GLuint id, const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_EXECUTE_PROGRAM_NV, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = id;
- n[3].f = params[0];
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_ExecuteProgramNV(ctx->Exec, (target, id, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramParameters4dvNV(GLenum target, GLuint index,
- GLsizei num, const GLdouble *params)
-{
- GLint i;
- for (i = 0; i < num; i++) {
- save_ProgramEnvParameter4dvARB(target, index + i, params + 4 * i);
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramParameters4fvNV(GLenum target, GLuint index,
- GLsizei num, const GLfloat *params)
-{
- GLint i;
- for (i = 0; i < num; i++) {
- save_ProgramEnvParameter4fvARB(target, index + i, params + 4 * i);
- }
-}
-
-
-static void GLAPIENTRY
-save_LoadProgramNV(GLenum target, GLuint id, GLsizei len,
- const GLubyte * program)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_LOAD_PROGRAM_NV, 4);
- if (n) {
- GLubyte *programCopy = (GLubyte *) malloc(len);
- if (!programCopy) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV");
- return;
- }
- memcpy(programCopy, program, len);
- n[1].e = target;
- n[2].ui = id;
- n[3].i = len;
- n[4].data = programCopy;
- }
- if (ctx->ExecuteFlag) {
- CALL_LoadProgramNV(ctx->Exec, (target, id, len, program));
- }
-}
-
-
-static void GLAPIENTRY
-save_RequestResidentProgramsNV(GLsizei num, const GLuint * ids)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_TRACK_MATRIX_NV, 2);
- if (n) {
- GLuint *idCopy = (GLuint *) malloc(num * sizeof(GLuint));
- if (!idCopy) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glRequestResidentProgramsNV");
- return;
- }
- memcpy(idCopy, ids, num * sizeof(GLuint));
- n[1].i = num;
- n[2].data = idCopy;
- }
- if (ctx->ExecuteFlag) {
- CALL_RequestResidentProgramsNV(ctx->Exec, (num, ids));
- }
-}
-
-
-static void GLAPIENTRY
-save_TrackMatrixNV(GLenum target, GLuint address,
- GLenum matrix, GLenum transform)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TRACK_MATRIX_NV, 4);
- if (n) {
- n[1].e = target;
- n[2].ui = address;
- n[3].e = matrix;
- n[4].e = transform;
- }
- if (ctx->ExecuteFlag) {
- CALL_TrackMatrixNV(ctx->Exec, (target, address, matrix, transform));
- }
-}
-#endif /* FEATURE_NV_vertex_program */
-
-
-/*
- * GL_NV_fragment_program
- */
-#if FEATURE_NV_fragment_program
-static void GLAPIENTRY
-save_ProgramLocalParameter4fARB(GLenum target, GLuint index,
- GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = x;
- n[4].f = y;
- n[5].f = z;
- n[6].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramLocalParameter4fARB(ctx->Exec, (target, index, x, y, z, w));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramLocalParameter4fvARB(GLenum target, GLuint index,
- const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = params[0];
- n[4].f = params[1];
- n[5].f = params[2];
- n[6].f = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramLocalParameter4fvARB(ctx->Exec, (target, index, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramLocalParameters4fvEXT(GLenum target, GLuint index, GLsizei count,
- const GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- if (count > 0) {
- GLint i;
- const GLfloat * p = params;
-
- for (i = 0 ; i < count ; i++) {
- n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = p[0];
- n[4].f = p[1];
- n[5].f = p[2];
- n[6].f = p[3];
- p += 4;
- }
- }
- }
-
- if (ctx->ExecuteFlag) {
- CALL_ProgramLocalParameters4fvEXT(ctx->Exec, (target, index, count, params));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramLocalParameter4dARB(GLenum target, GLuint index,
- GLdouble x, GLdouble y,
- GLdouble z, GLdouble w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = (GLfloat) x;
- n[4].f = (GLfloat) y;
- n[5].f = (GLfloat) z;
- n[6].f = (GLfloat) w;
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramLocalParameter4dARB(ctx->Exec, (target, index, x, y, z, w));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramLocalParameter4dvARB(GLenum target, GLuint index,
- const GLdouble *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
- if (n) {
- n[1].e = target;
- n[2].ui = index;
- n[3].f = (GLfloat) params[0];
- n[4].f = (GLfloat) params[1];
- n[5].f = (GLfloat) params[2];
- n[6].f = (GLfloat) params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramLocalParameter4dvARB(ctx->Exec, (target, index, params));
- }
-}
-
-static void GLAPIENTRY
-save_ProgramNamedParameter4fNV(GLuint id, GLsizei len, const GLubyte * name,
- GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_PROGRAM_NAMED_PARAMETER_NV, 6);
- if (n) {
- GLubyte *nameCopy = (GLubyte *) malloc(len);
- if (!nameCopy) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glProgramNamedParameter4fNV");
- return;
- }
- memcpy(nameCopy, name, len);
- n[1].ui = id;
- n[2].i = len;
- n[3].data = nameCopy;
- n[4].f = x;
- n[5].f = y;
- n[6].f = z;
- n[7].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramNamedParameter4fNV(ctx->Exec, (id, len, name, x, y, z, w));
- }
-}
-
-
-static void GLAPIENTRY
-save_ProgramNamedParameter4fvNV(GLuint id, GLsizei len, const GLubyte * name,
- const float v[])
-{
- save_ProgramNamedParameter4fNV(id, len, name, v[0], v[1], v[2], v[3]);
-}
-
-
-static void GLAPIENTRY
-save_ProgramNamedParameter4dNV(GLuint id, GLsizei len, const GLubyte * name,
- GLdouble x, GLdouble y, GLdouble z, GLdouble w)
-{
- save_ProgramNamedParameter4fNV(id, len, name, (GLfloat) x, (GLfloat) y,
- (GLfloat) z, (GLfloat) w);
-}
-
-
-static void GLAPIENTRY
-save_ProgramNamedParameter4dvNV(GLuint id, GLsizei len, const GLubyte * name,
- const double v[])
-{
- save_ProgramNamedParameter4fNV(id, len, name, (GLfloat) v[0],
- (GLfloat) v[1], (GLfloat) v[2],
- (GLfloat) v[3]);
-}
-
-#endif /* FEATURE_NV_fragment_program */
-
-
-
-/* GL_EXT_stencil_two_side */
-static void GLAPIENTRY
-save_ActiveStencilFaceEXT(GLenum face)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ACTIVE_STENCIL_FACE_EXT, 1);
- if (n) {
- n[1].e = face;
- }
- if (ctx->ExecuteFlag) {
- CALL_ActiveStencilFaceEXT(ctx->Exec, (face));
- }
-}
-
-
-/* GL_EXT_depth_bounds_test */
-static void GLAPIENTRY
-save_DepthBoundsEXT(GLclampd zmin, GLclampd zmax)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DEPTH_BOUNDS_EXT, 2);
- if (n) {
- n[1].f = (GLfloat) zmin;
- n[2].f = (GLfloat) zmax;
- }
- if (ctx->ExecuteFlag) {
- CALL_DepthBoundsEXT(ctx->Exec, (zmin, zmax));
- }
-}
-
-
-
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
-
-static void GLAPIENTRY
-save_ProgramStringARB(GLenum target, GLenum format, GLsizei len,
- const GLvoid * string)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
-
- n = alloc_instruction(ctx, OPCODE_PROGRAM_STRING_ARB, 4);
- if (n) {
- GLubyte *programCopy = (GLubyte *) malloc(len);
- if (!programCopy) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glProgramStringARB");
- return;
- }
- memcpy(programCopy, string, len);
- n[1].e = target;
- n[2].e = format;
- n[3].i = len;
- n[4].data = programCopy;
- }
- if (ctx->ExecuteFlag) {
- CALL_ProgramStringARB(ctx->Exec, (target, format, len, string));
- }
-}
-
-#endif /* FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program */
-
-
-#if FEATURE_queryobj
-
-static void GLAPIENTRY
-save_BeginQueryARB(GLenum target, GLuint id)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BEGIN_QUERY_ARB, 2);
- if (n) {
- n[1].e = target;
- n[2].ui = id;
- }
- if (ctx->ExecuteFlag) {
- CALL_BeginQueryARB(ctx->Exec, (target, id));
- }
-}
-
-
-static void GLAPIENTRY
-save_EndQueryARB(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_END_QUERY_ARB, 1);
- if (n) {
- n[1].e = target;
- }
- if (ctx->ExecuteFlag) {
- CALL_EndQueryARB(ctx->Exec, (target));
- }
-}
-
-#endif /* FEATURE_queryobj */
-
-
-static void GLAPIENTRY
-save_DrawBuffersARB(GLsizei count, const GLenum * buffers)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_DRAW_BUFFERS_ARB, 1 + MAX_DRAW_BUFFERS);
- if (n) {
- GLint i;
- n[1].i = count;
- if (count > MAX_DRAW_BUFFERS)
- count = MAX_DRAW_BUFFERS;
- for (i = 0; i < count; i++) {
- n[2 + i].e = buffers[i];
- }
- }
- if (ctx->ExecuteFlag) {
- CALL_DrawBuffersARB(ctx->Exec, (count, buffers));
- }
-}
-
-static void GLAPIENTRY
-save_TexBumpParameterfvATI(GLenum pname, const GLfloat *param)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- n = alloc_instruction(ctx, OPCODE_TEX_BUMP_PARAMETER_ATI, 5);
- if (n) {
- n[1].ui = pname;
- n[2].f = param[0];
- n[3].f = param[1];
- n[4].f = param[2];
- n[5].f = param[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_TexBumpParameterfvATI(ctx->Exec, (pname, param));
- }
-}
-
-static void GLAPIENTRY
-save_TexBumpParameterivATI(GLenum pname, const GLint *param)
-{
- GLfloat p[4];
- p[0] = INT_TO_FLOAT(param[0]);
- p[1] = INT_TO_FLOAT(param[1]);
- p[2] = INT_TO_FLOAT(param[2]);
- p[3] = INT_TO_FLOAT(param[3]);
- save_TexBumpParameterfvATI(pname, p);
-}
-
-#if FEATURE_ATI_fragment_shader
-static void GLAPIENTRY
-save_BindFragmentShaderATI(GLuint id)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- n = alloc_instruction(ctx, OPCODE_BIND_FRAGMENT_SHADER_ATI, 1);
- if (n) {
- n[1].ui = id;
- }
- if (ctx->ExecuteFlag) {
- CALL_BindFragmentShaderATI(ctx->Exec, (id));
- }
-}
-
-static void GLAPIENTRY
-save_SetFragmentShaderConstantATI(GLuint dst, const GLfloat *value)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
-
- n = alloc_instruction(ctx, OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI, 5);
- if (n) {
- n[1].ui = dst;
- n[2].f = value[0];
- n[3].f = value[1];
- n[4].f = value[2];
- n[5].f = value[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_SetFragmentShaderConstantATI(ctx->Exec, (dst, value));
- }
-}
-#endif
-
-static void
-save_Attr1fNV(GLenum attr, GLfloat x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_1F_NV, 2);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 1;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, 0, 0, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib1fNV(ctx->Exec, (attr, x));
- }
-}
-
-static void
-save_Attr2fNV(GLenum attr, GLfloat x, GLfloat y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_2F_NV, 3);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 2;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, 0, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib2fNV(ctx->Exec, (attr, x, y));
- }
-}
-
-static void
-save_Attr3fNV(GLenum attr, GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_3F_NV, 4);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 3;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib3fNV(ctx->Exec, (attr, x, y, z));
- }
-}
-
-static void
-save_Attr4fNV(GLenum attr, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_4F_NV, 5);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- n[5].f = w;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 4;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, w);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib4fNV(ctx->Exec, (attr, x, y, z, w));
- }
-}
-
-
-static void
-save_Attr1fARB(GLenum attr, GLfloat x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_1F_ARB, 2);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 1;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, 0, 0, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib1fARB(ctx->Exec, (attr, x));
- }
-}
-
-static void
-save_Attr2fARB(GLenum attr, GLfloat x, GLfloat y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_2F_ARB, 3);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 2;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, 0, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib2fARB(ctx->Exec, (attr, x, y));
- }
-}
-
-static void
-save_Attr3fARB(GLenum attr, GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_3F_ARB, 4);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 3;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, 1);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib3fARB(ctx->Exec, (attr, x, y, z));
- }
-}
-
-static void
-save_Attr4fARB(GLenum attr, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_ATTR_4F_ARB, 5);
- if (n) {
- n[1].e = attr;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- n[5].f = w;
- }
-
- ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
- ctx->ListState.ActiveAttribSize[attr] = 4;
- ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, w);
-
- if (ctx->ExecuteFlag) {
- CALL_VertexAttrib4fARB(ctx->Exec, (attr, x, y, z, w));
- }
-}
-
-
-static void GLAPIENTRY
-save_EvalCoord1f(GLfloat x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_EVAL_C1, 1);
- if (n) {
- n[1].f = x;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalCoord1f(ctx->Exec, (x));
- }
-}
-
-static void GLAPIENTRY
-save_EvalCoord1fv(const GLfloat * v)
-{
- save_EvalCoord1f(v[0]);
-}
-
-static void GLAPIENTRY
-save_EvalCoord2f(GLfloat x, GLfloat y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_EVAL_C2, 2);
- if (n) {
- n[1].f = x;
- n[2].f = y;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalCoord2f(ctx->Exec, (x, y));
- }
-}
-
-static void GLAPIENTRY
-save_EvalCoord2fv(const GLfloat * v)
-{
- save_EvalCoord2f(v[0], v[1]);
-}
-
-
-static void GLAPIENTRY
-save_EvalPoint1(GLint x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_EVAL_P1, 1);
- if (n) {
- n[1].i = x;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalPoint1(ctx->Exec, (x));
- }
-}
-
-static void GLAPIENTRY
-save_EvalPoint2(GLint x, GLint y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_EVAL_P2, 2);
- if (n) {
- n[1].i = x;
- n[2].i = y;
- }
- if (ctx->ExecuteFlag) {
- CALL_EvalPoint2(ctx->Exec, (x, y));
- }
-}
-
-static void GLAPIENTRY
-save_Indexf(GLfloat x)
-{
- save_Attr1fNV(VERT_ATTRIB_COLOR_INDEX, x);
-}
-
-static void GLAPIENTRY
-save_Indexfv(const GLfloat * v)
-{
- save_Attr1fNV(VERT_ATTRIB_COLOR_INDEX, v[0]);
-}
-
-static void GLAPIENTRY
-save_EdgeFlag(GLboolean x)
-{
- save_Attr1fNV(VERT_ATTRIB_EDGEFLAG, x ? (GLfloat)1.0 : (GLfloat)0.0);
-}
-
-static INLINE GLboolean compare4fv( const GLfloat *a,
- const GLfloat *b,
- GLuint count )
-{
- return memcmp( a, b, count * sizeof(GLfloat) ) == 0;
-}
-
-
-static void GLAPIENTRY
-save_Materialfv(GLenum face, GLenum pname, const GLfloat * param)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- int args, i;
- GLuint bitmask;
-
- switch (face) {
- case GL_BACK:
- case GL_FRONT:
- case GL_FRONT_AND_BACK:
- break;
- default:
- _mesa_compile_error(ctx, GL_INVALID_ENUM, "material(face)");
- return;
- }
-
- switch (pname) {
- case GL_EMISSION:
- case GL_AMBIENT:
- case GL_DIFFUSE:
- case GL_SPECULAR:
- case GL_AMBIENT_AND_DIFFUSE:
- args = 4;
- break;
- case GL_SHININESS:
- args = 1;
- break;
- case GL_COLOR_INDEXES:
- args = 3;
- break;
- default:
- _mesa_compile_error(ctx, GL_INVALID_ENUM, "material(pname)");
- return;
- }
-
- if (ctx->ExecuteFlag) {
- CALL_Materialfv(ctx->Exec, (face, pname, param));
- }
-
- bitmask = _mesa_material_bitmask(ctx, face, pname, ~0, NULL);
-
- /* Try to eliminate redundant statechanges. Because it is legal to
- * call glMaterial even inside begin/end calls, don't need to worry
- * about ctx->Driver.CurrentSavePrimitive here.
- */
- for (i = 0; i < MAT_ATTRIB_MAX; i++) {
- if (bitmask & (1 << i)) {
- if (ctx->ListState.ActiveMaterialSize[i] == args &&
- compare4fv(ctx->ListState.CurrentMaterial[i], param, args)) {
- bitmask &= ~(1 << i);
- }
- else {
- ctx->ListState.ActiveMaterialSize[i] = args;
- COPY_SZ_4V(ctx->ListState.CurrentMaterial[i], args, param);
- }
- }
- }
-
- /* If this call has effect, return early:
- */
- if (bitmask == 0)
- return;
-
- SAVE_FLUSH_VERTICES(ctx);
-
- n = alloc_instruction(ctx, OPCODE_MATERIAL, 6);
- if (n) {
- n[1].e = face;
- n[2].e = pname;
- for (i = 0; i < args; i++)
- n[3 + i].f = param[i];
- }
-}
-
-static void GLAPIENTRY
-save_Begin(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- GLboolean error = GL_FALSE;
-
- if ( /*mode < GL_POINTS || */ mode > GL_POLYGON) {
- _mesa_compile_error(ctx, GL_INVALID_ENUM, "Begin (mode)");
- error = GL_TRUE;
- }
- else if (ctx->Driver.CurrentSavePrimitive == PRIM_UNKNOWN) {
- /* Typically the first begin. This may raise an error on
- * playback, depending on whether CallList is issued from inside
- * a begin/end or not.
- */
- ctx->Driver.CurrentSavePrimitive = PRIM_INSIDE_UNKNOWN_PRIM;
- }
- else if (ctx->Driver.CurrentSavePrimitive == PRIM_OUTSIDE_BEGIN_END) {
- ctx->Driver.CurrentSavePrimitive = mode;
- }
- else {
- _mesa_compile_error(ctx, GL_INVALID_OPERATION, "recursive begin");
- error = GL_TRUE;
- }
-
- if (!error) {
- /* Give the driver an opportunity to hook in an optimized
- * display list compiler.
- */
- if (ctx->Driver.NotifySaveBegin(ctx, mode))
- return;
-
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_BEGIN, 1);
- if (n) {
- n[1].e = mode;
- }
- }
-
- if (ctx->ExecuteFlag) {
- CALL_Begin(ctx->Exec, (mode));
- }
-}
-
-static void GLAPIENTRY
-save_End(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- SAVE_FLUSH_VERTICES(ctx);
- (void) alloc_instruction(ctx, OPCODE_END, 0);
- ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
- if (ctx->ExecuteFlag) {
- CALL_End(ctx->Exec, ());
- }
-}
-
-static void GLAPIENTRY
-save_Rectf(GLfloat a, GLfloat b, GLfloat c, GLfloat d)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- SAVE_FLUSH_VERTICES(ctx);
- n = alloc_instruction(ctx, OPCODE_RECTF, 4);
- if (n) {
- n[1].f = a;
- n[2].f = b;
- n[3].f = c;
- n[4].f = d;
- }
- if (ctx->ExecuteFlag) {
- CALL_Rectf(ctx->Exec, (a, b, c, d));
- }
-}
-
-
-static void GLAPIENTRY
-save_Vertex2f(GLfloat x, GLfloat y)
-{
- save_Attr2fNV(VERT_ATTRIB_POS, x, y);
-}
-
-static void GLAPIENTRY
-save_Vertex2fv(const GLfloat * v)
-{
- save_Attr2fNV(VERT_ATTRIB_POS, v[0], v[1]);
-}
-
-static void GLAPIENTRY
-save_Vertex3f(GLfloat x, GLfloat y, GLfloat z)
-{
- save_Attr3fNV(VERT_ATTRIB_POS, x, y, z);
-}
-
-static void GLAPIENTRY
-save_Vertex3fv(const GLfloat * v)
-{
- save_Attr3fNV(VERT_ATTRIB_POS, v[0], v[1], v[2]);
-}
-
-static void GLAPIENTRY
-save_Vertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- save_Attr4fNV(VERT_ATTRIB_POS, x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_Vertex4fv(const GLfloat * v)
-{
- save_Attr4fNV(VERT_ATTRIB_POS, v[0], v[1], v[2], v[3]);
-}
-
-static void GLAPIENTRY
-save_TexCoord1f(GLfloat x)
-{
- save_Attr1fNV(VERT_ATTRIB_TEX0, x);
-}
-
-static void GLAPIENTRY
-save_TexCoord1fv(const GLfloat * v)
-{
- save_Attr1fNV(VERT_ATTRIB_TEX0, v[0]);
-}
-
-static void GLAPIENTRY
-save_TexCoord2f(GLfloat x, GLfloat y)
-{
- save_Attr2fNV(VERT_ATTRIB_TEX0, x, y);
-}
-
-static void GLAPIENTRY
-save_TexCoord2fv(const GLfloat * v)
-{
- save_Attr2fNV(VERT_ATTRIB_TEX0, v[0], v[1]);
-}
-
-static void GLAPIENTRY
-save_TexCoord3f(GLfloat x, GLfloat y, GLfloat z)
-{
- save_Attr3fNV(VERT_ATTRIB_TEX0, x, y, z);
-}
-
-static void GLAPIENTRY
-save_TexCoord3fv(const GLfloat * v)
-{
- save_Attr3fNV(VERT_ATTRIB_TEX0, v[0], v[1], v[2]);
-}
-
-static void GLAPIENTRY
-save_TexCoord4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- save_Attr4fNV(VERT_ATTRIB_TEX0, x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_TexCoord4fv(const GLfloat * v)
-{
- save_Attr4fNV(VERT_ATTRIB_TEX0, v[0], v[1], v[2], v[3]);
-}
-
-static void GLAPIENTRY
-save_Normal3f(GLfloat x, GLfloat y, GLfloat z)
-{
- save_Attr3fNV(VERT_ATTRIB_NORMAL, x, y, z);
-}
-
-static void GLAPIENTRY
-save_Normal3fv(const GLfloat * v)
-{
- save_Attr3fNV(VERT_ATTRIB_NORMAL, v[0], v[1], v[2]);
-}
-
-static void GLAPIENTRY
-save_FogCoordfEXT(GLfloat x)
-{
- save_Attr1fNV(VERT_ATTRIB_FOG, x);
-}
-
-static void GLAPIENTRY
-save_FogCoordfvEXT(const GLfloat * v)
-{
- save_Attr1fNV(VERT_ATTRIB_FOG, v[0]);
-}
-
-static void GLAPIENTRY
-save_Color3f(GLfloat x, GLfloat y, GLfloat z)
-{
- save_Attr3fNV(VERT_ATTRIB_COLOR0, x, y, z);
-}
-
-static void GLAPIENTRY
-save_Color3fv(const GLfloat * v)
-{
- save_Attr3fNV(VERT_ATTRIB_COLOR0, v[0], v[1], v[2]);
-}
-
-static void GLAPIENTRY
-save_Color4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- save_Attr4fNV(VERT_ATTRIB_COLOR0, x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_Color4fv(const GLfloat * v)
-{
- save_Attr4fNV(VERT_ATTRIB_COLOR0, v[0], v[1], v[2], v[3]);
-}
-
-static void GLAPIENTRY
-save_SecondaryColor3fEXT(GLfloat x, GLfloat y, GLfloat z)
-{
- save_Attr3fNV(VERT_ATTRIB_COLOR1, x, y, z);
-}
-
-static void GLAPIENTRY
-save_SecondaryColor3fvEXT(const GLfloat * v)
-{
- save_Attr3fNV(VERT_ATTRIB_COLOR1, v[0], v[1], v[2]);
-}
-
-
-/* Just call the respective ATTR for texcoord
- */
-static void GLAPIENTRY
-save_MultiTexCoord1f(GLenum target, GLfloat x)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr1fNV(attr, x);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord1fv(GLenum target, const GLfloat * v)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr1fNV(attr, v[0]);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord2f(GLenum target, GLfloat x, GLfloat y)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr2fNV(attr, x, y);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord2fv(GLenum target, const GLfloat * v)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr2fNV(attr, v[0], v[1]);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord3f(GLenum target, GLfloat x, GLfloat y, GLfloat z)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr3fNV(attr, x, y, z);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord3fv(GLenum target, const GLfloat * v)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr3fNV(attr, v[0], v[1], v[2]);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord4f(GLenum target, GLfloat x, GLfloat y,
- GLfloat z, GLfloat w)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr4fNV(attr, x, y, z, w);
-}
-
-static void GLAPIENTRY
-save_MultiTexCoord4fv(GLenum target, const GLfloat * v)
-{
- GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
- save_Attr4fNV(attr, v[0], v[1], v[2], v[3]);
-}
-
-
-/**
- * Record a GL_INVALID_VALUE error when a invalid vertex attribute
- * index is found.
- */
-static void
-index_error(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- _mesa_error(ctx, GL_INVALID_VALUE, "VertexAttribf(index)");
-}
-
-
-/* First level for NV_vertex_program:
- *
- * Check for errors at compile time?.
- */
-static void GLAPIENTRY
-save_VertexAttrib1fNV(GLuint index, GLfloat x)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr1fNV(index, x);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib1fvNV(GLuint index, const GLfloat * v)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr1fNV(index, v[0]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib2fNV(GLuint index, GLfloat x, GLfloat y)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr2fNV(index, x, y);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib2fvNV(GLuint index, const GLfloat * v)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr2fNV(index, v[0], v[1]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib3fNV(GLuint index, GLfloat x, GLfloat y, GLfloat z)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr3fNV(index, x, y, z);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib3fvNV(GLuint index, const GLfloat * v)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr3fNV(index, v[0], v[1], v[2]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib4fNV(GLuint index, GLfloat x, GLfloat y,
- GLfloat z, GLfloat w)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr4fNV(index, x, y, z, w);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib4fvNV(GLuint index, const GLfloat * v)
-{
- if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
- save_Attr4fNV(index, v[0], v[1], v[2], v[3]);
- else
- index_error();
-}
-
-
-
-
-static void GLAPIENTRY
-save_VertexAttrib1fARB(GLuint index, GLfloat x)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr1fARB(index, x);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib1fvARB(GLuint index, const GLfloat * v)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr1fARB(index, v[0]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib2fARB(GLuint index, GLfloat x, GLfloat y)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr2fARB(index, x, y);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib2fvARB(GLuint index, const GLfloat * v)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr2fARB(index, v[0], v[1]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib3fARB(GLuint index, GLfloat x, GLfloat y, GLfloat z)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr3fARB(index, x, y, z);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib3fvARB(GLuint index, const GLfloat * v)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr3fARB(index, v[0], v[1], v[2]);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib4fARB(GLuint index, GLfloat x, GLfloat y, GLfloat z,
- GLfloat w)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr4fARB(index, x, y, z, w);
- else
- index_error();
-}
-
-static void GLAPIENTRY
-save_VertexAttrib4fvARB(GLuint index, const GLfloat * v)
-{
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- save_Attr4fARB(index, v[0], v[1], v[2], v[3]);
- else
- index_error();
-}
-
-
-/* GL_ARB_shader_objects, GL_ARB_vertex/fragment_shader */
-
-static void GLAPIENTRY
-exec_BindAttribLocationARB(GLuint program, GLuint index, const GLchar *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_BindAttribLocationARB(ctx->Exec, (program, index, name));
-}
-
-static GLint GLAPIENTRY
-exec_GetAttribLocationARB(GLuint program, const GLchar *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_GetAttribLocationARB(ctx->Exec, (program, name));
-}
-
-static GLint GLAPIENTRY
-exec_GetUniformLocationARB(GLuint program, const GLchar *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_GetUniformLocationARB(ctx->Exec, (program, name));
-}
-/* XXX more shader functions needed here */
-
-
-#if FEATURE_EXT_framebuffer_blit
-static void GLAPIENTRY
-save_BlitFramebufferEXT(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
- GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
- GLbitfield mask, GLenum filter)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BLIT_FRAMEBUFFER, 10);
- if (n) {
- n[1].i = srcX0;
- n[2].i = srcY0;
- n[3].i = srcX1;
- n[4].i = srcY1;
- n[5].i = dstX0;
- n[6].i = dstY0;
- n[7].i = dstX1;
- n[8].i = dstY1;
- n[9].i = mask;
- n[10].e = filter;
- }
- if (ctx->ExecuteFlag) {
- CALL_BlitFramebufferEXT(ctx->Exec, (srcX0, srcY0, srcX1, srcY1,
- dstX0, dstY0, dstX1, dstY1,
- mask, filter));
- }
-}
-#endif
-
-
-/** GL_EXT_provoking_vertex */
-static void GLAPIENTRY
-save_ProvokingVertexEXT(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_PROVOKING_VERTEX, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_ProvokingVertexEXT(ctx->Exec, (mode));*/
- _mesa_ProvokingVertexEXT(mode);
- }
-}
-
-
-/** GL_EXT_transform_feedback */
-static void GLAPIENTRY
-save_BeginTransformFeedback(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_BEGIN_TRANSFORM_FEEDBACK, 1);
- if (n) {
- n[1].e = mode;
- }
- if (ctx->ExecuteFlag) {
- CALL_BeginTransformFeedbackEXT(ctx->Exec, (mode));
- }
-}
-
-
-/** GL_EXT_transform_feedback */
-static void GLAPIENTRY
-save_EndTransformFeedback(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- (void) alloc_instruction(ctx, OPCODE_END_TRANSFORM_FEEDBACK, 0);
- if (ctx->ExecuteFlag) {
- CALL_EndTransformFeedbackEXT(ctx->Exec, ());
- }
-}
-
-
-/* aka UseProgram() */
-static void GLAPIENTRY
-save_UseProgramObjectARB(GLhandleARB program)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_USE_PROGRAM, 1);
- if (n) {
- n[1].ui = program;
- }
- if (ctx->ExecuteFlag) {
- CALL_UseProgramObjectARB(ctx->Exec, (program));
- }
-}
-
-
-static void GLAPIENTRY
-save_Uniform1fARB(GLint location, GLfloat x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1F, 2);
- if (n) {
- n[1].i = location;
- n[2].f = x;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform1fARB(ctx->Exec, (location, x));
- }
-}
-
-
-static void GLAPIENTRY
-save_Uniform2fARB(GLint location, GLfloat x, GLfloat y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2F, 3);
- if (n) {
- n[1].i = location;
- n[2].f = x;
- n[3].f = y;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform2fARB(ctx->Exec, (location, x, y));
- }
-}
-
-
-static void GLAPIENTRY
-save_Uniform3fARB(GLint location, GLfloat x, GLfloat y, GLfloat z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3F, 4);
- if (n) {
- n[1].i = location;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform3fARB(ctx->Exec, (location, x, y, z));
- }
-}
-
-
-static void GLAPIENTRY
-save_Uniform4fARB(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4F, 5);
- if (n) {
- n[1].i = location;
- n[2].f = x;
- n[3].f = y;
- n[4].f = z;
- n[5].f = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform4fARB(ctx->Exec, (location, x, y, z, w));
- }
-}
-
-
-/** Return copy of memory */
-static void *
-memdup(const void *src, GLsizei bytes)
-{
- void *b = bytes >= 0 ? malloc(bytes) : NULL;
- if (b)
- memcpy(b, src, bytes);
- return b;
-}
-
-
-static void GLAPIENTRY
-save_Uniform1fvARB(GLint location, GLsizei count, const GLfloat *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1FV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 1 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform1fvARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform2fvARB(GLint location, GLsizei count, const GLfloat *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2FV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 2 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform2fvARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform3fvARB(GLint location, GLsizei count, const GLfloat *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3FV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 3 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform3fvARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform4fvARB(GLint location, GLsizei count, const GLfloat *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4FV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 4 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform4fvARB(ctx->Exec, (location, count, v));
- }
-}
-
-
-static void GLAPIENTRY
-save_Uniform1iARB(GLint location, GLint x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1I, 2);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform1iARB(ctx->Exec, (location, x));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform2iARB(GLint location, GLint x, GLint y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2I, 3);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform2iARB(ctx->Exec, (location, x, y));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform3iARB(GLint location, GLint x, GLint y, GLint z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3I, 4);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- n[4].i = z;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform3iARB(ctx->Exec, (location, x, y, z));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform4iARB(GLint location, GLint x, GLint y, GLint z, GLint w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4I, 5);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- n[4].i = z;
- n[5].i = w;
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform4iARB(ctx->Exec, (location, x, y, z, w));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_Uniform1ivARB(GLint location, GLsizei count, const GLint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1IV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 1 * sizeof(GLint));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform1ivARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform2ivARB(GLint location, GLsizei count, const GLint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2IV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 2 * sizeof(GLint));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform2ivARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform3ivARB(GLint location, GLsizei count, const GLint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3IV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 3 * sizeof(GLint));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform3ivARB(ctx->Exec, (location, count, v));
- }
-}
-
-static void GLAPIENTRY
-save_Uniform4ivARB(GLint location, GLsizei count, const GLint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4IV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 4 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_Uniform4ivARB(ctx->Exec, (location, count, v));
- }
-}
-
-
-
-static void GLAPIENTRY
-save_Uniform1ui(GLint location, GLuint x)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1UI, 2);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform1ui(ctx->Exec, (location, x));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform2ui(GLint location, GLuint x, GLuint y)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2UI, 3);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform2ui(ctx->Exec, (location, x, y));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform3ui(GLint location, GLuint x, GLuint y, GLuint z)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3UI, 4);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- n[4].i = z;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform3ui(ctx->Exec, (location, x, y, z));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform4ui(GLint location, GLuint x, GLuint y, GLuint z, GLuint w)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4UI, 5);
- if (n) {
- n[1].i = location;
- n[2].i = x;
- n[3].i = y;
- n[4].i = z;
- n[5].i = w;
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform4ui(ctx->Exec, (location, x, y, z, w));*/
- }
-}
-
-
-
-static void GLAPIENTRY
-save_Uniform1uiv(GLint location, GLsizei count, const GLuint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_1UIV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 1 * sizeof(*v));
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform1uiv(ctx->Exec, (location, count, v));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform2uiv(GLint location, GLsizei count, const GLuint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_2UIV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 2 * sizeof(*v));
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform2uiv(ctx->Exec, (location, count, v));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform3uiv(GLint location, GLsizei count, const GLuint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_3UIV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 3 * sizeof(*v));
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform3uiv(ctx->Exec, (location, count, v));*/
- }
-}
-
-static void GLAPIENTRY
-save_Uniform4uiv(GLint location, GLsizei count, const GLuint *v)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_4UIV, 3);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].data = memdup(v, count * 4 * sizeof(*v));
- }
- if (ctx->ExecuteFlag) {
- /*CALL_Uniform4uiv(ctx->Exec, (location, count, v));*/
- }
-}
-
-
-
-static void GLAPIENTRY
-save_UniformMatrix2fvARB(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX22, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 2 * 2 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix2fvARB(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UniformMatrix3fvARB(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX33, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 3 * 3 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix3fvARB(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UniformMatrix4fvARB(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX44, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 4 * 4 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix4fvARB(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-
-static void GLAPIENTRY
-save_UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX23, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 2 * 3 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix2x3fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX32, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 3 * 2 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix3x2fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-
-static void GLAPIENTRY
-save_UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX24, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 2 * 4 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix2x4fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX42, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 4 * 2 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix4x2fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-
-static void GLAPIENTRY
-save_UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX34, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 3 * 4 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix3x4fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose,
- const GLfloat *m)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX43, 4);
- if (n) {
- n[1].i = location;
- n[2].i = count;
- n[3].b = transpose;
- n[4].data = memdup(m, count * 4 * 3 * sizeof(GLfloat));
- }
- if (ctx->ExecuteFlag) {
- CALL_UniformMatrix4x3fv(ctx->Exec, (location, count, transpose, m));
- }
-}
-
-static void GLAPIENTRY
-save_UseShaderProgramEXT(GLenum type, GLuint program)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_USE_SHADER_PROGRAM_EXT, 2);
- if (n) {
- n[1].ui = type;
- n[2].ui = program;
- }
- if (ctx->ExecuteFlag) {
- CALL_UseShaderProgramEXT(ctx->Exec, (type, program));
- }
-}
-
-static void GLAPIENTRY
-save_ActiveProgramEXT(GLuint program)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_ACTIVE_PROGRAM_EXT, 1);
- if (n) {
- n[1].ui = program;
- }
- if (ctx->ExecuteFlag) {
- CALL_ActiveProgramEXT(ctx->Exec, (program));
- }
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-save_ClearColorIi(GLint red, GLint green, GLint blue, GLint alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEARCOLOR_I, 4);
- if (n) {
- n[1].i = red;
- n[2].i = green;
- n[3].i = blue;
- n[4].i = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearColorIiEXT(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-save_ClearColorIui(GLuint red, GLuint green, GLuint blue, GLuint alpha)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_CLEARCOLOR_UI, 4);
- if (n) {
- n[1].ui = red;
- n[2].ui = green;
- n[3].ui = blue;
- n[4].ui = alpha;
- }
- if (ctx->ExecuteFlag) {
- CALL_ClearColorIuiEXT(ctx->Exec, (red, green, blue, alpha));
- }
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-save_TexParameterIiv(GLenum target, GLenum pname, const GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEXPARAMETER_I, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].i = params[0];
- n[4].i = params[1];
- n[5].i = params[2];
- n[6].i = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_TexParameterIivEXT(ctx->Exec, (target, pname, params));
- }
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-save_TexParameterIuiv(GLenum target, GLenum pname, const GLuint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_TEXPARAMETER_UI, 6);
- if (n) {
- n[1].e = target;
- n[2].e = pname;
- n[3].ui = params[0];
- n[4].ui = params[1];
- n[5].ui = params[2];
- n[6].ui = params[3];
- }
- if (ctx->ExecuteFlag) {
- CALL_TexParameterIuivEXT(ctx->Exec, (target, pname, params));
- }
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-exec_GetTexParameterIiv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexParameterIivEXT(ctx->Exec, (target, pname, params));
-}
-
-/** GL_EXT_texture_integer */
-static void GLAPIENTRY
-exec_GetTexParameterIuiv(GLenum target, GLenum pname, GLuint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexParameterIuivEXT(ctx->Exec, (target, pname, params));
-}
-
-
-/* GL_ARB_instanced_arrays */
-static void
-save_VertexAttribDivisor(GLuint index, GLuint divisor)
-{
- GET_CURRENT_CONTEXT(ctx);
- Node *n;
- ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
- n = alloc_instruction(ctx, OPCODE_VERTEX_ATTRIB_DIVISOR, 2);
- if (n) {
- n[1].ui = index;
- n[2].ui = divisor;
- }
- if (ctx->ExecuteFlag) {
- CALL_VertexAttribDivisorARB(ctx->Exec, (index, divisor));
- }
-}
-
-
-
-/**
- * Save an error-generating command into display list.
- *
- * KW: Will appear in the list before the vertex buffer containing the
- * command that provoked the error. I don't see this as a problem.
- */
-static void
-save_error(struct gl_context *ctx, GLenum error, const char *s)
-{
- Node *n;
- n = alloc_instruction(ctx, OPCODE_ERROR, 2);
- if (n) {
- n[1].e = error;
- n[2].data = (void *) s;
- }
-}
-
-
-/**
- * Compile an error into current display list.
- */
-void
-_mesa_compile_error(struct gl_context *ctx, GLenum error, const char *s)
-{
- if (ctx->CompileFlag)
- save_error(ctx, error, s);
- if (ctx->ExecuteFlag)
- _mesa_error(ctx, error, "%s", s);
-}
-
-
-/**
- * Test if ID names a display list.
- */
-static GLboolean
-islist(struct gl_context *ctx, GLuint list)
-{
- if (list > 0 && lookup_list(ctx, list)) {
- return GL_TRUE;
- }
- else {
- return GL_FALSE;
- }
-}
-
-
-
-/**********************************************************************/
-/* Display list execution */
-/**********************************************************************/
-
-
-/*
- * Execute a display list. Note that the ListBase offset must have already
- * been added before calling this function. I.e. the list argument is
- * the absolute list number, not relative to ListBase.
- * \param list - display list number
- */
-static void
-execute_list(struct gl_context *ctx, GLuint list)
-{
- struct gl_display_list *dlist;
- Node *n;
- GLboolean done;
-
- if (list == 0 || !islist(ctx, list))
- return;
-
- if (ctx->ListState.CallDepth == MAX_LIST_NESTING) {
- /* raise an error? */
- return;
- }
-
- dlist = lookup_list(ctx, list);
- if (!dlist)
- return;
-
- ctx->ListState.CallDepth++;
-
- if (ctx->Driver.BeginCallList)
- ctx->Driver.BeginCallList(ctx, dlist);
-
- n = dlist->Head;
-
- done = GL_FALSE;
- while (!done) {
- const OpCode opcode = n[0].opcode;
-
- if (is_ext_opcode(opcode)) {
- n += ext_opcode_execute(ctx, n);
- }
- else {
- switch (opcode) {
- case OPCODE_ERROR:
- _mesa_error(ctx, n[1].e, "%s", (const char *) n[2].data);
- break;
- case OPCODE_ACCUM:
- CALL_Accum(ctx->Exec, (n[1].e, n[2].f));
- break;
- case OPCODE_ALPHA_FUNC:
- CALL_AlphaFunc(ctx->Exec, (n[1].e, n[2].f));
- break;
- case OPCODE_BIND_TEXTURE:
- CALL_BindTexture(ctx->Exec, (n[1].e, n[2].ui));
- break;
- case OPCODE_BITMAP:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_Bitmap(ctx->Exec, ((GLsizei) n[1].i, (GLsizei) n[2].i,
- n[3].f, n[4].f, n[5].f, n[6].f,
- (const GLubyte *) n[7].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_BLEND_COLOR:
- CALL_BlendColor(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_BLEND_EQUATION:
- CALL_BlendEquation(ctx->Exec, (n[1].e));
- break;
- case OPCODE_BLEND_EQUATION_SEPARATE:
- CALL_BlendEquationSeparateEXT(ctx->Exec, (n[1].e, n[2].e));
- break;
- case OPCODE_BLEND_FUNC_SEPARATE:
- CALL_BlendFuncSeparateEXT(ctx->Exec,
- (n[1].e, n[2].e, n[3].e, n[4].e));
- break;
-
- case OPCODE_BLEND_FUNC_I:
- /* GL_ARB_draw_buffers_blend */
- CALL_BlendFunciARB(ctx->Exec, (n[1].ui, n[2].e, n[3].e));
- break;
- case OPCODE_BLEND_FUNC_SEPARATE_I:
- /* GL_ARB_draw_buffers_blend */
- CALL_BlendFuncSeparateiARB(ctx->Exec, (n[1].ui, n[2].e, n[3].e,
- n[4].e, n[5].e));
- break;
- case OPCODE_BLEND_EQUATION_I:
- /* GL_ARB_draw_buffers_blend */
- CALL_BlendEquationiARB(ctx->Exec, (n[1].ui, n[2].e));
- break;
- case OPCODE_BLEND_EQUATION_SEPARATE_I:
- /* GL_ARB_draw_buffers_blend */
- CALL_BlendEquationSeparateiARB(ctx->Exec,
- (n[1].ui, n[2].e, n[3].e));
- break;
-
- case OPCODE_CALL_LIST:
- /* Generated by glCallList(), don't add ListBase */
- if (ctx->ListState.CallDepth < MAX_LIST_NESTING) {
- execute_list(ctx, n[1].ui);
- }
- break;
- case OPCODE_CALL_LIST_OFFSET:
- /* Generated by glCallLists() so we must add ListBase */
- if (n[2].b) {
- /* user specified a bad data type at compile time */
- _mesa_error(ctx, GL_INVALID_ENUM, "glCallLists(type)");
- }
- else if (ctx->ListState.CallDepth < MAX_LIST_NESTING) {
- GLuint list = (GLuint) (ctx->List.ListBase + n[1].i);
- execute_list(ctx, list);
- }
- break;
- case OPCODE_CLEAR:
- CALL_Clear(ctx->Exec, (n[1].bf));
- break;
- case OPCODE_CLEAR_BUFFER_IV:
- {
- GLint value[4];
- value[0] = n[3].i;
- value[1] = n[4].i;
- value[2] = n[5].i;
- value[3] = n[6].i;
- /*CALL_ClearBufferiv(ctx->Exec, (n[1].e, n[2].i, value));*/
- }
- break;
- case OPCODE_CLEAR_BUFFER_UIV:
- {
- GLuint value[4];
- value[0] = n[3].ui;
- value[1] = n[4].ui;
- value[2] = n[5].ui;
- value[3] = n[6].ui;
- /*CALL_ClearBufferiv(ctx->Exec, (n[1].e, n[2].i, value));*/
- }
- break;
- case OPCODE_CLEAR_BUFFER_FV:
- {
- GLfloat value[4];
- value[0] = n[3].f;
- value[1] = n[4].f;
- value[2] = n[5].f;
- value[3] = n[6].f;
- /*CALL_ClearBufferfv(ctx->Exec, (n[1].e, n[2].i, value));*/
- }
- break;
- case OPCODE_CLEAR_BUFFER_FI:
- /*CALL_ClearBufferfi(ctx->Exec, (n[1].e, n[2].i, n[3].f, n[4].i));*/
- break;
- case OPCODE_CLEAR_COLOR:
- CALL_ClearColor(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_CLEAR_ACCUM:
- CALL_ClearAccum(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_CLEAR_DEPTH:
- CALL_ClearDepth(ctx->Exec, ((GLclampd) n[1].f));
- break;
- case OPCODE_CLEAR_INDEX:
- CALL_ClearIndex(ctx->Exec, ((GLfloat) n[1].ui));
- break;
- case OPCODE_CLEAR_STENCIL:
- CALL_ClearStencil(ctx->Exec, (n[1].i));
- break;
- case OPCODE_CLIP_PLANE:
- {
- GLdouble eq[4];
- eq[0] = n[2].f;
- eq[1] = n[3].f;
- eq[2] = n[4].f;
- eq[3] = n[5].f;
- CALL_ClipPlane(ctx->Exec, (n[1].e, eq));
- }
- break;
- case OPCODE_COLOR_MASK:
- CALL_ColorMask(ctx->Exec, (n[1].b, n[2].b, n[3].b, n[4].b));
- break;
- case OPCODE_COLOR_MASK_INDEXED:
- CALL_ColorMaskIndexedEXT(ctx->Exec, (n[1].ui, n[2].b, n[3].b,
- n[4].b, n[5].b));
- break;
- case OPCODE_COLOR_MATERIAL:
- CALL_ColorMaterial(ctx->Exec, (n[1].e, n[2].e));
- break;
- case OPCODE_COLOR_TABLE:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_ColorTable(ctx->Exec, (n[1].e, n[2].e, n[3].i, n[4].e,
- n[5].e, n[6].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_COLOR_TABLE_PARAMETER_FV:
- {
- GLfloat params[4];
- params[0] = n[3].f;
- params[1] = n[4].f;
- params[2] = n[5].f;
- params[3] = n[6].f;
- CALL_ColorTableParameterfv(ctx->Exec,
- (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_COLOR_TABLE_PARAMETER_IV:
- {
- GLint params[4];
- params[0] = n[3].i;
- params[1] = n[4].i;
- params[2] = n[5].i;
- params[3] = n[6].i;
- CALL_ColorTableParameteriv(ctx->Exec,
- (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_COLOR_SUB_TABLE:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_ColorSubTable(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].e, n[5].e, n[6].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_CONVOLUTION_FILTER_1D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_ConvolutionFilter1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].e, n[5].e,
- n[6].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_CONVOLUTION_FILTER_2D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_ConvolutionFilter2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].e, n[6].e,
- n[7].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_CONVOLUTION_PARAMETER_I:
- CALL_ConvolutionParameteri(ctx->Exec, (n[1].e, n[2].e, n[3].i));
- break;
- case OPCODE_CONVOLUTION_PARAMETER_IV:
- {
- GLint params[4];
- params[0] = n[3].i;
- params[1] = n[4].i;
- params[2] = n[5].i;
- params[3] = n[6].i;
- CALL_ConvolutionParameteriv(ctx->Exec,
- (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_CONVOLUTION_PARAMETER_F:
- CALL_ConvolutionParameterf(ctx->Exec, (n[1].e, n[2].e, n[3].f));
- break;
- case OPCODE_CONVOLUTION_PARAMETER_FV:
- {
- GLfloat params[4];
- params[0] = n[3].f;
- params[1] = n[4].f;
- params[2] = n[5].f;
- params[3] = n[6].f;
- CALL_ConvolutionParameterfv(ctx->Exec,
- (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_COPY_COLOR_SUB_TABLE:
- CALL_CopyColorSubTable(ctx->Exec, (n[1].e, n[2].i,
- n[3].i, n[4].i, n[5].i));
- break;
- case OPCODE_COPY_COLOR_TABLE:
- CALL_CopyColorSubTable(ctx->Exec, (n[1].e, n[2].i,
- n[3].i, n[4].i, n[5].i));
- break;
- case OPCODE_COPY_PIXELS:
- CALL_CopyPixels(ctx->Exec, (n[1].i, n[2].i,
- (GLsizei) n[3].i, (GLsizei) n[4].i,
- n[5].e));
- break;
- case OPCODE_COPY_TEX_IMAGE1D:
- CALL_CopyTexImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].i,
- n[5].i, n[6].i, n[7].i));
- break;
- case OPCODE_COPY_TEX_IMAGE2D:
- CALL_CopyTexImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].i,
- n[5].i, n[6].i, n[7].i, n[8].i));
- break;
- case OPCODE_COPY_TEX_SUB_IMAGE1D:
- CALL_CopyTexSubImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].i, n[6].i));
- break;
- case OPCODE_COPY_TEX_SUB_IMAGE2D:
- CALL_CopyTexSubImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].i, n[6].i, n[7].i,
- n[8].i));
- break;
- case OPCODE_COPY_TEX_SUB_IMAGE3D:
- CALL_CopyTexSubImage3D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].i, n[6].i, n[7].i,
- n[8].i, n[9].i));
- break;
- case OPCODE_CULL_FACE:
- CALL_CullFace(ctx->Exec, (n[1].e));
- break;
- case OPCODE_DEPTH_FUNC:
- CALL_DepthFunc(ctx->Exec, (n[1].e));
- break;
- case OPCODE_DEPTH_MASK:
- CALL_DepthMask(ctx->Exec, (n[1].b));
- break;
- case OPCODE_DEPTH_RANGE:
- CALL_DepthRange(ctx->Exec,
- ((GLclampd) n[1].f, (GLclampd) n[2].f));
- break;
- case OPCODE_DISABLE:
- CALL_Disable(ctx->Exec, (n[1].e));
- break;
- case OPCODE_DISABLE_INDEXED:
- CALL_DisableIndexedEXT(ctx->Exec, (n[1].ui, n[2].e));
- break;
- case OPCODE_DRAW_BUFFER:
- CALL_DrawBuffer(ctx->Exec, (n[1].e));
- break;
- case OPCODE_DRAW_PIXELS:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_DrawPixels(ctx->Exec, (n[1].i, n[2].i, n[3].e, n[4].e,
- n[5].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_ENABLE:
- CALL_Enable(ctx->Exec, (n[1].e));
- break;
- case OPCODE_ENABLE_INDEXED:
- CALL_EnableIndexedEXT(ctx->Exec, (n[1].ui, n[2].e));
- break;
- case OPCODE_EVALMESH1:
- CALL_EvalMesh1(ctx->Exec, (n[1].e, n[2].i, n[3].i));
- break;
- case OPCODE_EVALMESH2:
- CALL_EvalMesh2(ctx->Exec,
- (n[1].e, n[2].i, n[3].i, n[4].i, n[5].i));
- break;
- case OPCODE_FOG:
- {
- GLfloat p[4];
- p[0] = n[2].f;
- p[1] = n[3].f;
- p[2] = n[4].f;
- p[3] = n[5].f;
- CALL_Fogfv(ctx->Exec, (n[1].e, p));
- }
- break;
- case OPCODE_FRONT_FACE:
- CALL_FrontFace(ctx->Exec, (n[1].e));
- break;
- case OPCODE_FRUSTUM:
- CALL_Frustum(ctx->Exec,
- (n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f));
- break;
- case OPCODE_HINT:
- CALL_Hint(ctx->Exec, (n[1].e, n[2].e));
- break;
- case OPCODE_HISTOGRAM:
- CALL_Histogram(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].b));
- break;
- case OPCODE_INDEX_MASK:
- CALL_IndexMask(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_INIT_NAMES:
- CALL_InitNames(ctx->Exec, ());
- break;
- case OPCODE_LIGHT:
- {
- GLfloat p[4];
- p[0] = n[3].f;
- p[1] = n[4].f;
- p[2] = n[5].f;
- p[3] = n[6].f;
- CALL_Lightfv(ctx->Exec, (n[1].e, n[2].e, p));
- }
- break;
- case OPCODE_LIGHT_MODEL:
- {
- GLfloat p[4];
- p[0] = n[2].f;
- p[1] = n[3].f;
- p[2] = n[4].f;
- p[3] = n[5].f;
- CALL_LightModelfv(ctx->Exec, (n[1].e, p));
- }
- break;
- case OPCODE_LINE_STIPPLE:
- CALL_LineStipple(ctx->Exec, (n[1].i, n[2].us));
- break;
- case OPCODE_LINE_WIDTH:
- CALL_LineWidth(ctx->Exec, (n[1].f));
- break;
- case OPCODE_LIST_BASE:
- CALL_ListBase(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_LOAD_IDENTITY:
- CALL_LoadIdentity(ctx->Exec, ());
- break;
- case OPCODE_LOAD_MATRIX:
- if (sizeof(Node) == sizeof(GLfloat)) {
- CALL_LoadMatrixf(ctx->Exec, (&n[1].f));
- }
- else {
- GLfloat m[16];
- GLuint i;
- for (i = 0; i < 16; i++) {
- m[i] = n[1 + i].f;
- }
- CALL_LoadMatrixf(ctx->Exec, (m));
- }
- break;
- case OPCODE_LOAD_NAME:
- CALL_LoadName(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_LOGIC_OP:
- CALL_LogicOp(ctx->Exec, (n[1].e));
- break;
- case OPCODE_MAP1:
- {
- GLenum target = n[1].e;
- GLint ustride = _mesa_evaluator_components(target);
- GLint uorder = n[5].i;
- GLfloat u1 = n[2].f;
- GLfloat u2 = n[3].f;
- CALL_Map1f(ctx->Exec, (target, u1, u2, ustride, uorder,
- (GLfloat *) n[6].data));
- }
- break;
- case OPCODE_MAP2:
- {
- GLenum target = n[1].e;
- GLfloat u1 = n[2].f;
- GLfloat u2 = n[3].f;
- GLfloat v1 = n[4].f;
- GLfloat v2 = n[5].f;
- GLint ustride = n[6].i;
- GLint vstride = n[7].i;
- GLint uorder = n[8].i;
- GLint vorder = n[9].i;
- CALL_Map2f(ctx->Exec, (target, u1, u2, ustride, uorder,
- v1, v2, vstride, vorder,
- (GLfloat *) n[10].data));
- }
- break;
- case OPCODE_MAPGRID1:
- CALL_MapGrid1f(ctx->Exec, (n[1].i, n[2].f, n[3].f));
- break;
- case OPCODE_MAPGRID2:
- CALL_MapGrid2f(ctx->Exec,
- (n[1].i, n[2].f, n[3].f, n[4].i, n[5].f, n[6].f));
- break;
- case OPCODE_MATRIX_MODE:
- CALL_MatrixMode(ctx->Exec, (n[1].e));
- break;
- case OPCODE_MIN_MAX:
- CALL_Minmax(ctx->Exec, (n[1].e, n[2].e, n[3].b));
- break;
- case OPCODE_MULT_MATRIX:
- if (sizeof(Node) == sizeof(GLfloat)) {
- CALL_MultMatrixf(ctx->Exec, (&n[1].f));
- }
- else {
- GLfloat m[16];
- GLuint i;
- for (i = 0; i < 16; i++) {
- m[i] = n[1 + i].f;
- }
- CALL_MultMatrixf(ctx->Exec, (m));
- }
- break;
- case OPCODE_ORTHO:
- CALL_Ortho(ctx->Exec,
- (n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f));
- break;
- case OPCODE_PASSTHROUGH:
- CALL_PassThrough(ctx->Exec, (n[1].f));
- break;
- case OPCODE_PIXEL_MAP:
- CALL_PixelMapfv(ctx->Exec,
- (n[1].e, n[2].i, (GLfloat *) n[3].data));
- break;
- case OPCODE_PIXEL_TRANSFER:
- CALL_PixelTransferf(ctx->Exec, (n[1].e, n[2].f));
- break;
- case OPCODE_PIXEL_ZOOM:
- CALL_PixelZoom(ctx->Exec, (n[1].f, n[2].f));
- break;
- case OPCODE_POINT_SIZE:
- CALL_PointSize(ctx->Exec, (n[1].f));
- break;
- case OPCODE_POINT_PARAMETERS:
- {
- GLfloat params[3];
- params[0] = n[2].f;
- params[1] = n[3].f;
- params[2] = n[4].f;
- CALL_PointParameterfvEXT(ctx->Exec, (n[1].e, params));
- }
- break;
- case OPCODE_POLYGON_MODE:
- CALL_PolygonMode(ctx->Exec, (n[1].e, n[2].e));
- break;
- case OPCODE_POLYGON_STIPPLE:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_PolygonStipple(ctx->Exec, ((GLubyte *) n[1].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_POLYGON_OFFSET:
- CALL_PolygonOffset(ctx->Exec, (n[1].f, n[2].f));
- break;
- case OPCODE_POP_ATTRIB:
- CALL_PopAttrib(ctx->Exec, ());
- break;
- case OPCODE_POP_MATRIX:
- CALL_PopMatrix(ctx->Exec, ());
- break;
- case OPCODE_POP_NAME:
- CALL_PopName(ctx->Exec, ());
- break;
- case OPCODE_PRIORITIZE_TEXTURE:
- CALL_PrioritizeTextures(ctx->Exec, (1, &n[1].ui, &n[2].f));
- break;
- case OPCODE_PUSH_ATTRIB:
- CALL_PushAttrib(ctx->Exec, (n[1].bf));
- break;
- case OPCODE_PUSH_MATRIX:
- CALL_PushMatrix(ctx->Exec, ());
- break;
- case OPCODE_PUSH_NAME:
- CALL_PushName(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_RASTER_POS:
- CALL_RasterPos4f(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_READ_BUFFER:
- CALL_ReadBuffer(ctx->Exec, (n[1].e));
- break;
- case OPCODE_RESET_HISTOGRAM:
- CALL_ResetHistogram(ctx->Exec, (n[1].e));
- break;
- case OPCODE_RESET_MIN_MAX:
- CALL_ResetMinmax(ctx->Exec, (n[1].e));
- break;
- case OPCODE_ROTATE:
- CALL_Rotatef(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_SCALE:
- CALL_Scalef(ctx->Exec, (n[1].f, n[2].f, n[3].f));
- break;
- case OPCODE_SCISSOR:
- CALL_Scissor(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
- break;
- case OPCODE_SHADE_MODEL:
- CALL_ShadeModel(ctx->Exec, (n[1].e));
- break;
- case OPCODE_PROVOKING_VERTEX:
- CALL_ProvokingVertexEXT(ctx->Exec, (n[1].e));
- break;
- case OPCODE_BEGIN_TRANSFORM_FEEDBACK:
- CALL_BeginTransformFeedbackEXT(ctx->Exec, (n[1].e));
- break;
- case OPCODE_END_TRANSFORM_FEEDBACK:
- CALL_EndTransformFeedbackEXT(ctx->Exec, ());
- break;
- case OPCODE_STENCIL_FUNC:
- CALL_StencilFunc(ctx->Exec, (n[1].e, n[2].i, n[3].ui));
- break;
- case OPCODE_STENCIL_MASK:
- CALL_StencilMask(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_STENCIL_OP:
- CALL_StencilOp(ctx->Exec, (n[1].e, n[2].e, n[3].e));
- break;
- case OPCODE_STENCIL_FUNC_SEPARATE:
- CALL_StencilFuncSeparate(ctx->Exec,
- (n[1].e, n[2].e, n[3].i, n[4].ui));
- break;
- case OPCODE_STENCIL_MASK_SEPARATE:
- CALL_StencilMaskSeparate(ctx->Exec, (n[1].e, n[2].ui));
- break;
- case OPCODE_STENCIL_OP_SEPARATE:
- CALL_StencilOpSeparate(ctx->Exec,
- (n[1].e, n[2].e, n[3].e, n[4].e));
- break;
- case OPCODE_TEXENV:
- {
- GLfloat params[4];
- params[0] = n[3].f;
- params[1] = n[4].f;
- params[2] = n[5].f;
- params[3] = n[6].f;
- CALL_TexEnvfv(ctx->Exec, (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_TEXGEN:
- {
- GLfloat params[4];
- params[0] = n[3].f;
- params[1] = n[4].f;
- params[2] = n[5].f;
- params[3] = n[6].f;
- CALL_TexGenfv(ctx->Exec, (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_TEXPARAMETER:
- {
- GLfloat params[4];
- params[0] = n[3].f;
- params[1] = n[4].f;
- params[2] = n[5].f;
- params[3] = n[6].f;
- CALL_TexParameterfv(ctx->Exec, (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_TEX_IMAGE1D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexImage1D(ctx->Exec, (n[1].e, /* target */
- n[2].i, /* level */
- n[3].i, /* components */
- n[4].i, /* width */
- n[5].e, /* border */
- n[6].e, /* format */
- n[7].e, /* type */
- n[8].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TEX_IMAGE2D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexImage2D(ctx->Exec, (n[1].e, /* target */
- n[2].i, /* level */
- n[3].i, /* components */
- n[4].i, /* width */
- n[5].i, /* height */
- n[6].e, /* border */
- n[7].e, /* format */
- n[8].e, /* type */
- n[9].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TEX_IMAGE3D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexImage3D(ctx->Exec, (n[1].e, /* target */
- n[2].i, /* level */
- n[3].i, /* components */
- n[4].i, /* width */
- n[5].i, /* height */
- n[6].i, /* depth */
- n[7].e, /* border */
- n[8].e, /* format */
- n[9].e, /* type */
- n[10].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TEX_SUB_IMAGE1D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexSubImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].e,
- n[6].e, n[7].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TEX_SUB_IMAGE2D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexSubImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].e,
- n[6].i, n[7].e, n[8].e,
- n[9].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TEX_SUB_IMAGE3D:
- {
- const struct gl_pixelstore_attrib save = ctx->Unpack;
- ctx->Unpack = ctx->DefaultPacking;
- CALL_TexSubImage3D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
- n[4].i, n[5].i, n[6].i, n[7].i,
- n[8].i, n[9].e, n[10].e,
- n[11].data));
- ctx->Unpack = save; /* restore */
- }
- break;
- case OPCODE_TRANSLATE:
- CALL_Translatef(ctx->Exec, (n[1].f, n[2].f, n[3].f));
- break;
- case OPCODE_VIEWPORT:
- CALL_Viewport(ctx->Exec, (n[1].i, n[2].i,
- (GLsizei) n[3].i, (GLsizei) n[4].i));
- break;
- case OPCODE_WINDOW_POS:
- CALL_WindowPos4fMESA(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_ACTIVE_TEXTURE: /* GL_ARB_multitexture */
- CALL_ActiveTextureARB(ctx->Exec, (n[1].e));
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_1D: /* GL_ARB_texture_compression */
- CALL_CompressedTexImage1DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
- n[4].i, n[5].i, n[6].i,
- n[7].data));
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_2D: /* GL_ARB_texture_compression */
- CALL_CompressedTexImage2DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
- n[4].i, n[5].i, n[6].i,
- n[7].i, n[8].data));
- break;
- case OPCODE_COMPRESSED_TEX_IMAGE_3D: /* GL_ARB_texture_compression */
- CALL_CompressedTexImage3DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
- n[4].i, n[5].i, n[6].i,
- n[7].i, n[8].i,
- n[9].data));
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D: /* GL_ARB_texture_compress */
- CALL_CompressedTexSubImage1DARB(ctx->Exec,
- (n[1].e, n[2].i, n[3].i, n[4].i,
- n[5].e, n[6].i, n[7].data));
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D: /* GL_ARB_texture_compress */
- CALL_CompressedTexSubImage2DARB(ctx->Exec,
- (n[1].e, n[2].i, n[3].i, n[4].i,
- n[5].i, n[6].i, n[7].e, n[8].i,
- n[9].data));
- break;
- case OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D: /* GL_ARB_texture_compress */
- CALL_CompressedTexSubImage3DARB(ctx->Exec,
- (n[1].e, n[2].i, n[3].i, n[4].i,
- n[5].i, n[6].i, n[7].i, n[8].i,
- n[9].e, n[10].i, n[11].data));
- break;
- case OPCODE_SAMPLE_COVERAGE: /* GL_ARB_multisample */
- CALL_SampleCoverageARB(ctx->Exec, (n[1].f, n[2].b));
- break;
- case OPCODE_WINDOW_POS_ARB: /* GL_ARB_window_pos */
- CALL_WindowPos3fMESA(ctx->Exec, (n[1].f, n[2].f, n[3].f));
- break;
-#if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
- case OPCODE_BIND_PROGRAM_NV: /* GL_NV_vertex_program */
- CALL_BindProgramNV(ctx->Exec, (n[1].e, n[2].ui));
- break;
-#endif
-#if FEATURE_NV_vertex_program
- case OPCODE_EXECUTE_PROGRAM_NV:
- {
- GLfloat v[4];
- v[0] = n[3].f;
- v[1] = n[4].f;
- v[2] = n[5].f;
- v[3] = n[6].f;
- CALL_ExecuteProgramNV(ctx->Exec, (n[1].e, n[2].ui, v));
- }
- break;
- case OPCODE_REQUEST_RESIDENT_PROGRAMS_NV:
- CALL_RequestResidentProgramsNV(ctx->Exec, (n[1].ui,
- (GLuint *) n[2].data));
- break;
- case OPCODE_LOAD_PROGRAM_NV:
- CALL_LoadProgramNV(ctx->Exec, (n[1].e, n[2].ui, n[3].i,
- (const GLubyte *) n[4].data));
- break;
- case OPCODE_TRACK_MATRIX_NV:
- CALL_TrackMatrixNV(ctx->Exec, (n[1].e, n[2].ui, n[3].e, n[4].e));
- break;
-#endif
-
-#if FEATURE_NV_fragment_program
- case OPCODE_PROGRAM_LOCAL_PARAMETER_ARB:
- CALL_ProgramLocalParameter4fARB(ctx->Exec,
- (n[1].e, n[2].ui, n[3].f, n[4].f,
- n[5].f, n[6].f));
- break;
- case OPCODE_PROGRAM_NAMED_PARAMETER_NV:
- CALL_ProgramNamedParameter4fNV(ctx->Exec, (n[1].ui, n[2].i,
- (const GLubyte *) n[3].
- data, n[4].f, n[5].f,
- n[6].f, n[7].f));
- break;
-#endif
-
- case OPCODE_ACTIVE_STENCIL_FACE_EXT:
- CALL_ActiveStencilFaceEXT(ctx->Exec, (n[1].e));
- break;
- case OPCODE_DEPTH_BOUNDS_EXT:
- CALL_DepthBoundsEXT(ctx->Exec, (n[1].f, n[2].f));
- break;
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
- case OPCODE_PROGRAM_STRING_ARB:
- CALL_ProgramStringARB(ctx->Exec,
- (n[1].e, n[2].e, n[3].i, n[4].data));
- break;
-#endif
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program || FEATURE_NV_vertex_program
- case OPCODE_PROGRAM_ENV_PARAMETER_ARB:
- CALL_ProgramEnvParameter4fARB(ctx->Exec, (n[1].e, n[2].ui, n[3].f,
- n[4].f, n[5].f,
- n[6].f));
- break;
-#endif
-#if FEATURE_queryobj
- case OPCODE_BEGIN_QUERY_ARB:
- CALL_BeginQueryARB(ctx->Exec, (n[1].e, n[2].ui));
- break;
- case OPCODE_END_QUERY_ARB:
- CALL_EndQueryARB(ctx->Exec, (n[1].e));
- break;
-#endif
- case OPCODE_DRAW_BUFFERS_ARB:
- {
- GLenum buffers[MAX_DRAW_BUFFERS];
- GLint i, count = MIN2(n[1].i, MAX_DRAW_BUFFERS);
- for (i = 0; i < count; i++)
- buffers[i] = n[2 + i].e;
- CALL_DrawBuffersARB(ctx->Exec, (n[1].i, buffers));
- }
- break;
-#if FEATURE_EXT_framebuffer_blit
- case OPCODE_BLIT_FRAMEBUFFER:
- CALL_BlitFramebufferEXT(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i,
- n[5].i, n[6].i, n[7].i, n[8].i,
- n[9].i, n[10].e));
- break;
-#endif
-
- case OPCODE_USE_PROGRAM:
- CALL_UseProgramObjectARB(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_USE_SHADER_PROGRAM_EXT:
- CALL_UseShaderProgramEXT(ctx->Exec, (n[1].ui, n[2].ui));
- break;
- case OPCODE_ACTIVE_PROGRAM_EXT:
- CALL_ActiveProgramEXT(ctx->Exec, (n[1].ui));
- break;
- case OPCODE_UNIFORM_1F:
- CALL_Uniform1fARB(ctx->Exec, (n[1].i, n[2].f));
- break;
- case OPCODE_UNIFORM_2F:
- CALL_Uniform2fARB(ctx->Exec, (n[1].i, n[2].f, n[3].f));
- break;
- case OPCODE_UNIFORM_3F:
- CALL_Uniform3fARB(ctx->Exec, (n[1].i, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_UNIFORM_4F:
- CALL_Uniform4fARB(ctx->Exec,
- (n[1].i, n[2].f, n[3].f, n[4].f, n[5].f));
- break;
- case OPCODE_UNIFORM_1FV:
- CALL_Uniform1fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_2FV:
- CALL_Uniform2fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_3FV:
- CALL_Uniform3fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_4FV:
- CALL_Uniform4fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_1I:
- CALL_Uniform1iARB(ctx->Exec, (n[1].i, n[2].i));
- break;
- case OPCODE_UNIFORM_2I:
- CALL_Uniform2iARB(ctx->Exec, (n[1].i, n[2].i, n[3].i));
- break;
- case OPCODE_UNIFORM_3I:
- CALL_Uniform3iARB(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
- break;
- case OPCODE_UNIFORM_4I:
- CALL_Uniform4iARB(ctx->Exec,
- (n[1].i, n[2].i, n[3].i, n[4].i, n[5].i));
- break;
- case OPCODE_UNIFORM_1IV:
- CALL_Uniform1ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_2IV:
- CALL_Uniform2ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_3IV:
- CALL_Uniform3ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_4IV:
- CALL_Uniform4ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
- break;
- case OPCODE_UNIFORM_1UI:
- /*CALL_Uniform1uiARB(ctx->Exec, (n[1].i, n[2].i));*/
- break;
- case OPCODE_UNIFORM_2UI:
- /*CALL_Uniform2uiARB(ctx->Exec, (n[1].i, n[2].i, n[3].i));*/
- break;
- case OPCODE_UNIFORM_3UI:
- /*CALL_Uniform3uiARB(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));*/
- break;
- case OPCODE_UNIFORM_4UI:
- /*CALL_Uniform4uiARB(ctx->Exec,
- (n[1].i, n[2].i, n[3].i, n[4].i, n[5].i));
- */
- break;
- case OPCODE_UNIFORM_1UIV:
- /*CALL_Uniform1uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
- break;
- case OPCODE_UNIFORM_2UIV:
- /*CALL_Uniform2uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
- break;
- case OPCODE_UNIFORM_3UIV:
- /*CALL_Uniform3uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
- break;
- case OPCODE_UNIFORM_4UIV:
- /*CALL_Uniform4uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
- break;
- case OPCODE_UNIFORM_MATRIX22:
- CALL_UniformMatrix2fvARB(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX33:
- CALL_UniformMatrix3fvARB(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX44:
- CALL_UniformMatrix4fvARB(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX23:
- CALL_UniformMatrix2x3fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX32:
- CALL_UniformMatrix3x2fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX24:
- CALL_UniformMatrix2x4fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX42:
- CALL_UniformMatrix4x2fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX34:
- CALL_UniformMatrix3x4fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
- case OPCODE_UNIFORM_MATRIX43:
- CALL_UniformMatrix4x3fv(ctx->Exec,
- (n[1].i, n[2].i, n[3].b, n[4].data));
- break;
-
- case OPCODE_TEX_BUMP_PARAMETER_ATI:
- {
- GLfloat values[4];
- GLuint i, pname = n[1].ui;
-
- for (i = 0; i < 4; i++)
- values[i] = n[1 + i].f;
- CALL_TexBumpParameterfvATI(ctx->Exec, (pname, values));
- }
- break;
-#if FEATURE_ATI_fragment_shader
- case OPCODE_BIND_FRAGMENT_SHADER_ATI:
- CALL_BindFragmentShaderATI(ctx->Exec, (n[1].i));
- break;
- case OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI:
- {
- GLfloat values[4];
- GLuint i, dst = n[1].ui;
-
- for (i = 0; i < 4; i++)
- values[i] = n[1 + i].f;
- CALL_SetFragmentShaderConstantATI(ctx->Exec, (dst, values));
- }
- break;
-#endif
- case OPCODE_ATTR_1F_NV:
- CALL_VertexAttrib1fNV(ctx->Exec, (n[1].e, n[2].f));
- break;
- case OPCODE_ATTR_2F_NV:
- /* Really shouldn't have to do this - the Node structure
- * is convenient, but it would be better to store the data
- * packed appropriately so that it can be sent directly
- * on. With x86_64 becoming common, this will start to
- * matter more.
- */
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib2fvNV(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib2fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f));
- break;
- case OPCODE_ATTR_3F_NV:
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib3fvNV(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib3fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f,
- n[4].f));
- break;
- case OPCODE_ATTR_4F_NV:
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib4fvNV(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib4fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f,
- n[4].f, n[5].f));
- break;
- case OPCODE_ATTR_1F_ARB:
- CALL_VertexAttrib1fARB(ctx->Exec, (n[1].e, n[2].f));
- break;
- case OPCODE_ATTR_2F_ARB:
- /* Really shouldn't have to do this - the Node structure
- * is convenient, but it would be better to store the data
- * packed appropriately so that it can be sent directly
- * on. With x86_64 becoming common, this will start to
- * matter more.
- */
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib2fvARB(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib2fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f));
- break;
- case OPCODE_ATTR_3F_ARB:
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib3fvARB(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib3fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f,
- n[4].f));
- break;
- case OPCODE_ATTR_4F_ARB:
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_VertexAttrib4fvARB(ctx->Exec, (n[1].e, &n[2].f));
- else
- CALL_VertexAttrib4fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f,
- n[4].f, n[5].f));
- break;
- case OPCODE_MATERIAL:
- if (sizeof(Node) == sizeof(GLfloat))
- CALL_Materialfv(ctx->Exec, (n[1].e, n[2].e, &n[3].f));
- else {
- GLfloat f[4];
- f[0] = n[3].f;
- f[1] = n[4].f;
- f[2] = n[5].f;
- f[3] = n[6].f;
- CALL_Materialfv(ctx->Exec, (n[1].e, n[2].e, f));
- }
- break;
- case OPCODE_BEGIN:
- CALL_Begin(ctx->Exec, (n[1].e));
- break;
- case OPCODE_END:
- CALL_End(ctx->Exec, ());
- break;
- case OPCODE_RECTF:
- CALL_Rectf(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
- break;
- case OPCODE_EVAL_C1:
- CALL_EvalCoord1f(ctx->Exec, (n[1].f));
- break;
- case OPCODE_EVAL_C2:
- CALL_EvalCoord2f(ctx->Exec, (n[1].f, n[2].f));
- break;
- case OPCODE_EVAL_P1:
- CALL_EvalPoint1(ctx->Exec, (n[1].i));
- break;
- case OPCODE_EVAL_P2:
- CALL_EvalPoint2(ctx->Exec, (n[1].i, n[2].i));
- break;
-
- /* GL_EXT_texture_integer */
- case OPCODE_CLEARCOLOR_I:
- CALL_ClearColorIiEXT(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
- break;
- case OPCODE_CLEARCOLOR_UI:
- CALL_ClearColorIuiEXT(ctx->Exec,
- (n[1].ui, n[2].ui, n[3].ui, n[4].ui));
- break;
- case OPCODE_TEXPARAMETER_I:
- {
- GLint params[4];
- params[0] = n[3].i;
- params[1] = n[4].i;
- params[2] = n[5].i;
- params[3] = n[6].i;
- CALL_TexParameterIivEXT(ctx->Exec, (n[1].e, n[2].e, params));
- }
- break;
- case OPCODE_TEXPARAMETER_UI:
- {
- GLuint params[4];
- params[0] = n[3].ui;
- params[1] = n[4].ui;
- params[2] = n[5].ui;
- params[3] = n[6].ui;
- CALL_TexParameterIuivEXT(ctx->Exec, (n[1].e, n[2].e, params));
- }
- break;
-
- case OPCODE_VERTEX_ATTRIB_DIVISOR:
- /* GL_ARB_instanced_arrays */
- CALL_VertexAttribDivisorARB(ctx->Exec, (n[1].ui, n[2].ui));
- break;
-
- case OPCODE_CONTINUE:
- n = (Node *) n[1].next;
- break;
- case OPCODE_END_OF_LIST:
- done = GL_TRUE;
- break;
- default:
- {
- char msg[1000];
- _mesa_snprintf(msg, sizeof(msg), "Error in execute_list: opcode=%d",
- (int) opcode);
- _mesa_problem(ctx, "%s", msg);
- }
- done = GL_TRUE;
- }
-
- /* increment n to point to next compiled command */
- if (opcode != OPCODE_CONTINUE) {
- n += InstSize[opcode];
- }
- }
- }
-
- if (ctx->Driver.EndCallList)
- ctx->Driver.EndCallList(ctx);
-
- ctx->ListState.CallDepth--;
-}
-
-
-
-/**********************************************************************/
-/* GL functions */
-/**********************************************************************/
-
-/**
- * Test if a display list number is valid.
- */
-static GLboolean GLAPIENTRY
-_mesa_IsList(GLuint list)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0); /* must be called before assert */
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
- return islist(ctx, list);
-}
-
-
-/**
- * Delete a sequence of consecutive display lists.
- */
-static void GLAPIENTRY
-_mesa_DeleteLists(GLuint list, GLsizei range)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLuint i;
- FLUSH_VERTICES(ctx, 0); /* must be called before assert */
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (range < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteLists");
- return;
- }
- for (i = list; i < list + range; i++) {
- destroy_list(ctx, i);
- }
-}
-
-
-/**
- * Return a display list number, n, such that lists n through n+range-1
- * are free.
- */
-static GLuint GLAPIENTRY
-_mesa_GenLists(GLsizei range)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLuint base;
- FLUSH_VERTICES(ctx, 0); /* must be called before assert */
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
-
- if (range < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGenLists");
- return 0;
- }
- if (range == 0) {
- return 0;
- }
-
- /*
- * Make this an atomic operation
- */
- _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
-
- base = _mesa_HashFindFreeKeyBlock(ctx->Shared->DisplayList, range);
- if (base) {
- /* reserve the list IDs by with empty/dummy lists */
- GLint i;
- for (i = 0; i < range; i++) {
- _mesa_HashInsert(ctx->Shared->DisplayList, base + i,
- make_list(base + i, 1));
- }
- }
-
- _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
-
- return base;
-}
-
-
-/**
- * Begin a new display list.
- */
-static void GLAPIENTRY
-_mesa_NewList(GLuint name, GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- FLUSH_CURRENT(ctx, 0); /* must be called before assert */
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glNewList %u %s\n", name,
- _mesa_lookup_enum_by_nr(mode));
-
- if (name == 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glNewList");
- return;
- }
-
- if (mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glNewList");
- return;
- }
-
- if (ctx->ListState.CurrentList) {
- /* already compiling a display list */
- _mesa_error(ctx, GL_INVALID_OPERATION, "glNewList");
- return;
- }
-
- ctx->CompileFlag = GL_TRUE;
- ctx->ExecuteFlag = (mode == GL_COMPILE_AND_EXECUTE);
-
- /* Reset acumulated list state:
- */
- invalidate_saved_current_state( ctx );
-
- /* Allocate new display list */
- ctx->ListState.CurrentList = make_list(name, BLOCK_SIZE);
- ctx->ListState.CurrentBlock = ctx->ListState.CurrentList->Head;
- ctx->ListState.CurrentPos = 0;
-
- ctx->Driver.NewList(ctx, name, mode);
-
- ctx->CurrentDispatch = ctx->Save;
- _glapi_set_dispatch(ctx->CurrentDispatch);
-}
-
-
-/**
- * End definition of current display list.
- */
-static void GLAPIENTRY
-_mesa_EndList(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- SAVE_FLUSH_VERTICES(ctx);
- ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glEndList\n");
-
- /* Check that a list is under construction */
- if (!ctx->ListState.CurrentList) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glEndList");
- return;
- }
-
- /* Call before emitting END_OF_LIST, in case the driver wants to
- * emit opcodes itself.
- */
- ctx->Driver.EndList(ctx);
-
- (void) alloc_instruction(ctx, OPCODE_END_OF_LIST, 0);
-
- /* Destroy old list, if any */
- destroy_list(ctx, ctx->ListState.CurrentList->Name);
-
- /* Install the new list */
- _mesa_HashInsert(ctx->Shared->DisplayList,
- ctx->ListState.CurrentList->Name,
- ctx->ListState.CurrentList);
-
-
- if (MESA_VERBOSE & VERBOSE_DISPLAY_LIST)
- mesa_print_display_list(ctx->ListState.CurrentList->Name);
-
- ctx->ListState.CurrentList = NULL;
- ctx->ExecuteFlag = GL_TRUE;
- ctx->CompileFlag = GL_FALSE;
-
- ctx->CurrentDispatch = ctx->Exec;
- _glapi_set_dispatch(ctx->CurrentDispatch);
-}
-
-
-void GLAPIENTRY
-_mesa_CallList(GLuint list)
-{
- GLboolean save_compile_flag;
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_CURRENT(ctx, 0);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glCallList %d\n", list);
-
- if (list == 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glCallList(list==0)");
- return;
- }
-
- if (0)
- mesa_print_display_list( list );
-
- /* VERY IMPORTANT: Save the CompileFlag status, turn it off,
- * execute the display list, and restore the CompileFlag.
- */
- save_compile_flag = ctx->CompileFlag;
- if (save_compile_flag) {
- ctx->CompileFlag = GL_FALSE;
- }
-
- execute_list(ctx, list);
- ctx->CompileFlag = save_compile_flag;
-
- /* also restore API function pointers to point to "save" versions */
- if (save_compile_flag) {
- ctx->CurrentDispatch = ctx->Save;
- _glapi_set_dispatch(ctx->CurrentDispatch);
- }
-}
-
-
-/**
- * Execute glCallLists: call multiple display lists.
- */
-void GLAPIENTRY
-_mesa_CallLists(GLsizei n, GLenum type, const GLvoid * lists)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint i;
- GLboolean save_compile_flag;
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glCallLists %d\n", n);
-
- switch (type) {
- case GL_BYTE:
- case GL_UNSIGNED_BYTE:
- case GL_SHORT:
- case GL_UNSIGNED_SHORT:
- case GL_INT:
- case GL_UNSIGNED_INT:
- case GL_FLOAT:
- case GL_2_BYTES:
- case GL_3_BYTES:
- case GL_4_BYTES:
- /* OK */
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glCallLists(type)");
- return;
- }
-
- /* Save the CompileFlag status, turn it off, execute display list,
- * and restore the CompileFlag.
- */
- save_compile_flag = ctx->CompileFlag;
- ctx->CompileFlag = GL_FALSE;
-
- for (i = 0; i < n; i++) {
- GLuint list = (GLuint) (ctx->List.ListBase + translate_id(i, type, lists));
- execute_list(ctx, list);
- }
-
- ctx->CompileFlag = save_compile_flag;
-
- /* also restore API function pointers to point to "save" versions */
- if (save_compile_flag) {
- ctx->CurrentDispatch = ctx->Save;
- _glapi_set_dispatch(ctx->CurrentDispatch);
- }
-}
-
-
-/**
- * Set the offset added to list numbers in glCallLists.
- */
-static void GLAPIENTRY
-_mesa_ListBase(GLuint base)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0); /* must be called before assert */
- ASSERT_OUTSIDE_BEGIN_END(ctx);
- ctx->List.ListBase = base;
-}
-
-
-/* Can no longer assume ctx->Exec->Func is equal to _mesa_Func.
- */
-static void GLAPIENTRY
-exec_Finish(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_Finish(ctx->Exec, ());
-}
-
-static void GLAPIENTRY
-exec_Flush(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_Flush(ctx->Exec, ());
-}
-
-static void GLAPIENTRY
-exec_GetBooleanv(GLenum pname, GLboolean *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetBooleanv(ctx->Exec, (pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetClipPlane(GLenum plane, GLdouble * equation)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetClipPlane(ctx->Exec, (plane, equation));
-}
-
-static void GLAPIENTRY
-exec_GetDoublev(GLenum pname, GLdouble *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetDoublev(ctx->Exec, (pname, params));
-}
-
-static GLenum GLAPIENTRY
-exec_GetError(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_GetError(ctx->Exec, ());
-}
-
-static void GLAPIENTRY
-exec_GetFloatv(GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetFloatv(ctx->Exec, (pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetIntegerv(GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetIntegerv(ctx->Exec, (pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetLightfv(GLenum light, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetLightfv(ctx->Exec, (light, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetLightiv(GLenum light, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetLightiv(ctx->Exec, (light, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetMapdv(GLenum target, GLenum query, GLdouble * v)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMapdv(ctx->Exec, (target, query, v));
-}
-
-static void GLAPIENTRY
-exec_GetMapfv(GLenum target, GLenum query, GLfloat * v)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMapfv(ctx->Exec, (target, query, v));
-}
-
-static void GLAPIENTRY
-exec_GetMapiv(GLenum target, GLenum query, GLint * v)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMapiv(ctx->Exec, (target, query, v));
-}
-
-static void GLAPIENTRY
-exec_GetMaterialfv(GLenum face, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMaterialfv(ctx->Exec, (face, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetMaterialiv(GLenum face, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMaterialiv(ctx->Exec, (face, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetPixelMapfv(GLenum map, GLfloat *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetPixelMapfv(ctx->Exec, (map, values));
-}
-
-static void GLAPIENTRY
-exec_GetPixelMapuiv(GLenum map, GLuint *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetPixelMapuiv(ctx->Exec, (map, values));
-}
-
-static void GLAPIENTRY
-exec_GetPixelMapusv(GLenum map, GLushort *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetPixelMapusv(ctx->Exec, (map, values));
-}
-
-static void GLAPIENTRY
-exec_GetPolygonStipple(GLubyte * dest)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetPolygonStipple(ctx->Exec, (dest));
-}
-
-static const GLubyte *GLAPIENTRY
-exec_GetString(GLenum name)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_GetString(ctx->Exec, (name));
-}
-
-static void GLAPIENTRY
-exec_GetTexEnvfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexEnvfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexEnviv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexEnviv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexGendv(GLenum coord, GLenum pname, GLdouble *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexGendv(ctx->Exec, (coord, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexGenfv(GLenum coord, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexGenfv(ctx->Exec, (coord, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexGeniv(GLenum coord, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexGeniv(ctx->Exec, (coord, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexImage(GLenum target, GLint level, GLenum format,
- GLenum type, GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexImage(ctx->Exec, (target, level, format, type, pixels));
-}
-
-static void GLAPIENTRY
-exec_GetTexLevelParameterfv(GLenum target, GLint level,
- GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexLevelParameterfv(ctx->Exec, (target, level, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexLevelParameteriv(GLenum target, GLint level,
- GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexLevelParameteriv(ctx->Exec, (target, level, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexParameterfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetTexParameteriv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetTexParameteriv(ctx->Exec, (target, pname, params));
-}
-
-static GLboolean GLAPIENTRY
-exec_IsEnabled(GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_IsEnabled(ctx->Exec, (cap));
-}
-
-static void GLAPIENTRY
-exec_PixelStoref(GLenum pname, GLfloat param)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_PixelStoref(ctx->Exec, (pname, param));
-}
-
-static void GLAPIENTRY
-exec_PixelStorei(GLenum pname, GLint param)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_PixelStorei(ctx->Exec, (pname, param));
-}
-
-static void GLAPIENTRY
-exec_ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
- GLenum format, GLenum type, GLvoid * pixels)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_ReadPixels(ctx->Exec, (x, y, width, height, format, type, pixels));
-}
-
-static GLint GLAPIENTRY
-exec_RenderMode(GLenum mode)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_RenderMode(ctx->Exec, (mode));
-}
-
-static void GLAPIENTRY
-exec_FeedbackBuffer(GLsizei size, GLenum type, GLfloat * buffer)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_FeedbackBuffer(ctx->Exec, (size, type, buffer));
-}
-
-static void GLAPIENTRY
-exec_SelectBuffer(GLsizei size, GLuint * buffer)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_SelectBuffer(ctx->Exec, (size, buffer));
-}
-
-static GLboolean GLAPIENTRY
-exec_AreTexturesResident(GLsizei n, const GLuint * texName,
- GLboolean * residences)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_AreTexturesResident(ctx->Exec, (n, texName, residences));
-}
-
-static void GLAPIENTRY
-exec_ColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_ColorPointer(ctx->Exec, (size, type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_DeleteTextures(GLsizei n, const GLuint * texName)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_DeleteTextures(ctx->Exec, (n, texName));
-}
-
-static void GLAPIENTRY
-exec_DisableClientState(GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_DisableClientState(ctx->Exec, (cap));
-}
-
-static void GLAPIENTRY
-exec_EdgeFlagPointer(GLsizei stride, const GLvoid * vptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_EdgeFlagPointer(ctx->Exec, (stride, vptr));
-}
-
-static void GLAPIENTRY
-exec_EnableClientState(GLenum cap)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_EnableClientState(ctx->Exec, (cap));
-}
-
-static void GLAPIENTRY
-exec_GenTextures(GLsizei n, GLuint * texName)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GenTextures(ctx->Exec, (n, texName));
-}
-
-static void GLAPIENTRY
-exec_GetPointerv(GLenum pname, GLvoid **params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetPointerv(ctx->Exec, (pname, params));
-}
-
-static void GLAPIENTRY
-exec_IndexPointer(GLenum type, GLsizei stride, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_IndexPointer(ctx->Exec, (type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_InterleavedArrays(GLenum format, GLsizei stride, const GLvoid * pointer)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_InterleavedArrays(ctx->Exec, (format, stride, pointer));
-}
-
-static GLboolean GLAPIENTRY
-exec_IsTexture(GLuint texture)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- return CALL_IsTexture(ctx->Exec, (texture));
-}
-
-static void GLAPIENTRY
-exec_NormalPointer(GLenum type, GLsizei stride, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_NormalPointer(ctx->Exec, (type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_PopClientAttrib(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_PopClientAttrib(ctx->Exec, ());
-}
-
-static void GLAPIENTRY
-exec_PushClientAttrib(GLbitfield mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_PushClientAttrib(ctx->Exec, (mask));
-}
-
-static void GLAPIENTRY
-exec_TexCoordPointer(GLint size, GLenum type, GLsizei stride,
- const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_TexCoordPointer(ctx->Exec, (size, type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_GetCompressedTexImageARB(GLenum target, GLint level, GLvoid * img)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetCompressedTexImageARB(ctx->Exec, (target, level, img));
-}
-
-static void GLAPIENTRY
-exec_VertexPointer(GLint size, GLenum type, GLsizei stride,
- const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_VertexPointer(ctx->Exec, (size, type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_CopyConvolutionFilter1D(GLenum target, GLenum internalFormat,
- GLint x, GLint y, GLsizei width)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_CopyConvolutionFilter1D(ctx->Exec,
- (target, internalFormat, x, y, width));
-}
-
-static void GLAPIENTRY
-exec_CopyConvolutionFilter2D(GLenum target, GLenum internalFormat,
- GLint x, GLint y, GLsizei width, GLsizei height)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_CopyConvolutionFilter2D(ctx->Exec,
- (target, internalFormat, x, y, width,
- height));
-}
-
-static void GLAPIENTRY
-exec_GetColorTable(GLenum target, GLenum format, GLenum type, GLvoid * data)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetColorTable(ctx->Exec, (target, format, type, data));
-}
-
-static void GLAPIENTRY
-exec_GetColorTableParameterfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetColorTableParameterfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetColorTableParameteriv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetColorTableParameteriv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetConvolutionFilter(GLenum target, GLenum format, GLenum type,
- GLvoid * image)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetConvolutionFilter(ctx->Exec, (target, format, type, image));
-}
-
-static void GLAPIENTRY
-exec_GetConvolutionParameterfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetConvolutionParameterfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetConvolutionParameteriv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetConvolutionParameteriv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetHistogram(GLenum target, GLboolean reset, GLenum format,
- GLenum type, GLvoid *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetHistogram(ctx->Exec, (target, reset, format, type, values));
-}
-
-static void GLAPIENTRY
-exec_GetHistogramParameterfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetHistogramParameterfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetHistogramParameteriv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetHistogramParameteriv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetMinmax(GLenum target, GLboolean reset, GLenum format,
- GLenum type, GLvoid *values)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMinmax(ctx->Exec, (target, reset, format, type, values));
-}
-
-static void GLAPIENTRY
-exec_GetMinmaxParameterfv(GLenum target, GLenum pname, GLfloat *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMinmaxParameterfv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetMinmaxParameteriv(GLenum target, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetMinmaxParameteriv(ctx->Exec, (target, pname, params));
-}
-
-static void GLAPIENTRY
-exec_GetSeparableFilter(GLenum target, GLenum format, GLenum type,
- GLvoid *row, GLvoid *column, GLvoid *span)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_GetSeparableFilter(ctx->Exec,
- (target, format, type, row, column, span));
-}
-
-static void GLAPIENTRY
-exec_SeparableFilter2D(GLenum target, GLenum internalFormat,
- GLsizei width, GLsizei height, GLenum format,
- GLenum type, const GLvoid *row, const GLvoid *column)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_SeparableFilter2D(ctx->Exec,
- (target, internalFormat, width, height, format,
- type, row, column));
-}
-
-static void GLAPIENTRY
-exec_ColorPointerEXT(GLint size, GLenum type, GLsizei stride,
- GLsizei count, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_ColorPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_EdgeFlagPointerEXT(GLsizei stride, GLsizei count, const GLboolean *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_EdgeFlagPointerEXT(ctx->Exec, (stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_IndexPointerEXT(GLenum type, GLsizei stride, GLsizei count,
- const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_IndexPointerEXT(ctx->Exec, (type, stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_NormalPointerEXT(GLenum type, GLsizei stride, GLsizei count,
- const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_NormalPointerEXT(ctx->Exec, (type, stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_TexCoordPointerEXT(GLint size, GLenum type, GLsizei stride,
- GLsizei count, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_TexCoordPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_VertexPointerEXT(GLint size, GLenum type, GLsizei stride,
- GLsizei count, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_VertexPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
-}
-
-static void GLAPIENTRY
-exec_LockArraysEXT(GLint first, GLsizei count)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_LockArraysEXT(ctx->Exec, (first, count));
-}
-
-static void GLAPIENTRY
-exec_UnlockArraysEXT(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_UnlockArraysEXT(ctx->Exec, ());
-}
-
-static void GLAPIENTRY
-exec_ClientActiveTextureARB(GLenum target)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_ClientActiveTextureARB(ctx->Exec, (target));
-}
-
-static void GLAPIENTRY
-exec_SecondaryColorPointerEXT(GLint size, GLenum type,
- GLsizei stride, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_SecondaryColorPointerEXT(ctx->Exec, (size, type, stride, ptr));
-}
-
-static void GLAPIENTRY
-exec_FogCoordPointerEXT(GLenum type, GLsizei stride, const GLvoid *ptr)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_FogCoordPointerEXT(ctx->Exec, (type, stride, ptr));
-}
-
-/* GL_EXT_multi_draw_arrays */
-static void GLAPIENTRY
-exec_MultiDrawArraysEXT(GLenum mode, const GLint *first,
- const GLsizei *count, GLsizei primcount)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_MultiDrawArraysEXT(ctx->Exec, (mode, first, count, primcount));
-}
-
-/* GL_IBM_multimode_draw_arrays */
-static void GLAPIENTRY
-exec_MultiModeDrawArraysIBM(const GLenum * mode, const GLint * first,
- const GLsizei * count, GLsizei primcount,
- GLint modestride)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_MultiModeDrawArraysIBM(ctx->Exec,
- (mode, first, count, primcount, modestride));
-}
-
-/* GL_IBM_multimode_draw_arrays */
-static void GLAPIENTRY
-exec_MultiModeDrawElementsIBM(const GLenum * mode,
- const GLsizei * count,
- GLenum type,
- const GLvoid * const *indices,
- GLsizei primcount, GLint modestride)
-{
- GET_CURRENT_CONTEXT(ctx);
- FLUSH_VERTICES(ctx, 0);
- CALL_MultiModeDrawElementsIBM(ctx->Exec,
- (mode, count, type, indices, primcount,
- modestride));
-}
-
-
-
-/**
- * Setup the given dispatch table to point to Mesa's display list
- * building functions.
- *
- * This does not include any of the tnl functions - they are
- * initialized from _mesa_init_api_defaults and from the active vtxfmt
- * struct.
- */
-struct _glapi_table *
-_mesa_create_save_table(void)
-{
- struct _glapi_table *table;
-
- table = _mesa_alloc_dispatch_table(_gloffset_COUNT);
- if (table == NULL)
- return NULL;
-
- _mesa_loopback_init_api_table(table);
-
- /* GL 1.0 */
- SET_Accum(table, save_Accum);
- SET_AlphaFunc(table, save_AlphaFunc);
- SET_Bitmap(table, save_Bitmap);
- SET_BlendFunc(table, save_BlendFunc);
- SET_CallList(table, save_CallList);
- SET_CallLists(table, save_CallLists);
- SET_Clear(table, save_Clear);
- SET_ClearAccum(table, save_ClearAccum);
- SET_ClearColor(table, save_ClearColor);
- SET_ClearDepth(table, save_ClearDepth);
- SET_ClearIndex(table, save_ClearIndex);
- SET_ClearStencil(table, save_ClearStencil);
- SET_ClipPlane(table, save_ClipPlane);
- SET_ColorMask(table, save_ColorMask);
- SET_ColorMaskIndexedEXT(table, save_ColorMaskIndexed);
- SET_ColorMaterial(table, save_ColorMaterial);
- SET_CopyPixels(table, save_CopyPixels);
- SET_CullFace(table, save_CullFace);
- SET_DeleteLists(table, _mesa_DeleteLists);
- SET_DepthFunc(table, save_DepthFunc);
- SET_DepthMask(table, save_DepthMask);
- SET_DepthRange(table, save_DepthRange);
- SET_Disable(table, save_Disable);
- SET_DisableIndexedEXT(table, save_DisableIndexed);
- SET_DrawBuffer(table, save_DrawBuffer);
- SET_DrawPixels(table, save_DrawPixels);
- SET_Enable(table, save_Enable);
- SET_EnableIndexedEXT(table, save_EnableIndexed);
- SET_EndList(table, _mesa_EndList);
- SET_EvalMesh1(table, save_EvalMesh1);
- SET_EvalMesh2(table, save_EvalMesh2);
- SET_Finish(table, exec_Finish);
- SET_Flush(table, exec_Flush);
- SET_Fogf(table, save_Fogf);
- SET_Fogfv(table, save_Fogfv);
- SET_Fogi(table, save_Fogi);
- SET_Fogiv(table, save_Fogiv);
- SET_FrontFace(table, save_FrontFace);
- SET_Frustum(table, save_Frustum);
- SET_GenLists(table, _mesa_GenLists);
- SET_GetBooleanv(table, exec_GetBooleanv);
- SET_GetClipPlane(table, exec_GetClipPlane);
- SET_GetDoublev(table, exec_GetDoublev);
- SET_GetError(table, exec_GetError);
- SET_GetFloatv(table, exec_GetFloatv);
- SET_GetIntegerv(table, exec_GetIntegerv);
- SET_GetLightfv(table, exec_GetLightfv);
- SET_GetLightiv(table, exec_GetLightiv);
- SET_GetMapdv(table, exec_GetMapdv);
- SET_GetMapfv(table, exec_GetMapfv);
- SET_GetMapiv(table, exec_GetMapiv);
- SET_GetMaterialfv(table, exec_GetMaterialfv);
- SET_GetMaterialiv(table, exec_GetMaterialiv);
- SET_GetPixelMapfv(table, exec_GetPixelMapfv);
- SET_GetPixelMapuiv(table, exec_GetPixelMapuiv);
- SET_GetPixelMapusv(table, exec_GetPixelMapusv);
- SET_GetPolygonStipple(table, exec_GetPolygonStipple);
- SET_GetString(table, exec_GetString);
- SET_GetTexEnvfv(table, exec_GetTexEnvfv);
- SET_GetTexEnviv(table, exec_GetTexEnviv);
- SET_GetTexGendv(table, exec_GetTexGendv);
- SET_GetTexGenfv(table, exec_GetTexGenfv);
- SET_GetTexGeniv(table, exec_GetTexGeniv);
- SET_GetTexImage(table, exec_GetTexImage);
- SET_GetTexLevelParameterfv(table, exec_GetTexLevelParameterfv);
- SET_GetTexLevelParameteriv(table, exec_GetTexLevelParameteriv);
- SET_GetTexParameterfv(table, exec_GetTexParameterfv);
- SET_GetTexParameteriv(table, exec_GetTexParameteriv);
- SET_Hint(table, save_Hint);
- SET_IndexMask(table, save_IndexMask);
- SET_InitNames(table, save_InitNames);
- SET_IsEnabled(table, exec_IsEnabled);
- SET_IsList(table, _mesa_IsList);
- SET_LightModelf(table, save_LightModelf);
- SET_LightModelfv(table, save_LightModelfv);
- SET_LightModeli(table, save_LightModeli);
- SET_LightModeliv(table, save_LightModeliv);
- SET_Lightf(table, save_Lightf);
- SET_Lightfv(table, save_Lightfv);
- SET_Lighti(table, save_Lighti);
- SET_Lightiv(table, save_Lightiv);
- SET_LineStipple(table, save_LineStipple);
- SET_LineWidth(table, save_LineWidth);
- SET_ListBase(table, save_ListBase);
- SET_LoadIdentity(table, save_LoadIdentity);
- SET_LoadMatrixd(table, save_LoadMatrixd);
- SET_LoadMatrixf(table, save_LoadMatrixf);
- SET_LoadName(table, save_LoadName);
- SET_LogicOp(table, save_LogicOp);
- SET_Map1d(table, save_Map1d);
- SET_Map1f(table, save_Map1f);
- SET_Map2d(table, save_Map2d);
- SET_Map2f(table, save_Map2f);
- SET_MapGrid1d(table, save_MapGrid1d);
- SET_MapGrid1f(table, save_MapGrid1f);
- SET_MapGrid2d(table, save_MapGrid2d);
- SET_MapGrid2f(table, save_MapGrid2f);
- SET_MatrixMode(table, save_MatrixMode);
- SET_MultMatrixd(table, save_MultMatrixd);
- SET_MultMatrixf(table, save_MultMatrixf);
- SET_NewList(table, save_NewList);
- SET_Ortho(table, save_Ortho);
- SET_PassThrough(table, save_PassThrough);
- SET_PixelMapfv(table, save_PixelMapfv);
- SET_PixelMapuiv(table, save_PixelMapuiv);
- SET_PixelMapusv(table, save_PixelMapusv);
- SET_PixelStoref(table, exec_PixelStoref);
- SET_PixelStorei(table, exec_PixelStorei);
- SET_PixelTransferf(table, save_PixelTransferf);
- SET_PixelTransferi(table, save_PixelTransferi);
- SET_PixelZoom(table, save_PixelZoom);
- SET_PointSize(table, save_PointSize);
- SET_PolygonMode(table, save_PolygonMode);
- SET_PolygonOffset(table, save_PolygonOffset);
- SET_PolygonStipple(table, save_PolygonStipple);
- SET_PopAttrib(table, save_PopAttrib);
- SET_PopMatrix(table, save_PopMatrix);
- SET_PopName(table, save_PopName);
- SET_PushAttrib(table, save_PushAttrib);
- SET_PushMatrix(table, save_PushMatrix);
- SET_PushName(table, save_PushName);
- SET_RasterPos2d(table, save_RasterPos2d);
- SET_RasterPos2dv(table, save_RasterPos2dv);
- SET_RasterPos2f(table, save_RasterPos2f);
- SET_RasterPos2fv(table, save_RasterPos2fv);
- SET_RasterPos2i(table, save_RasterPos2i);
- SET_RasterPos2iv(table, save_RasterPos2iv);
- SET_RasterPos2s(table, save_RasterPos2s);
- SET_RasterPos2sv(table, save_RasterPos2sv);
- SET_RasterPos3d(table, save_RasterPos3d);
- SET_RasterPos3dv(table, save_RasterPos3dv);
- SET_RasterPos3f(table, save_RasterPos3f);
- SET_RasterPos3fv(table, save_RasterPos3fv);
- SET_RasterPos3i(table, save_RasterPos3i);
- SET_RasterPos3iv(table, save_RasterPos3iv);
- SET_RasterPos3s(table, save_RasterPos3s);
- SET_RasterPos3sv(table, save_RasterPos3sv);
- SET_RasterPos4d(table, save_RasterPos4d);
- SET_RasterPos4dv(table, save_RasterPos4dv);
- SET_RasterPos4f(table, save_RasterPos4f);
- SET_RasterPos4fv(table, save_RasterPos4fv);
- SET_RasterPos4i(table, save_RasterPos4i);
- SET_RasterPos4iv(table, save_RasterPos4iv);
- SET_RasterPos4s(table, save_RasterPos4s);
- SET_RasterPos4sv(table, save_RasterPos4sv);
- SET_ReadBuffer(table, save_ReadBuffer);
- SET_ReadPixels(table, exec_ReadPixels);
- SET_RenderMode(table, exec_RenderMode);
- SET_Rotated(table, save_Rotated);
- SET_Rotatef(table, save_Rotatef);
- SET_Scaled(table, save_Scaled);
- SET_Scalef(table, save_Scalef);
- SET_Scissor(table, save_Scissor);
- SET_FeedbackBuffer(table, exec_FeedbackBuffer);
- SET_SelectBuffer(table, exec_SelectBuffer);
- SET_ShadeModel(table, save_ShadeModel);
- SET_StencilFunc(table, save_StencilFunc);
- SET_StencilMask(table, save_StencilMask);
- SET_StencilOp(table, save_StencilOp);
- SET_TexEnvf(table, save_TexEnvf);
- SET_TexEnvfv(table, save_TexEnvfv);
- SET_TexEnvi(table, save_TexEnvi);
- SET_TexEnviv(table, save_TexEnviv);
- SET_TexGend(table, save_TexGend);
- SET_TexGendv(table, save_TexGendv);
- SET_TexGenf(table, save_TexGenf);
- SET_TexGenfv(table, save_TexGenfv);
- SET_TexGeni(table, save_TexGeni);
- SET_TexGeniv(table, save_TexGeniv);
- SET_TexImage1D(table, save_TexImage1D);
- SET_TexImage2D(table, save_TexImage2D);
- SET_TexParameterf(table, save_TexParameterf);
- SET_TexParameterfv(table, save_TexParameterfv);
- SET_TexParameteri(table, save_TexParameteri);
- SET_TexParameteriv(table, save_TexParameteriv);
- SET_Translated(table, save_Translated);
- SET_Translatef(table, save_Translatef);
- SET_Viewport(table, save_Viewport);
-
- /* GL 1.1 */
- SET_AreTexturesResident(table, exec_AreTexturesResident);
- SET_BindTexture(table, save_BindTexture);
- SET_ColorPointer(table, exec_ColorPointer);
- SET_CopyTexImage1D(table, save_CopyTexImage1D);
- SET_CopyTexImage2D(table, save_CopyTexImage2D);
- SET_CopyTexSubImage1D(table, save_CopyTexSubImage1D);
- SET_CopyTexSubImage2D(table, save_CopyTexSubImage2D);
- SET_DeleteTextures(table, exec_DeleteTextures);
- SET_DisableClientState(table, exec_DisableClientState);
- SET_EdgeFlagPointer(table, exec_EdgeFlagPointer);
- SET_EnableClientState(table, exec_EnableClientState);
- SET_GenTextures(table, exec_GenTextures);
- SET_GetPointerv(table, exec_GetPointerv);
- SET_IndexPointer(table, exec_IndexPointer);
- SET_InterleavedArrays(table, exec_InterleavedArrays);
- SET_IsTexture(table, exec_IsTexture);
- SET_NormalPointer(table, exec_NormalPointer);
- SET_PopClientAttrib(table, exec_PopClientAttrib);
- SET_PrioritizeTextures(table, save_PrioritizeTextures);
- SET_PushClientAttrib(table, exec_PushClientAttrib);
- SET_TexCoordPointer(table, exec_TexCoordPointer);
- SET_TexSubImage1D(table, save_TexSubImage1D);
- SET_TexSubImage2D(table, save_TexSubImage2D);
- SET_VertexPointer(table, exec_VertexPointer);
-
- /* GL 1.2 */
- SET_CopyTexSubImage3D(table, save_CopyTexSubImage3D);
- SET_TexImage3D(table, save_TexImage3D);
- SET_TexSubImage3D(table, save_TexSubImage3D);
-
- /* GL 2.0 */
- SET_StencilFuncSeparate(table, save_StencilFuncSeparate);
- SET_StencilMaskSeparate(table, save_StencilMaskSeparate);
- SET_StencilOpSeparate(table, save_StencilOpSeparate);
-
- /* ATI_separate_stencil */
- SET_StencilFuncSeparateATI(table, save_StencilFuncSeparateATI);
-
- /* GL_ARB_imaging */
- /* Not all are supported */
- SET_BlendColor(table, save_BlendColor);
- SET_BlendEquation(table, save_BlendEquation);
- SET_ColorSubTable(table, save_ColorSubTable);
- SET_ColorTable(table, save_ColorTable);
- SET_ColorTableParameterfv(table, save_ColorTableParameterfv);
- SET_ColorTableParameteriv(table, save_ColorTableParameteriv);
- SET_ConvolutionFilter1D(table, save_ConvolutionFilter1D);
- SET_ConvolutionFilter2D(table, save_ConvolutionFilter2D);
- SET_ConvolutionParameterf(table, save_ConvolutionParameterf);
- SET_ConvolutionParameterfv(table, save_ConvolutionParameterfv);
- SET_ConvolutionParameteri(table, save_ConvolutionParameteri);
- SET_ConvolutionParameteriv(table, save_ConvolutionParameteriv);
- SET_CopyColorSubTable(table, save_CopyColorSubTable);
- SET_CopyColorTable(table, save_CopyColorTable);
- SET_CopyConvolutionFilter1D(table, exec_CopyConvolutionFilter1D);
- SET_CopyConvolutionFilter2D(table, exec_CopyConvolutionFilter2D);
- SET_GetColorTable(table, exec_GetColorTable);
- SET_GetColorTableParameterfv(table, exec_GetColorTableParameterfv);
- SET_GetColorTableParameteriv(table, exec_GetColorTableParameteriv);
- SET_GetConvolutionFilter(table, exec_GetConvolutionFilter);
- SET_GetConvolutionParameterfv(table, exec_GetConvolutionParameterfv);
- SET_GetConvolutionParameteriv(table, exec_GetConvolutionParameteriv);
- SET_GetHistogram(table, exec_GetHistogram);
- SET_GetHistogramParameterfv(table, exec_GetHistogramParameterfv);
- SET_GetHistogramParameteriv(table, exec_GetHistogramParameteriv);
- SET_GetMinmax(table, exec_GetMinmax);
- SET_GetMinmaxParameterfv(table, exec_GetMinmaxParameterfv);
- SET_GetMinmaxParameteriv(table, exec_GetMinmaxParameteriv);
- SET_GetSeparableFilter(table, exec_GetSeparableFilter);
- SET_Histogram(table, save_Histogram);
- SET_Minmax(table, save_Minmax);
- SET_ResetHistogram(table, save_ResetHistogram);
- SET_ResetMinmax(table, save_ResetMinmax);
- SET_SeparableFilter2D(table, exec_SeparableFilter2D);
-
- /* 2. GL_EXT_blend_color */
-#if 0
- SET_BlendColorEXT(table, save_BlendColorEXT);
-#endif
-
- /* 3. GL_EXT_polygon_offset */
- SET_PolygonOffsetEXT(table, save_PolygonOffsetEXT);
-
- /* 6. GL_EXT_texture3d */
-#if 0
- SET_CopyTexSubImage3DEXT(table, save_CopyTexSubImage3D);
- SET_TexImage3DEXT(table, save_TexImage3DEXT);
- SET_TexSubImage3DEXT(table, save_TexSubImage3D);
-#endif
-
- /* 14. GL_SGI_color_table */
-#if 0
- SET_ColorTableSGI(table, save_ColorTable);
- SET_ColorSubTableSGI(table, save_ColorSubTable);
- SET_GetColorTableSGI(table, exec_GetColorTable);
- SET_GetColorTableParameterfvSGI(table, exec_GetColorTableParameterfv);
- SET_GetColorTableParameterivSGI(table, exec_GetColorTableParameteriv);
-#endif
-
- /* 30. GL_EXT_vertex_array */
- SET_ColorPointerEXT(table, exec_ColorPointerEXT);
- SET_EdgeFlagPointerEXT(table, exec_EdgeFlagPointerEXT);
- SET_IndexPointerEXT(table, exec_IndexPointerEXT);
- SET_NormalPointerEXT(table, exec_NormalPointerEXT);
- SET_TexCoordPointerEXT(table, exec_TexCoordPointerEXT);
- SET_VertexPointerEXT(table, exec_VertexPointerEXT);
-
- /* 37. GL_EXT_blend_minmax */
-#if 0
- SET_BlendEquationEXT(table, save_BlendEquationEXT);
-#endif
-
- /* 54. GL_EXT_point_parameters */
- SET_PointParameterfEXT(table, save_PointParameterfEXT);
- SET_PointParameterfvEXT(table, save_PointParameterfvEXT);
-
- /* 97. GL_EXT_compiled_vertex_array */
- SET_LockArraysEXT(table, exec_LockArraysEXT);
- SET_UnlockArraysEXT(table, exec_UnlockArraysEXT);
-
- /* 145. GL_EXT_secondary_color */
- SET_SecondaryColorPointerEXT(table, exec_SecondaryColorPointerEXT);
-
- /* 148. GL_EXT_multi_draw_arrays */
- SET_MultiDrawArraysEXT(table, exec_MultiDrawArraysEXT);
-
- /* 149. GL_EXT_fog_coord */
- SET_FogCoordPointerEXT(table, exec_FogCoordPointerEXT);
-
- /* 173. GL_EXT_blend_func_separate */
- SET_BlendFuncSeparateEXT(table, save_BlendFuncSeparateEXT);
-
- /* 196. GL_MESA_resize_buffers */
- SET_ResizeBuffersMESA(table, _mesa_ResizeBuffersMESA);
-
- /* 197. GL_MESA_window_pos */
- SET_WindowPos2dMESA(table, save_WindowPos2dMESA);
- SET_WindowPos2dvMESA(table, save_WindowPos2dvMESA);
- SET_WindowPos2fMESA(table, save_WindowPos2fMESA);
- SET_WindowPos2fvMESA(table, save_WindowPos2fvMESA);
- SET_WindowPos2iMESA(table, save_WindowPos2iMESA);
- SET_WindowPos2ivMESA(table, save_WindowPos2ivMESA);
- SET_WindowPos2sMESA(table, save_WindowPos2sMESA);
- SET_WindowPos2svMESA(table, save_WindowPos2svMESA);
- SET_WindowPos3dMESA(table, save_WindowPos3dMESA);
- SET_WindowPos3dvMESA(table, save_WindowPos3dvMESA);
- SET_WindowPos3fMESA(table, save_WindowPos3fMESA);
- SET_WindowPos3fvMESA(table, save_WindowPos3fvMESA);
- SET_WindowPos3iMESA(table, save_WindowPos3iMESA);
- SET_WindowPos3ivMESA(table, save_WindowPos3ivMESA);
- SET_WindowPos3sMESA(table, save_WindowPos3sMESA);
- SET_WindowPos3svMESA(table, save_WindowPos3svMESA);
- SET_WindowPos4dMESA(table, save_WindowPos4dMESA);
- SET_WindowPos4dvMESA(table, save_WindowPos4dvMESA);
- SET_WindowPos4fMESA(table, save_WindowPos4fMESA);
- SET_WindowPos4fvMESA(table, save_WindowPos4fvMESA);
- SET_WindowPos4iMESA(table, save_WindowPos4iMESA);
- SET_WindowPos4ivMESA(table, save_WindowPos4ivMESA);
- SET_WindowPos4sMESA(table, save_WindowPos4sMESA);
- SET_WindowPos4svMESA(table, save_WindowPos4svMESA);
-
- /* 200. GL_IBM_multimode_draw_arrays */
- SET_MultiModeDrawArraysIBM(table, exec_MultiModeDrawArraysIBM);
- SET_MultiModeDrawElementsIBM(table, exec_MultiModeDrawElementsIBM);
-
-#if FEATURE_NV_vertex_program
- /* 233. GL_NV_vertex_program */
- /* The following commands DO NOT go into display lists:
- * AreProgramsResidentNV, IsProgramNV, GenProgramsNV, DeleteProgramsNV,
- * VertexAttribPointerNV, GetProgram*, GetVertexAttrib*
- */
- SET_BindProgramNV(table, save_BindProgramNV);
- SET_DeleteProgramsNV(table, _mesa_DeletePrograms);
- SET_ExecuteProgramNV(table, save_ExecuteProgramNV);
- SET_GenProgramsNV(table, _mesa_GenPrograms);
- SET_AreProgramsResidentNV(table, _mesa_AreProgramsResidentNV);
- SET_RequestResidentProgramsNV(table, save_RequestResidentProgramsNV);
- SET_GetProgramParameterfvNV(table, _mesa_GetProgramParameterfvNV);
- SET_GetProgramParameterdvNV(table, _mesa_GetProgramParameterdvNV);
- SET_GetProgramivNV(table, _mesa_GetProgramivNV);
- SET_GetProgramStringNV(table, _mesa_GetProgramStringNV);
- SET_GetTrackMatrixivNV(table, _mesa_GetTrackMatrixivNV);
- SET_GetVertexAttribdvNV(table, _mesa_GetVertexAttribdvNV);
- SET_GetVertexAttribfvNV(table, _mesa_GetVertexAttribfvNV);
- SET_GetVertexAttribivNV(table, _mesa_GetVertexAttribivNV);
- SET_GetVertexAttribPointervNV(table, _mesa_GetVertexAttribPointervNV);
- SET_IsProgramNV(table, _mesa_IsProgramARB);
- SET_LoadProgramNV(table, save_LoadProgramNV);
- SET_ProgramEnvParameter4dARB(table, save_ProgramEnvParameter4dARB);
- SET_ProgramEnvParameter4dvARB(table, save_ProgramEnvParameter4dvARB);
- SET_ProgramEnvParameter4fARB(table, save_ProgramEnvParameter4fARB);
- SET_ProgramEnvParameter4fvARB(table, save_ProgramEnvParameter4fvARB);
- SET_ProgramParameters4dvNV(table, save_ProgramParameters4dvNV);
- SET_ProgramParameters4fvNV(table, save_ProgramParameters4fvNV);
- SET_TrackMatrixNV(table, save_TrackMatrixNV);
- SET_VertexAttribPointerNV(table, _mesa_VertexAttribPointerNV);
-#endif
-
- /* 244. GL_ATI_envmap_bumpmap */
- SET_TexBumpParameterivATI(table, save_TexBumpParameterivATI);
- SET_TexBumpParameterfvATI(table, save_TexBumpParameterfvATI);
-
- /* 245. GL_ATI_fragment_shader */
-#if FEATURE_ATI_fragment_shader
- SET_BindFragmentShaderATI(table, save_BindFragmentShaderATI);
- SET_SetFragmentShaderConstantATI(table, save_SetFragmentShaderConstantATI);
-#endif
-
- /* 282. GL_NV_fragment_program */
-#if FEATURE_NV_fragment_program
- SET_ProgramNamedParameter4fNV(table, save_ProgramNamedParameter4fNV);
- SET_ProgramNamedParameter4dNV(table, save_ProgramNamedParameter4dNV);
- SET_ProgramNamedParameter4fvNV(table, save_ProgramNamedParameter4fvNV);
- SET_ProgramNamedParameter4dvNV(table, save_ProgramNamedParameter4dvNV);
- SET_GetProgramNamedParameterfvNV(table,
- _mesa_GetProgramNamedParameterfvNV);
- SET_GetProgramNamedParameterdvNV(table,
- _mesa_GetProgramNamedParameterdvNV);
- SET_ProgramLocalParameter4dARB(table, save_ProgramLocalParameter4dARB);
- SET_ProgramLocalParameter4dvARB(table, save_ProgramLocalParameter4dvARB);
- SET_ProgramLocalParameter4fARB(table, save_ProgramLocalParameter4fARB);
- SET_ProgramLocalParameter4fvARB(table, save_ProgramLocalParameter4fvARB);
- SET_GetProgramLocalParameterdvARB(table,
- _mesa_GetProgramLocalParameterdvARB);
- SET_GetProgramLocalParameterfvARB(table,
- _mesa_GetProgramLocalParameterfvARB);
-#endif
-
- /* 262. GL_NV_point_sprite */
- SET_PointParameteriNV(table, save_PointParameteriNV);
- SET_PointParameterivNV(table, save_PointParameterivNV);
-
- /* 268. GL_EXT_stencil_two_side */
- SET_ActiveStencilFaceEXT(table, save_ActiveStencilFaceEXT);
-
- /* 273. GL_APPLE_vertex_array_object */
- SET_BindVertexArrayAPPLE(table, _mesa_BindVertexArrayAPPLE);
- SET_DeleteVertexArraysAPPLE(table, _mesa_DeleteVertexArraysAPPLE);
- SET_GenVertexArraysAPPLE(table, _mesa_GenVertexArraysAPPLE);
- SET_IsVertexArrayAPPLE(table, _mesa_IsVertexArrayAPPLE);
-
- /* ???. GL_EXT_depth_bounds_test */
- SET_DepthBoundsEXT(table, save_DepthBoundsEXT);
-
- /* ARB 1. GL_ARB_multitexture */
- SET_ActiveTextureARB(table, save_ActiveTextureARB);
- SET_ClientActiveTextureARB(table, exec_ClientActiveTextureARB);
-
- /* ARB 3. GL_ARB_transpose_matrix */
- SET_LoadTransposeMatrixdARB(table, save_LoadTransposeMatrixdARB);
- SET_LoadTransposeMatrixfARB(table, save_LoadTransposeMatrixfARB);
- SET_MultTransposeMatrixdARB(table, save_MultTransposeMatrixdARB);
- SET_MultTransposeMatrixfARB(table, save_MultTransposeMatrixfARB);
-
- /* ARB 5. GL_ARB_multisample */
- SET_SampleCoverageARB(table, save_SampleCoverageARB);
-
- /* ARB 12. GL_ARB_texture_compression */
- SET_CompressedTexImage3DARB(table, save_CompressedTexImage3DARB);
- SET_CompressedTexImage2DARB(table, save_CompressedTexImage2DARB);
- SET_CompressedTexImage1DARB(table, save_CompressedTexImage1DARB);
- SET_CompressedTexSubImage3DARB(table, save_CompressedTexSubImage3DARB);
- SET_CompressedTexSubImage2DARB(table, save_CompressedTexSubImage2DARB);
- SET_CompressedTexSubImage1DARB(table, save_CompressedTexSubImage1DARB);
- SET_GetCompressedTexImageARB(table, exec_GetCompressedTexImageARB);
-
- /* ARB 14. GL_ARB_point_parameters */
- /* aliased with EXT_point_parameters functions */
-
- /* ARB 25. GL_ARB_window_pos */
- /* aliased with MESA_window_pos functions */
-
- /* ARB 26. GL_ARB_vertex_program */
- /* ARB 27. GL_ARB_fragment_program */
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
- /* glVertexAttrib* functions alias the NV ones, handled elsewhere */
- SET_VertexAttribPointerARB(table, _mesa_VertexAttribPointerARB);
- SET_EnableVertexAttribArrayARB(table, _mesa_EnableVertexAttribArrayARB);
- SET_DisableVertexAttribArrayARB(table, _mesa_DisableVertexAttribArrayARB);
- SET_ProgramStringARB(table, save_ProgramStringARB);
- SET_BindProgramNV(table, save_BindProgramNV);
- SET_DeleteProgramsNV(table, _mesa_DeletePrograms);
- SET_GenProgramsNV(table, _mesa_GenPrograms);
- SET_IsProgramNV(table, _mesa_IsProgramARB);
- SET_GetVertexAttribdvNV(table, _mesa_GetVertexAttribdvNV);
- SET_GetVertexAttribfvNV(table, _mesa_GetVertexAttribfvNV);
- SET_GetVertexAttribivNV(table, _mesa_GetVertexAttribivNV);
- SET_GetVertexAttribPointervNV(table, _mesa_GetVertexAttribPointervNV);
- SET_ProgramEnvParameter4dARB(table, save_ProgramEnvParameter4dARB);
- SET_ProgramEnvParameter4dvARB(table, save_ProgramEnvParameter4dvARB);
- SET_ProgramEnvParameter4fARB(table, save_ProgramEnvParameter4fARB);
- SET_ProgramEnvParameter4fvARB(table, save_ProgramEnvParameter4fvARB);
- SET_ProgramLocalParameter4dARB(table, save_ProgramLocalParameter4dARB);
- SET_ProgramLocalParameter4dvARB(table, save_ProgramLocalParameter4dvARB);
- SET_ProgramLocalParameter4fARB(table, save_ProgramLocalParameter4fARB);
- SET_ProgramLocalParameter4fvARB(table, save_ProgramLocalParameter4fvARB);
- SET_GetProgramEnvParameterdvARB(table, _mesa_GetProgramEnvParameterdvARB);
- SET_GetProgramEnvParameterfvARB(table, _mesa_GetProgramEnvParameterfvARB);
- SET_GetProgramLocalParameterdvARB(table,
- _mesa_GetProgramLocalParameterdvARB);
- SET_GetProgramLocalParameterfvARB(table,
- _mesa_GetProgramLocalParameterfvARB);
- SET_GetProgramivARB(table, _mesa_GetProgramivARB);
- SET_GetProgramStringARB(table, _mesa_GetProgramStringARB);
-#endif
-
- /* ARB 28. GL_ARB_vertex_buffer_object */
-#if FEATURE_ARB_vertex_buffer_object
- /* None of the extension's functions get compiled */
- SET_BindBufferARB(table, _mesa_BindBufferARB);
- SET_BufferDataARB(table, _mesa_BufferDataARB);
- SET_BufferSubDataARB(table, _mesa_BufferSubDataARB);
- SET_DeleteBuffersARB(table, _mesa_DeleteBuffersARB);
- SET_GenBuffersARB(table, _mesa_GenBuffersARB);
- SET_GetBufferParameterivARB(table, _mesa_GetBufferParameterivARB);
- SET_GetBufferPointervARB(table, _mesa_GetBufferPointervARB);
- SET_GetBufferSubDataARB(table, _mesa_GetBufferSubDataARB);
- SET_IsBufferARB(table, _mesa_IsBufferARB);
- SET_MapBufferARB(table, _mesa_MapBufferARB);
- SET_UnmapBufferARB(table, _mesa_UnmapBufferARB);
-#endif
-
-#if FEATURE_queryobj
- SET_BeginQueryARB(table, save_BeginQueryARB);
- SET_EndQueryARB(table, save_EndQueryARB);
- SET_GenQueriesARB(table, _mesa_GenQueriesARB);
- SET_DeleteQueriesARB(table, _mesa_DeleteQueriesARB);
- SET_IsQueryARB(table, _mesa_IsQueryARB);
- SET_GetQueryivARB(table, _mesa_GetQueryivARB);
- SET_GetQueryObjectivARB(table, _mesa_GetQueryObjectivARB);
- SET_GetQueryObjectuivARB(table, _mesa_GetQueryObjectuivARB);
-#endif
- SET_DrawBuffersARB(table, save_DrawBuffersARB);
-
-#if FEATURE_EXT_framebuffer_blit
- SET_BlitFramebufferEXT(table, save_BlitFramebufferEXT);
-#endif
-
- /* GL_ARB_shader_objects */
- SET_UseProgramObjectARB(table, save_UseProgramObjectARB);
- SET_Uniform1fARB(table, save_Uniform1fARB);
- SET_Uniform2fARB(table, save_Uniform2fARB);
- SET_Uniform3fARB(table, save_Uniform3fARB);
- SET_Uniform4fARB(table, save_Uniform4fARB);
- SET_Uniform1fvARB(table, save_Uniform1fvARB);
- SET_Uniform2fvARB(table, save_Uniform2fvARB);
- SET_Uniform3fvARB(table, save_Uniform3fvARB);
- SET_Uniform4fvARB(table, save_Uniform4fvARB);
- SET_Uniform1iARB(table, save_Uniform1iARB);
- SET_Uniform2iARB(table, save_Uniform2iARB);
- SET_Uniform3iARB(table, save_Uniform3iARB);
- SET_Uniform4iARB(table, save_Uniform4iARB);
- SET_Uniform1ivARB(table, save_Uniform1ivARB);
- SET_Uniform2ivARB(table, save_Uniform2ivARB);
- SET_Uniform3ivARB(table, save_Uniform3ivARB);
- SET_Uniform4ivARB(table, save_Uniform4ivARB);
- SET_UniformMatrix2fvARB(table, save_UniformMatrix2fvARB);
- SET_UniformMatrix3fvARB(table, save_UniformMatrix3fvARB);
- SET_UniformMatrix4fvARB(table, save_UniformMatrix4fvARB);
- SET_UniformMatrix2x3fv(table, save_UniformMatrix2x3fv);
- SET_UniformMatrix3x2fv(table, save_UniformMatrix3x2fv);
- SET_UniformMatrix2x4fv(table, save_UniformMatrix2x4fv);
- SET_UniformMatrix4x2fv(table, save_UniformMatrix4x2fv);
- SET_UniformMatrix3x4fv(table, save_UniformMatrix3x4fv);
- SET_UniformMatrix4x3fv(table, save_UniformMatrix4x3fv);
-
- /* ARB 30/31/32. GL_ARB_shader_objects, GL_ARB_vertex/fragment_shader */
- SET_BindAttribLocationARB(table, exec_BindAttribLocationARB);
- SET_GetAttribLocationARB(table, exec_GetAttribLocationARB);
- SET_GetUniformLocationARB(table, exec_GetUniformLocationARB);
- /* XXX additional functions need to be implemented here! */
-
- /* 299. GL_EXT_blend_equation_separate */
- SET_BlendEquationSeparateEXT(table, save_BlendEquationSeparateEXT);
-
- /* GL_EXT_gpu_program_parameters */
-#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
- SET_ProgramEnvParameters4fvEXT(table, save_ProgramEnvParameters4fvEXT);
- SET_ProgramLocalParameters4fvEXT(table, save_ProgramLocalParameters4fvEXT);
-#endif
-
- /* ARB 50. GL_ARB_map_buffer_range */
-#if FEATURE_ARB_map_buffer_range
- SET_MapBufferRange(table, _mesa_MapBufferRange); /* no dlist save */
- SET_FlushMappedBufferRange(table, _mesa_FlushMappedBufferRange); /* no dl */
-#endif
-
- /* ARB 59. GL_ARB_copy_buffer */
- SET_CopyBufferSubData(table, _mesa_CopyBufferSubData); /* no dlist save */
-
- /* 352. GL_EXT_transform_feedback */
-#if FEATURE_EXT_transform_feedback
- SET_BeginTransformFeedbackEXT(table, save_BeginTransformFeedback);
- SET_EndTransformFeedbackEXT(table, save_EndTransformFeedback);
-#endif
-
- /* 364. GL_EXT_provoking_vertex */
- SET_ProvokingVertexEXT(table, save_ProvokingVertexEXT);
-
- /* 371. GL_APPLE_object_purgeable */
-#if FEATURE_APPLE_object_purgeable
- SET_ObjectPurgeableAPPLE(table, _mesa_ObjectPurgeableAPPLE);
- SET_ObjectUnpurgeableAPPLE(table, _mesa_ObjectUnpurgeableAPPLE);
-#endif
-
- /* GL_EXT_texture_integer */
- SET_ClearColorIiEXT(table, save_ClearColorIi);
- SET_ClearColorIuiEXT(table, save_ClearColorIui);
- SET_TexParameterIivEXT(table, save_TexParameterIiv);
- SET_TexParameterIuivEXT(table, save_TexParameterIuiv);
- SET_GetTexParameterIivEXT(table, exec_GetTexParameterIiv);
- SET_GetTexParameterIuivEXT(table, exec_GetTexParameterIuiv);
-
- /* 377. GL_EXT_separate_shader_objects */
- SET_UseShaderProgramEXT(table, save_UseShaderProgramEXT);
- SET_ActiveProgramEXT(table, save_ActiveProgramEXT);
-
- /* GL 3.0 */
-#if 0
- SET_ClearBufferiv(table, save_ClearBufferiv);
- SET_ClearBufferuiv(table, save_ClearBufferuiv);
- SET_ClearBufferfv(table, save_ClearBufferfv);
- SET_ClearBufferfi(table, save_ClearBufferfi);
- SET_Uniform1ui(table, save_Uniform1ui);
- SET_Uniform2ui(table, save_Uniform2ui);
- SET_Uniform3ui(table, save_Uniform3ui);
- SET_Uniform4ui(table, save_Uniform4ui);
- SET_Uniform1uiv(table, save_Uniform1uiv);
- SET_Uniform2uiv(table, save_Uniform2uiv);
- SET_Uniform3uiv(table, save_Uniform3uiv);
- SET_Uniform4uiv(table, save_Uniform4uiv);
-#else
- (void) save_ClearBufferiv;
- (void) save_ClearBufferuiv;
- (void) save_ClearBufferfv;
- (void) save_ClearBufferfi;
- (void) save_Uniform1ui;
- (void) save_Uniform2ui;
- (void) save_Uniform3ui;
- (void) save_Uniform4ui;
- (void) save_Uniform1uiv;
- (void) save_Uniform2uiv;
- (void) save_Uniform3uiv;
- (void) save_Uniform4uiv;
-#endif
-
- /* GL_ARB_instanced_arrays */
- SET_VertexAttribDivisorARB(table, save_VertexAttribDivisor);
-
- /* GL_ARB_draw_buffer_blend */
- SET_BlendFunciARB(table, save_BlendFunci);
- SET_BlendFuncSeparateiARB(table, save_BlendFuncSeparatei);
- SET_BlendEquationiARB(table, save_BlendEquationi);
- SET_BlendEquationSeparateiARB(table, save_BlendEquationSeparatei);
-
- return table;
-}
-
-
-
-static const char *
-enum_string(GLenum k)
-{
- return _mesa_lookup_enum_by_nr(k);
-}
-
-
-/**
- * Print the commands in a display list. For debugging only.
- * TODO: many commands aren't handled yet.
- */
-static void GLAPIENTRY
-print_list(struct gl_context *ctx, GLuint list)
-{
- struct gl_display_list *dlist;
- Node *n;
- GLboolean done;
-
- if (!islist(ctx, list)) {
- printf("%u is not a display list ID\n", list);
- return;
- }
-
- dlist = lookup_list(ctx, list);
- if (!dlist)
- return;
-
- n = dlist->Head;
-
- printf("START-LIST %u, address %p\n", list, (void *) n);
-
- done = n ? GL_FALSE : GL_TRUE;
- while (!done) {
- const OpCode opcode = n[0].opcode;
-
- if (is_ext_opcode(opcode)) {
- n += ext_opcode_print(ctx, n);
- }
- else {
- switch (opcode) {
- case OPCODE_ACCUM:
- printf("Accum %s %g\n", enum_string(n[1].e), n[2].f);
- break;
- case OPCODE_BITMAP:
- printf("Bitmap %d %d %g %g %g %g %p\n", n[1].i, n[2].i,
- n[3].f, n[4].f, n[5].f, n[6].f, (void *) n[7].data);
- break;
- case OPCODE_CALL_LIST:
- printf("CallList %d\n", (int) n[1].ui);
- break;
- case OPCODE_CALL_LIST_OFFSET:
- printf("CallList %d + offset %u = %u\n", (int) n[1].ui,
- ctx->List.ListBase, ctx->List.ListBase + n[1].ui);
- break;
- case OPCODE_COLOR_TABLE_PARAMETER_FV:
- printf("ColorTableParameterfv %s %s %f %f %f %f\n",
- enum_string(n[1].e), enum_string(n[2].e),
- n[3].f, n[4].f, n[5].f, n[6].f);
- break;
- case OPCODE_COLOR_TABLE_PARAMETER_IV:
- printf("ColorTableParameteriv %s %s %d %d %d %d\n",
- enum_string(n[1].e), enum_string(n[2].e),
- n[3].i, n[4].i, n[5].i, n[6].i);
- break;
- case OPCODE_DISABLE:
- printf("Disable %s\n", enum_string(n[1].e));
- break;
- case OPCODE_ENABLE:
- printf("Enable %s\n", enum_string(n[1].e));
- break;
- case OPCODE_FRUSTUM:
- printf("Frustum %g %g %g %g %g %g\n",
- n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f);
- break;
- case OPCODE_LINE_STIPPLE:
- printf("LineStipple %d %x\n", n[1].i, (int) n[2].us);
- break;
- case OPCODE_LOAD_IDENTITY:
- printf("LoadIdentity\n");
- break;
- case OPCODE_LOAD_MATRIX:
- printf("LoadMatrix\n");
- printf(" %8f %8f %8f %8f\n",
- n[1].f, n[5].f, n[9].f, n[13].f);
- printf(" %8f %8f %8f %8f\n",
- n[2].f, n[6].f, n[10].f, n[14].f);
- printf(" %8f %8f %8f %8f\n",
- n[3].f, n[7].f, n[11].f, n[15].f);
- printf(" %8f %8f %8f %8f\n",
- n[4].f, n[8].f, n[12].f, n[16].f);
- break;
- case OPCODE_MULT_MATRIX:
- printf("MultMatrix (or Rotate)\n");
- printf(" %8f %8f %8f %8f\n",
- n[1].f, n[5].f, n[9].f, n[13].f);
- printf(" %8f %8f %8f %8f\n",
- n[2].f, n[6].f, n[10].f, n[14].f);
- printf(" %8f %8f %8f %8f\n",
- n[3].f, n[7].f, n[11].f, n[15].f);
- printf(" %8f %8f %8f %8f\n",
- n[4].f, n[8].f, n[12].f, n[16].f);
- break;
- case OPCODE_ORTHO:
- printf("Ortho %g %g %g %g %g %g\n",
- n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f);
- break;
- case OPCODE_POP_ATTRIB:
- printf("PopAttrib\n");
- break;
- case OPCODE_POP_MATRIX:
- printf("PopMatrix\n");
- break;
- case OPCODE_POP_NAME:
- printf("PopName\n");
- break;
- case OPCODE_PUSH_ATTRIB:
- printf("PushAttrib %x\n", n[1].bf);
- break;
- case OPCODE_PUSH_MATRIX:
- printf("PushMatrix\n");
- break;
- case OPCODE_PUSH_NAME:
- printf("PushName %d\n", (int) n[1].ui);
- break;
- case OPCODE_RASTER_POS:
- printf("RasterPos %g %g %g %g\n",
- n[1].f, n[2].f, n[3].f, n[4].f);
- break;
- case OPCODE_ROTATE:
- printf("Rotate %g %g %g %g\n",
- n[1].f, n[2].f, n[3].f, n[4].f);
- break;
- case OPCODE_SCALE:
- printf("Scale %g %g %g\n", n[1].f, n[2].f, n[3].f);
- break;
- case OPCODE_TRANSLATE:
- printf("Translate %g %g %g\n", n[1].f, n[2].f, n[3].f);
- break;
- case OPCODE_BIND_TEXTURE:
- printf("BindTexture %s %d\n",
- _mesa_lookup_enum_by_nr(n[1].ui), n[2].ui);
- break;
- case OPCODE_SHADE_MODEL:
- printf("ShadeModel %s\n", _mesa_lookup_enum_by_nr(n[1].ui));
- break;
- case OPCODE_MAP1:
- printf("Map1 %s %.3f %.3f %d %d\n",
- _mesa_lookup_enum_by_nr(n[1].ui),
- n[2].f, n[3].f, n[4].i, n[5].i);
- break;
- case OPCODE_MAP2:
- printf("Map2 %s %.3f %.3f %.3f %.3f %d %d %d %d\n",
- _mesa_lookup_enum_by_nr(n[1].ui),
- n[2].f, n[3].f, n[4].f, n[5].f,
- n[6].i, n[7].i, n[8].i, n[9].i);
- break;
- case OPCODE_MAPGRID1:
- printf("MapGrid1 %d %.3f %.3f\n", n[1].i, n[2].f, n[3].f);
- break;
- case OPCODE_MAPGRID2:
- printf("MapGrid2 %d %.3f %.3f, %d %.3f %.3f\n",
- n[1].i, n[2].f, n[3].f, n[4].i, n[5].f, n[6].f);
- break;
- case OPCODE_EVALMESH1:
- printf("EvalMesh1 %d %d\n", n[1].i, n[2].i);
- break;
- case OPCODE_EVALMESH2:
- printf("EvalMesh2 %d %d %d %d\n",
- n[1].i, n[2].i, n[3].i, n[4].i);
- break;
-
- case OPCODE_ATTR_1F_NV:
- printf("ATTR_1F_NV attr %d: %f\n", n[1].i, n[2].f);
- break;
- case OPCODE_ATTR_2F_NV:
- printf("ATTR_2F_NV attr %d: %f %f\n",
- n[1].i, n[2].f, n[3].f);
- break;
- case OPCODE_ATTR_3F_NV:
- printf("ATTR_3F_NV attr %d: %f %f %f\n",
- n[1].i, n[2].f, n[3].f, n[4].f);
- break;
- case OPCODE_ATTR_4F_NV:
- printf("ATTR_4F_NV attr %d: %f %f %f %f\n",
- n[1].i, n[2].f, n[3].f, n[4].f, n[5].f);
- break;
- case OPCODE_ATTR_1F_ARB:
- printf("ATTR_1F_ARB attr %d: %f\n", n[1].i, n[2].f);
- break;
- case OPCODE_ATTR_2F_ARB:
- printf("ATTR_2F_ARB attr %d: %f %f\n",
- n[1].i, n[2].f, n[3].f);
- break;
- case OPCODE_ATTR_3F_ARB:
- printf("ATTR_3F_ARB attr %d: %f %f %f\n",
- n[1].i, n[2].f, n[3].f, n[4].f);
- break;
- case OPCODE_ATTR_4F_ARB:
- printf("ATTR_4F_ARB attr %d: %f %f %f %f\n",
- n[1].i, n[2].f, n[3].f, n[4].f, n[5].f);
- break;
-
- case OPCODE_MATERIAL:
- printf("MATERIAL %x %x: %f %f %f %f\n",
- n[1].i, n[2].i, n[3].f, n[4].f, n[5].f, n[6].f);
- break;
- case OPCODE_BEGIN:
- printf("BEGIN %x\n", n[1].i);
- break;
- case OPCODE_END:
- printf("END\n");
- break;
- case OPCODE_RECTF:
- printf("RECTF %f %f %f %f\n", n[1].f, n[2].f, n[3].f,
- n[4].f);
- break;
- case OPCODE_EVAL_C1:
- printf("EVAL_C1 %f\n", n[1].f);
- break;
- case OPCODE_EVAL_C2:
- printf("EVAL_C2 %f %f\n", n[1].f, n[2].f);
- break;
- case OPCODE_EVAL_P1:
- printf("EVAL_P1 %d\n", n[1].i);
- break;
- case OPCODE_EVAL_P2:
- printf("EVAL_P2 %d %d\n", n[1].i, n[2].i);
- break;
-
- case OPCODE_PROVOKING_VERTEX:
- printf("ProvokingVertex %s\n",
- _mesa_lookup_enum_by_nr(n[1].ui));
- break;
-
- /*
- * meta opcodes/commands
- */
- case OPCODE_ERROR:
- printf("Error: %s %s\n",
- enum_string(n[1].e), (const char *) n[2].data);
- break;
- case OPCODE_CONTINUE:
- printf("DISPLAY-LIST-CONTINUE\n");
- n = (Node *) n[1].next;
- break;
- case OPCODE_END_OF_LIST:
- printf("END-LIST %u\n", list);
- done = GL_TRUE;
- break;
- default:
- if (opcode < 0 || opcode > OPCODE_END_OF_LIST) {
- printf
- ("ERROR IN DISPLAY LIST: opcode = %d, address = %p\n",
- opcode, (void *) n);
- return;
- }
- else {
- printf("command %d, %u operands\n", opcode,
- InstSize[opcode]);
- }
- }
- /* increment n to point to next compiled command */
- if (opcode != OPCODE_CONTINUE) {
- n += InstSize[opcode];
- }
- }
- }
-}
-
-
-
-/**
- * Clients may call this function to help debug display list problems.
- * This function is _ONLY_FOR_DEBUGGING_PURPOSES_. It may be removed,
- * changed, or break in the future without notice.
- */
-void
-mesa_print_display_list(GLuint list)
-{
- GET_CURRENT_CONTEXT(ctx);
- print_list(ctx, list);
-}
-
-
-/**********************************************************************/
-/***** Initialization *****/
-/**********************************************************************/
-
-void
-_mesa_save_vtxfmt_init(GLvertexformat * vfmt)
-{
- _MESA_INIT_ARRAYELT_VTXFMT(vfmt, _ae_);
-
- vfmt->Begin = save_Begin;
-
- _MESA_INIT_DLIST_VTXFMT(vfmt, save_);
-
- vfmt->Color3f = save_Color3f;
- vfmt->Color3fv = save_Color3fv;
- vfmt->Color4f = save_Color4f;
- vfmt->Color4fv = save_Color4fv;
- vfmt->EdgeFlag = save_EdgeFlag;
- vfmt->End = save_End;
-
- _MESA_INIT_EVAL_VTXFMT(vfmt, save_);
-
- vfmt->FogCoordfEXT = save_FogCoordfEXT;
- vfmt->FogCoordfvEXT = save_FogCoordfvEXT;
- vfmt->Indexf = save_Indexf;
- vfmt->Indexfv = save_Indexfv;
- vfmt->Materialfv = save_Materialfv;
- vfmt->MultiTexCoord1fARB = save_MultiTexCoord1f;
- vfmt->MultiTexCoord1fvARB = save_MultiTexCoord1fv;
- vfmt->MultiTexCoord2fARB = save_MultiTexCoord2f;
- vfmt->MultiTexCoord2fvARB = save_MultiTexCoord2fv;
- vfmt->MultiTexCoord3fARB = save_MultiTexCoord3f;
- vfmt->MultiTexCoord3fvARB = save_MultiTexCoord3fv;
- vfmt->MultiTexCoord4fARB = save_MultiTexCoord4f;
- vfmt->MultiTexCoord4fvARB = save_MultiTexCoord4fv;
- vfmt->Normal3f = save_Normal3f;
- vfmt->Normal3fv = save_Normal3fv;
- vfmt->SecondaryColor3fEXT = save_SecondaryColor3fEXT;
- vfmt->SecondaryColor3fvEXT = save_SecondaryColor3fvEXT;
- vfmt->TexCoord1f = save_TexCoord1f;
- vfmt->TexCoord1fv = save_TexCoord1fv;
- vfmt->TexCoord2f = save_TexCoord2f;
- vfmt->TexCoord2fv = save_TexCoord2fv;
- vfmt->TexCoord3f = save_TexCoord3f;
- vfmt->TexCoord3fv = save_TexCoord3fv;
- vfmt->TexCoord4f = save_TexCoord4f;
- vfmt->TexCoord4fv = save_TexCoord4fv;
- vfmt->Vertex2f = save_Vertex2f;
- vfmt->Vertex2fv = save_Vertex2fv;
- vfmt->Vertex3f = save_Vertex3f;
- vfmt->Vertex3fv = save_Vertex3fv;
- vfmt->Vertex4f = save_Vertex4f;
- vfmt->Vertex4fv = save_Vertex4fv;
- vfmt->VertexAttrib1fNV = save_VertexAttrib1fNV;
- vfmt->VertexAttrib1fvNV = save_VertexAttrib1fvNV;
- vfmt->VertexAttrib2fNV = save_VertexAttrib2fNV;
- vfmt->VertexAttrib2fvNV = save_VertexAttrib2fvNV;
- vfmt->VertexAttrib3fNV = save_VertexAttrib3fNV;
- vfmt->VertexAttrib3fvNV = save_VertexAttrib3fvNV;
- vfmt->VertexAttrib4fNV = save_VertexAttrib4fNV;
- vfmt->VertexAttrib4fvNV = save_VertexAttrib4fvNV;
- vfmt->VertexAttrib1fARB = save_VertexAttrib1fARB;
- vfmt->VertexAttrib1fvARB = save_VertexAttrib1fvARB;
- vfmt->VertexAttrib2fARB = save_VertexAttrib2fARB;
- vfmt->VertexAttrib2fvARB = save_VertexAttrib2fvARB;
- vfmt->VertexAttrib3fARB = save_VertexAttrib3fARB;
- vfmt->VertexAttrib3fvARB = save_VertexAttrib3fvARB;
- vfmt->VertexAttrib4fARB = save_VertexAttrib4fARB;
- vfmt->VertexAttrib4fvARB = save_VertexAttrib4fvARB;
-
- vfmt->Rectf = save_Rectf;
-
- /* The driver is required to implement these as
- * 1) They can probably do a better job.
- * 2) A lot of new mechanisms would have to be added to this module
- * to support it. That code would probably never get used,
- * because of (1).
- */
-#if 0
- vfmt->DrawArrays = 0;
- vfmt->DrawElements = 0;
- vfmt->DrawRangeElements = 0;
- vfmt->MultiDrawElemementsEXT = 0;
- vfmt->DrawElementsBaseVertex = 0;
- vfmt->DrawRangeElementsBaseVertex = 0;
- vfmt->MultiDrawElemementsBaseVertex = 0;
-#endif
-}
-
-
-void
-_mesa_install_dlist_vtxfmt(struct _glapi_table *disp,
- const GLvertexformat *vfmt)
-{
- SET_CallList(disp, vfmt->CallList);
- SET_CallLists(disp, vfmt->CallLists);
-}
-
-
-void _mesa_init_dlist_dispatch(struct _glapi_table *disp)
-{
- SET_CallList(disp, _mesa_CallList);
- SET_CallLists(disp, _mesa_CallLists);
-
- SET_DeleteLists(disp, _mesa_DeleteLists);
- SET_EndList(disp, _mesa_EndList);
- SET_GenLists(disp, _mesa_GenLists);
- SET_IsList(disp, _mesa_IsList);
- SET_ListBase(disp, _mesa_ListBase);
- SET_NewList(disp, _mesa_NewList);
-}
-
-
-#endif /* FEATURE_dlist */
-
-
-/**
- * Initialize display list state for given context.
- */
-void
-_mesa_init_display_list(struct gl_context *ctx)
-{
- static GLboolean tableInitialized = GL_FALSE;
-
- /* zero-out the instruction size table, just once */
- if (!tableInitialized) {
- memset(InstSize, 0, sizeof(InstSize));
- tableInitialized = GL_TRUE;
- }
-
- /* extension info */
- ctx->ListExt = CALLOC_STRUCT(gl_list_extensions);
-
- /* Display list */
- ctx->ListState.CallDepth = 0;
- ctx->ExecuteFlag = GL_TRUE;
- ctx->CompileFlag = GL_FALSE;
- ctx->ListState.CurrentBlock = NULL;
- ctx->ListState.CurrentPos = 0;
-
- /* Display List group */
- ctx->List.ListBase = 0;
-
-#if FEATURE_dlist
- _mesa_save_vtxfmt_init(&ctx->ListState.ListVtxfmt);
-#endif
-}
-
-
-void
-_mesa_free_display_list_data(struct gl_context *ctx)
-{
- free(ctx->ListExt);
- ctx->ListExt = NULL;
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.7
+ *
+ * Copyright (C) 1999-2008 Brian Paul All Rights Reserved.
+ * Copyright (C) 2009 VMware, Inc. 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 dlist.c
+ * Display lists management functions.
+ */
+
+#include "glheader.h"
+#include "imports.h"
+#include "api_arrayelt.h"
+#include "api_exec.h"
+#include "api_loopback.h"
+#if FEATURE_ATI_fragment_shader
+#include "atifragshader.h"
+#endif
+#include "config.h"
+#include "mfeatures.h"
+#if FEATURE_ARB_vertex_buffer_object
+#include "bufferobj.h"
+#endif
+#include "arrayobj.h"
+#include "context.h"
+#include "dlist.h"
+#include "enums.h"
+#include "eval.h"
+#include "framebuffer.h"
+#include "glapi/glapi.h"
+#include "hash.h"
+#include "image.h"
+#include "light.h"
+#include "macros.h"
+#include "pack.h"
+#include "queryobj.h"
+#include "teximage.h"
+#include "mtypes.h"
+#include "varray.h"
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+#include "arbprogram.h"
+#endif
+#if FEATURE_NV_vertex_program || FEATURE_NV_fragment_program
+#include "nvprogram.h"
+#endif
+
+#include "math/m_matrix.h"
+
+#include "main/dispatch.h"
+
+
+
+/**
+ * Other parts of Mesa (such as the VBO module) can plug into the display
+ * list system. This structure describes new display list instructions.
+ */
+struct gl_list_instruction
+{
+ GLuint Size;
+ void (*Execute)( struct gl_context *ctx, void *data );
+ void (*Destroy)( struct gl_context *ctx, void *data );
+ void (*Print)( struct gl_context *ctx, void *data );
+};
+
+
+#define MAX_DLIST_EXT_OPCODES 16
+
+/**
+ * Used by device drivers to hook new commands into display lists.
+ */
+struct gl_list_extensions
+{
+ struct gl_list_instruction Opcode[MAX_DLIST_EXT_OPCODES];
+ GLuint NumOpcodes;
+};
+
+
+
+/**
+ * Flush vertices.
+ *
+ * \param ctx GL context.
+ *
+ * Checks if dd_function_table::SaveNeedFlush is marked to flush
+ * stored (save) vertices, and calls
+ * dd_function_table::SaveFlushVertices if so.
+ */
+#define SAVE_FLUSH_VERTICES(ctx) \
+do { \
+ if (ctx->Driver.SaveNeedFlush) \
+ ctx->Driver.SaveFlushVertices(ctx); \
+} while (0)
+
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair, with return value.
+ *
+ * \param ctx GL context.
+ * \param retval value to return value in case the assertion fails.
+ */
+#define ASSERT_OUTSIDE_SAVE_BEGIN_END_WITH_RETVAL(ctx, retval) \
+do { \
+ if (ctx->Driver.CurrentSavePrimitive <= GL_POLYGON || \
+ ctx->Driver.CurrentSavePrimitive == PRIM_INSIDE_UNKNOWN_PRIM) { \
+ _mesa_compile_error( ctx, GL_INVALID_OPERATION, "begin/end" ); \
+ return retval; \
+ } \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair.
+ *
+ * \param ctx GL context.
+ */
+#define ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx) \
+do { \
+ if (ctx->Driver.CurrentSavePrimitive <= GL_POLYGON || \
+ ctx->Driver.CurrentSavePrimitive == PRIM_INSIDE_UNKNOWN_PRIM) { \
+ _mesa_compile_error( ctx, GL_INVALID_OPERATION, "begin/end" ); \
+ return; \
+ } \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair and flush the vertices.
+ *
+ * \param ctx GL context.
+ */
+#define ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx) \
+do { \
+ ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx); \
+ SAVE_FLUSH_VERTICES(ctx); \
+} while (0)
+
+/**
+ * Macro to assert that the API call was made outside the
+ * glBegin()/glEnd() pair and flush the vertices, with return value.
+ *
+ * \param ctx GL context.
+ * \param retval value to return value in case the assertion fails.
+ */
+#define ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH_WITH_RETVAL(ctx, retval)\
+do { \
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_WITH_RETVAL(ctx, retval); \
+ SAVE_FLUSH_VERTICES(ctx); \
+} while (0)
+
+
+
+/**
+ * Display list opcodes.
+ *
+ * The fact that these identifiers are assigned consecutive
+ * integer values starting at 0 is very important, see InstSize array usage)
+ */
+typedef enum
+{
+ OPCODE_INVALID = -1, /* Force signed enum */
+ OPCODE_ACCUM,
+ OPCODE_ALPHA_FUNC,
+ OPCODE_BIND_TEXTURE,
+ OPCODE_BITMAP,
+ OPCODE_BLEND_COLOR,
+ OPCODE_BLEND_EQUATION,
+ OPCODE_BLEND_EQUATION_SEPARATE,
+ OPCODE_BLEND_FUNC_SEPARATE,
+
+ OPCODE_BLEND_EQUATION_I,
+ OPCODE_BLEND_EQUATION_SEPARATE_I,
+ OPCODE_BLEND_FUNC_I,
+ OPCODE_BLEND_FUNC_SEPARATE_I,
+
+ OPCODE_CALL_LIST,
+ OPCODE_CALL_LIST_OFFSET,
+ OPCODE_CLEAR,
+ OPCODE_CLEAR_ACCUM,
+ OPCODE_CLEAR_COLOR,
+ OPCODE_CLEAR_DEPTH,
+ OPCODE_CLEAR_INDEX,
+ OPCODE_CLEAR_STENCIL,
+ OPCODE_CLEAR_BUFFER_IV,
+ OPCODE_CLEAR_BUFFER_UIV,
+ OPCODE_CLEAR_BUFFER_FV,
+ OPCODE_CLEAR_BUFFER_FI,
+ OPCODE_CLIP_PLANE,
+ OPCODE_COLOR_MASK,
+ OPCODE_COLOR_MASK_INDEXED,
+ OPCODE_COLOR_MATERIAL,
+ OPCODE_COLOR_TABLE,
+ OPCODE_COLOR_TABLE_PARAMETER_FV,
+ OPCODE_COLOR_TABLE_PARAMETER_IV,
+ OPCODE_COLOR_SUB_TABLE,
+ OPCODE_CONVOLUTION_FILTER_1D,
+ OPCODE_CONVOLUTION_FILTER_2D,
+ OPCODE_CONVOLUTION_PARAMETER_I,
+ OPCODE_CONVOLUTION_PARAMETER_IV,
+ OPCODE_CONVOLUTION_PARAMETER_F,
+ OPCODE_CONVOLUTION_PARAMETER_FV,
+ OPCODE_COPY_COLOR_SUB_TABLE,
+ OPCODE_COPY_COLOR_TABLE,
+ OPCODE_COPY_PIXELS,
+ OPCODE_COPY_TEX_IMAGE1D,
+ OPCODE_COPY_TEX_IMAGE2D,
+ OPCODE_COPY_TEX_SUB_IMAGE1D,
+ OPCODE_COPY_TEX_SUB_IMAGE2D,
+ OPCODE_COPY_TEX_SUB_IMAGE3D,
+ OPCODE_CULL_FACE,
+ OPCODE_DEPTH_FUNC,
+ OPCODE_DEPTH_MASK,
+ OPCODE_DEPTH_RANGE,
+ OPCODE_DISABLE,
+ OPCODE_DISABLE_INDEXED,
+ OPCODE_DRAW_BUFFER,
+ OPCODE_DRAW_PIXELS,
+ OPCODE_ENABLE,
+ OPCODE_ENABLE_INDEXED,
+ OPCODE_EVALMESH1,
+ OPCODE_EVALMESH2,
+ OPCODE_FOG,
+ OPCODE_FRONT_FACE,
+ OPCODE_FRUSTUM,
+ OPCODE_HINT,
+ OPCODE_HISTOGRAM,
+ OPCODE_INDEX_MASK,
+ OPCODE_INIT_NAMES,
+ OPCODE_LIGHT,
+ OPCODE_LIGHT_MODEL,
+ OPCODE_LINE_STIPPLE,
+ OPCODE_LINE_WIDTH,
+ OPCODE_LIST_BASE,
+ OPCODE_LOAD_IDENTITY,
+ OPCODE_LOAD_MATRIX,
+ OPCODE_LOAD_NAME,
+ OPCODE_LOGIC_OP,
+ OPCODE_MAP1,
+ OPCODE_MAP2,
+ OPCODE_MAPGRID1,
+ OPCODE_MAPGRID2,
+ OPCODE_MATRIX_MODE,
+ OPCODE_MIN_MAX,
+ OPCODE_MULT_MATRIX,
+ OPCODE_ORTHO,
+ OPCODE_PASSTHROUGH,
+ OPCODE_PIXEL_MAP,
+ OPCODE_PIXEL_TRANSFER,
+ OPCODE_PIXEL_ZOOM,
+ OPCODE_POINT_SIZE,
+ OPCODE_POINT_PARAMETERS,
+ OPCODE_POLYGON_MODE,
+ OPCODE_POLYGON_STIPPLE,
+ OPCODE_POLYGON_OFFSET,
+ OPCODE_POP_ATTRIB,
+ OPCODE_POP_MATRIX,
+ OPCODE_POP_NAME,
+ OPCODE_PRIORITIZE_TEXTURE,
+ OPCODE_PUSH_ATTRIB,
+ OPCODE_PUSH_MATRIX,
+ OPCODE_PUSH_NAME,
+ OPCODE_RASTER_POS,
+ OPCODE_READ_BUFFER,
+ OPCODE_RESET_HISTOGRAM,
+ OPCODE_RESET_MIN_MAX,
+ OPCODE_ROTATE,
+ OPCODE_SCALE,
+ OPCODE_SCISSOR,
+ OPCODE_SELECT_TEXTURE_SGIS,
+ OPCODE_SELECT_TEXTURE_COORD_SET,
+ OPCODE_SHADE_MODEL,
+ OPCODE_STENCIL_FUNC,
+ OPCODE_STENCIL_MASK,
+ OPCODE_STENCIL_OP,
+ OPCODE_TEXENV,
+ OPCODE_TEXGEN,
+ OPCODE_TEXPARAMETER,
+ OPCODE_TEX_IMAGE1D,
+ OPCODE_TEX_IMAGE2D,
+ OPCODE_TEX_IMAGE3D,
+ OPCODE_TEX_SUB_IMAGE1D,
+ OPCODE_TEX_SUB_IMAGE2D,
+ OPCODE_TEX_SUB_IMAGE3D,
+ OPCODE_TRANSLATE,
+ OPCODE_VIEWPORT,
+ OPCODE_WINDOW_POS,
+ /* GL_ARB_multitexture */
+ OPCODE_ACTIVE_TEXTURE,
+ /* GL_ARB_texture_compression */
+ OPCODE_COMPRESSED_TEX_IMAGE_1D,
+ OPCODE_COMPRESSED_TEX_IMAGE_2D,
+ OPCODE_COMPRESSED_TEX_IMAGE_3D,
+ OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D,
+ OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D,
+ OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D,
+ /* GL_ARB_multisample */
+ OPCODE_SAMPLE_COVERAGE,
+ /* GL_ARB_window_pos */
+ OPCODE_WINDOW_POS_ARB,
+ /* GL_NV_vertex_program */
+ OPCODE_BIND_PROGRAM_NV,
+ OPCODE_EXECUTE_PROGRAM_NV,
+ OPCODE_REQUEST_RESIDENT_PROGRAMS_NV,
+ OPCODE_LOAD_PROGRAM_NV,
+ OPCODE_TRACK_MATRIX_NV,
+ /* GL_NV_fragment_program */
+ OPCODE_PROGRAM_LOCAL_PARAMETER_ARB,
+ OPCODE_PROGRAM_NAMED_PARAMETER_NV,
+ /* GL_EXT_stencil_two_side */
+ OPCODE_ACTIVE_STENCIL_FACE_EXT,
+ /* GL_EXT_depth_bounds_test */
+ OPCODE_DEPTH_BOUNDS_EXT,
+ /* GL_ARB_vertex/fragment_program */
+ OPCODE_PROGRAM_STRING_ARB,
+ OPCODE_PROGRAM_ENV_PARAMETER_ARB,
+ /* GL_ARB_occlusion_query */
+ OPCODE_BEGIN_QUERY_ARB,
+ OPCODE_END_QUERY_ARB,
+ /* GL_ARB_draw_buffers */
+ OPCODE_DRAW_BUFFERS_ARB,
+ /* GL_ATI_fragment_shader */
+ OPCODE_TEX_BUMP_PARAMETER_ATI,
+ /* GL_ATI_fragment_shader */
+ OPCODE_BIND_FRAGMENT_SHADER_ATI,
+ OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI,
+ /* OpenGL 2.0 */
+ OPCODE_STENCIL_FUNC_SEPARATE,
+ OPCODE_STENCIL_OP_SEPARATE,
+ OPCODE_STENCIL_MASK_SEPARATE,
+
+ /* GL_ARB_shader_objects */
+ OPCODE_USE_PROGRAM,
+ OPCODE_UNIFORM_1F,
+ OPCODE_UNIFORM_2F,
+ OPCODE_UNIFORM_3F,
+ OPCODE_UNIFORM_4F,
+ OPCODE_UNIFORM_1FV,
+ OPCODE_UNIFORM_2FV,
+ OPCODE_UNIFORM_3FV,
+ OPCODE_UNIFORM_4FV,
+ OPCODE_UNIFORM_1I,
+ OPCODE_UNIFORM_2I,
+ OPCODE_UNIFORM_3I,
+ OPCODE_UNIFORM_4I,
+ OPCODE_UNIFORM_1IV,
+ OPCODE_UNIFORM_2IV,
+ OPCODE_UNIFORM_3IV,
+ OPCODE_UNIFORM_4IV,
+ OPCODE_UNIFORM_MATRIX22,
+ OPCODE_UNIFORM_MATRIX33,
+ OPCODE_UNIFORM_MATRIX44,
+ OPCODE_UNIFORM_MATRIX23,
+ OPCODE_UNIFORM_MATRIX32,
+ OPCODE_UNIFORM_MATRIX24,
+ OPCODE_UNIFORM_MATRIX42,
+ OPCODE_UNIFORM_MATRIX34,
+ OPCODE_UNIFORM_MATRIX43,
+
+ /* OpenGL 3.0 */
+ OPCODE_UNIFORM_1UI,
+ OPCODE_UNIFORM_2UI,
+ OPCODE_UNIFORM_3UI,
+ OPCODE_UNIFORM_4UI,
+ OPCODE_UNIFORM_1UIV,
+ OPCODE_UNIFORM_2UIV,
+ OPCODE_UNIFORM_3UIV,
+ OPCODE_UNIFORM_4UIV,
+
+ /* GL_EXT_framebuffer_blit */
+ OPCODE_BLIT_FRAMEBUFFER,
+
+ /* Vertex attributes -- fallback for when optimized display
+ * list build isn't active.
+ */
+ OPCODE_ATTR_1F_NV,
+ OPCODE_ATTR_2F_NV,
+ OPCODE_ATTR_3F_NV,
+ OPCODE_ATTR_4F_NV,
+ OPCODE_ATTR_1F_ARB,
+ OPCODE_ATTR_2F_ARB,
+ OPCODE_ATTR_3F_ARB,
+ OPCODE_ATTR_4F_ARB,
+ OPCODE_MATERIAL,
+ OPCODE_BEGIN,
+ OPCODE_END,
+ OPCODE_RECTF,
+ OPCODE_EVAL_C1,
+ OPCODE_EVAL_C2,
+ OPCODE_EVAL_P1,
+ OPCODE_EVAL_P2,
+
+ /* GL_EXT_provoking_vertex */
+ OPCODE_PROVOKING_VERTEX,
+
+ /* GL_EXT_transform_feedback */
+ OPCODE_BEGIN_TRANSFORM_FEEDBACK,
+ OPCODE_END_TRANSFORM_FEEDBACK,
+
+ /* GL_EXT_texture_integer */
+ OPCODE_CLEARCOLOR_I,
+ OPCODE_CLEARCOLOR_UI,
+ OPCODE_TEXPARAMETER_I,
+ OPCODE_TEXPARAMETER_UI,
+
+ /* GL_EXT_separate_shader_objects */
+ OPCODE_ACTIVE_PROGRAM_EXT,
+ OPCODE_USE_SHADER_PROGRAM_EXT,
+
+ /* GL_ARB_instanced_arrays */
+ OPCODE_VERTEX_ATTRIB_DIVISOR,
+
+ /* The following three are meta instructions */
+ OPCODE_ERROR, /* raise compiled-in error */
+ OPCODE_CONTINUE,
+ OPCODE_END_OF_LIST,
+ OPCODE_EXT_0
+} OpCode;
+
+
+
+/**
+ * Display list node.
+ *
+ * Display list instructions are stored as sequences of "nodes". Nodes
+ * are allocated in blocks. Each block has BLOCK_SIZE nodes. Blocks
+ * are linked together with a pointer.
+ *
+ * Each instruction in the display list is stored as a sequence of
+ * contiguous nodes in memory.
+ * Each node is the union of a variety of data types.
+ */
+union gl_dlist_node
+{
+ OpCode opcode;
+ GLboolean b;
+ GLbitfield bf;
+ GLubyte ub;
+ GLshort s;
+ GLushort us;
+ GLint i;
+ GLuint ui;
+ GLenum e;
+ GLfloat f;
+ GLvoid *data;
+ void *next; /* If prev node's opcode==OPCODE_CONTINUE */
+};
+
+
+typedef union gl_dlist_node Node;
+
+
+/**
+ * How many nodes to allocate at a time.
+ *
+ * \note Reduced now that we hold vertices etc. elsewhere.
+ */
+#define BLOCK_SIZE 256
+
+
+
+/**
+ * Number of nodes of storage needed for each instruction.
+ * Sizes for dynamically allocated opcodes are stored in the context struct.
+ */
+static GLuint InstSize[OPCODE_END_OF_LIST + 1];
+
+
+#if FEATURE_dlist
+
+
+void mesa_print_display_list(GLuint list);
+
+
+/**********************************************************************/
+/***** Private *****/
+/**********************************************************************/
+
+
+/**
+ * Make an empty display list. This is used by glGenLists() to
+ * reserve display list IDs.
+ */
+static struct gl_display_list *
+make_list(GLuint name, GLuint count)
+{
+ struct gl_display_list *dlist = CALLOC_STRUCT(gl_display_list);
+ dlist->Name = name;
+ dlist->Head = (Node *) malloc(sizeof(Node) * count);
+ dlist->Head[0].opcode = OPCODE_END_OF_LIST;
+ return dlist;
+}
+
+
+/**
+ * Lookup function to just encapsulate casting.
+ */
+static INLINE struct gl_display_list *
+lookup_list(struct gl_context *ctx, GLuint list)
+{
+ return (struct gl_display_list *)
+ _mesa_HashLookup(ctx->Shared->DisplayList, list);
+}
+
+
+/** Is the given opcode an extension code? */
+static INLINE GLboolean
+is_ext_opcode(OpCode opcode)
+{
+ return (opcode >= OPCODE_EXT_0);
+}
+
+
+/** Destroy an extended opcode instruction */
+static GLint
+ext_opcode_destroy(struct gl_context *ctx, Node *node)
+{
+ const GLint i = node[0].opcode - OPCODE_EXT_0;
+ GLint step;
+ ctx->ListExt->Opcode[i].Destroy(ctx, &node[1]);
+ step = ctx->ListExt->Opcode[i].Size;
+ return step;
+}
+
+
+/** Execute an extended opcode instruction */
+static GLint
+ext_opcode_execute(struct gl_context *ctx, Node *node)
+{
+ const GLint i = node[0].opcode - OPCODE_EXT_0;
+ GLint step;
+ ctx->ListExt->Opcode[i].Execute(ctx, &node[1]);
+ step = ctx->ListExt->Opcode[i].Size;
+ return step;
+}
+
+
+/** Print an extended opcode instruction */
+static GLint
+ext_opcode_print(struct gl_context *ctx, Node *node)
+{
+ const GLint i = node[0].opcode - OPCODE_EXT_0;
+ GLint step;
+ ctx->ListExt->Opcode[i].Print(ctx, &node[1]);
+ step = ctx->ListExt->Opcode[i].Size;
+ return step;
+}
+
+
+/**
+ * Delete the named display list, but don't remove from hash table.
+ * \param dlist - display list pointer
+ */
+void
+_mesa_delete_list(struct gl_context *ctx, struct gl_display_list *dlist)
+{
+ Node *n, *block;
+ GLboolean done;
+
+ n = block = dlist->Head;
+
+ done = block ? GL_FALSE : GL_TRUE;
+ while (!done) {
+ const OpCode opcode = n[0].opcode;
+
+ /* check for extension opcodes first */
+ if (is_ext_opcode(opcode)) {
+ n += ext_opcode_destroy(ctx, n);
+ }
+ else {
+ switch (opcode) {
+ /* for some commands, we need to free malloc'd memory */
+ case OPCODE_MAP1:
+ free(n[6].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_MAP2:
+ free(n[10].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_DRAW_PIXELS:
+ free(n[5].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_BITMAP:
+ free(n[7].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COLOR_TABLE:
+ free(n[6].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COLOR_SUB_TABLE:
+ free(n[6].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_CONVOLUTION_FILTER_1D:
+ free(n[6].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_CONVOLUTION_FILTER_2D:
+ free(n[7].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_POLYGON_STIPPLE:
+ free(n[1].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_IMAGE1D:
+ free(n[8].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_IMAGE2D:
+ free(n[9].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_IMAGE3D:
+ free(n[10].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_SUB_IMAGE1D:
+ free(n[7].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_SUB_IMAGE2D:
+ free(n[9].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_TEX_SUB_IMAGE3D:
+ free(n[11].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_1D:
+ free(n[7].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_2D:
+ free(n[8].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_3D:
+ free(n[9].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D:
+ free(n[7].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D:
+ free(n[9].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D:
+ free(n[11].data);
+ n += InstSize[n[0].opcode];
+ break;
+#if FEATURE_NV_vertex_program
+ case OPCODE_LOAD_PROGRAM_NV:
+ free(n[4].data); /* program string */
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_REQUEST_RESIDENT_PROGRAMS_NV:
+ free(n[2].data); /* array of program ids */
+ n += InstSize[n[0].opcode];
+ break;
+#endif
+#if FEATURE_NV_fragment_program
+ case OPCODE_PROGRAM_NAMED_PARAMETER_NV:
+ free(n[3].data); /* parameter name */
+ n += InstSize[n[0].opcode];
+ break;
+#endif
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+ case OPCODE_PROGRAM_STRING_ARB:
+ free(n[4].data); /* program string */
+ n += InstSize[n[0].opcode];
+ break;
+#endif
+ case OPCODE_UNIFORM_1FV:
+ case OPCODE_UNIFORM_2FV:
+ case OPCODE_UNIFORM_3FV:
+ case OPCODE_UNIFORM_4FV:
+ case OPCODE_UNIFORM_1IV:
+ case OPCODE_UNIFORM_2IV:
+ case OPCODE_UNIFORM_3IV:
+ case OPCODE_UNIFORM_4IV:
+ case OPCODE_UNIFORM_1UIV:
+ case OPCODE_UNIFORM_2UIV:
+ case OPCODE_UNIFORM_3UIV:
+ case OPCODE_UNIFORM_4UIV:
+ free(n[3].data);
+ n += InstSize[n[0].opcode];
+ break;
+ case OPCODE_UNIFORM_MATRIX22:
+ case OPCODE_UNIFORM_MATRIX33:
+ case OPCODE_UNIFORM_MATRIX44:
+ case OPCODE_UNIFORM_MATRIX24:
+ case OPCODE_UNIFORM_MATRIX42:
+ case OPCODE_UNIFORM_MATRIX23:
+ case OPCODE_UNIFORM_MATRIX32:
+ case OPCODE_UNIFORM_MATRIX34:
+ case OPCODE_UNIFORM_MATRIX43:
+ free(n[4].data);
+ n += InstSize[n[0].opcode];
+ break;
+
+ case OPCODE_CONTINUE:
+ n = (Node *) n[1].next;
+ free(block);
+ block = n;
+ break;
+ case OPCODE_END_OF_LIST:
+ free(block);
+ done = GL_TRUE;
+ break;
+ default:
+ /* Most frequent case */
+ n += InstSize[n[0].opcode];
+ break;
+ }
+ }
+ }
+
+ free(dlist);
+}
+
+
+/**
+ * Destroy a display list and remove from hash table.
+ * \param list - display list number
+ */
+static void
+destroy_list(struct gl_context *ctx, GLuint list)
+{
+ struct gl_display_list *dlist;
+
+ if (list == 0)
+ return;
+
+ dlist = lookup_list(ctx, list);
+ if (!dlist)
+ return;
+
+ _mesa_delete_list(ctx, dlist);
+ _mesa_HashRemove(ctx->Shared->DisplayList, list);
+}
+
+
+/*
+ * Translate the nth element of list from <type> to GLint.
+ */
+static GLint
+translate_id(GLsizei n, GLenum type, const GLvoid * list)
+{
+ GLbyte *bptr;
+ GLubyte *ubptr;
+ GLshort *sptr;
+ GLushort *usptr;
+ GLint *iptr;
+ GLuint *uiptr;
+ GLfloat *fptr;
+
+ switch (type) {
+ case GL_BYTE:
+ bptr = (GLbyte *) list;
+ return (GLint) bptr[n];
+ case GL_UNSIGNED_BYTE:
+ ubptr = (GLubyte *) list;
+ return (GLint) ubptr[n];
+ case GL_SHORT:
+ sptr = (GLshort *) list;
+ return (GLint) sptr[n];
+ case GL_UNSIGNED_SHORT:
+ usptr = (GLushort *) list;
+ return (GLint) usptr[n];
+ case GL_INT:
+ iptr = (GLint *) list;
+ return iptr[n];
+ case GL_UNSIGNED_INT:
+ uiptr = (GLuint *) list;
+ return (GLint) uiptr[n];
+ case GL_FLOAT:
+ fptr = (GLfloat *) list;
+ return (GLint) FLOORF(fptr[n]);
+ case GL_2_BYTES:
+ ubptr = ((GLubyte *) list) + 2 * n;
+ return (GLint) ubptr[0] * 256
+ + (GLint) ubptr[1];
+ case GL_3_BYTES:
+ ubptr = ((GLubyte *) list) + 3 * n;
+ return (GLint) ubptr[0] * 65536
+ + (GLint) ubptr[1] * 256
+ + (GLint) ubptr[2];
+ case GL_4_BYTES:
+ ubptr = ((GLubyte *) list) + 4 * n;
+ return (GLint) ubptr[0] * 16777216
+ + (GLint) ubptr[1] * 65536
+ + (GLint) ubptr[2] * 256
+ + (GLint) ubptr[3];
+ default:
+ return 0;
+ }
+}
+
+
+
+
+/**********************************************************************/
+/***** Public *****/
+/**********************************************************************/
+
+/**
+ * Wrapper for _mesa_unpack_image() that handles pixel buffer objects.
+ * If we run out of memory, GL_OUT_OF_MEMORY will be recorded.
+ */
+static GLvoid *
+unpack_image(struct gl_context *ctx, GLuint dimensions,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid * pixels,
+ const struct gl_pixelstore_attrib *unpack)
+{
+ if (!_mesa_is_bufferobj(unpack->BufferObj)) {
+ /* no PBO */
+ GLvoid *image = _mesa_unpack_image(dimensions, width, height, depth,
+ format, type, pixels, unpack);
+ if (pixels && !image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "display list construction");
+ }
+ return image;
+ }
+ else if (_mesa_validate_pbo_access(dimensions, unpack, width, height, depth,
+ format, type, pixels)) {
+ const GLubyte *map, *src;
+ GLvoid *image;
+
+ map = (GLubyte *)
+ ctx->Driver.MapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
+ GL_READ_ONLY_ARB, unpack->BufferObj);
+ if (!map) {
+ /* unable to map src buffer! */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "unable to map PBO");
+ return NULL;
+ }
+
+ src = ADD_POINTERS(map, pixels);
+ image = _mesa_unpack_image(dimensions, width, height, depth,
+ format, type, src, unpack);
+
+ ctx->Driver.UnmapBuffer(ctx, GL_PIXEL_UNPACK_BUFFER_EXT,
+ unpack->BufferObj);
+
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "display list construction");
+ }
+ return image;
+ }
+ /* bad access! */
+ return NULL;
+}
+
+
+/**
+ * Allocate space for a display list instruction (opcode + payload space).
+ * \param opcode the instruction opcode (OPCODE_* value)
+ * \param bytes instruction payload size (not counting opcode)
+ * \return pointer to allocated memory (the opcode space)
+ */
+static Node *
+dlist_alloc(struct gl_context *ctx, OpCode opcode, GLuint bytes)
+{
+ const GLuint numNodes = 1 + (bytes + sizeof(Node) - 1) / sizeof(Node);
+ Node *n;
+
+ if (opcode < (GLuint) OPCODE_EXT_0) {
+ if (InstSize[opcode] == 0) {
+ /* save instruction size now */
+ InstSize[opcode] = numNodes;
+ }
+ else {
+ /* make sure instruction size agrees */
+ ASSERT(numNodes == InstSize[opcode]);
+ }
+ }
+
+ if (ctx->ListState.CurrentPos + numNodes + 2 > BLOCK_SIZE) {
+ /* This block is full. Allocate a new block and chain to it */
+ Node *newblock;
+ n = ctx->ListState.CurrentBlock + ctx->ListState.CurrentPos;
+ n[0].opcode = OPCODE_CONTINUE;
+ newblock = (Node *) malloc(sizeof(Node) * BLOCK_SIZE);
+ if (!newblock) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "Building display list");
+ return NULL;
+ }
+ n[1].next = (Node *) newblock;
+ ctx->ListState.CurrentBlock = newblock;
+ ctx->ListState.CurrentPos = 0;
+ }
+
+ n = ctx->ListState.CurrentBlock + ctx->ListState.CurrentPos;
+ ctx->ListState.CurrentPos += numNodes;
+
+ n[0].opcode = opcode;
+
+ return n;
+}
+
+
+
+/**
+ * Allocate space for a display list instruction. Used by callers outside
+ * this file for things like VBO vertex data.
+ *
+ * \param opcode the instruction opcode (OPCODE_* value)
+ * \param bytes instruction size in bytes, not counting opcode.
+ * \return pointer to the usable data area (not including the internal
+ * opcode).
+ */
+void *
+_mesa_dlist_alloc(struct gl_context *ctx, GLuint opcode, GLuint bytes)
+{
+ Node *n = dlist_alloc(ctx, (OpCode) opcode, bytes);
+ if (n)
+ return n + 1; /* return pointer to payload area, after opcode */
+ else
+ return NULL;
+}
+
+
+/**
+ * This function allows modules and drivers to get their own opcodes
+ * for extending display list functionality.
+ * \param ctx the rendering context
+ * \param size number of bytes for storing the new display list command
+ * \param execute function to execute the new display list command
+ * \param destroy function to destroy the new display list command
+ * \param print function to print the new display list command
+ * \return the new opcode number or -1 if error
+ */
+GLint
+_mesa_dlist_alloc_opcode(struct gl_context *ctx,
+ GLuint size,
+ void (*execute) (struct gl_context *, void *),
+ void (*destroy) (struct gl_context *, void *),
+ void (*print) (struct gl_context *, void *))
+{
+ if (ctx->ListExt->NumOpcodes < MAX_DLIST_EXT_OPCODES) {
+ const GLuint i = ctx->ListExt->NumOpcodes++;
+ ctx->ListExt->Opcode[i].Size =
+ 1 + (size + sizeof(Node) - 1) / sizeof(Node);
+ ctx->ListExt->Opcode[i].Execute = execute;
+ ctx->ListExt->Opcode[i].Destroy = destroy;
+ ctx->ListExt->Opcode[i].Print = print;
+ return i + OPCODE_EXT_0;
+ }
+ return -1;
+}
+
+
+/**
+ * Allocate space for a display list instruction. The space is basically
+ * an array of Nodes where node[0] holds the opcode, node[1] is the first
+ * function parameter, node[2] is the second parameter, etc.
+ *
+ * \param opcode one of OPCODE_x
+ * \param nparams number of function parameters
+ * \return pointer to start of instruction space
+ */
+static INLINE Node *
+alloc_instruction(struct gl_context *ctx, OpCode opcode, GLuint nparams)
+{
+ return dlist_alloc(ctx, opcode, nparams * sizeof(Node));
+}
+
+
+
+/*
+ * Display List compilation functions
+ */
+static void GLAPIENTRY
+save_Accum(GLenum op, GLfloat value)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ACCUM, 2);
+ if (n) {
+ n[1].e = op;
+ n[2].f = value;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Accum(ctx->Exec, (op, value));
+ }
+}
+
+
+static void GLAPIENTRY
+save_AlphaFunc(GLenum func, GLclampf ref)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ALPHA_FUNC, 2);
+ if (n) {
+ n[1].e = func;
+ n[2].f = (GLfloat) ref;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_AlphaFunc(ctx->Exec, (func, ref));
+ }
+}
+
+
+static void GLAPIENTRY
+save_BindTexture(GLenum target, GLuint texture)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BIND_TEXTURE, 2);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = texture;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BindTexture(ctx->Exec, (target, texture));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Bitmap(GLsizei width, GLsizei height,
+ GLfloat xorig, GLfloat yorig,
+ GLfloat xmove, GLfloat ymove, const GLubyte * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BITMAP, 7);
+ if (n) {
+ n[1].i = (GLint) width;
+ n[2].i = (GLint) height;
+ n[3].f = xorig;
+ n[4].f = yorig;
+ n[5].f = xmove;
+ n[6].f = ymove;
+ n[7].data = _mesa_unpack_bitmap(width, height, pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Bitmap(ctx->Exec, (width, height,
+ xorig, yorig, xmove, ymove, pixels));
+ }
+}
+
+
+static void GLAPIENTRY
+save_BlendEquation(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendEquation(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_BlendEquationSeparateEXT(GLenum modeRGB, GLenum modeA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_SEPARATE, 2);
+ if (n) {
+ n[1].e = modeRGB;
+ n[2].e = modeA;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendEquationSeparateEXT(ctx->Exec, (modeRGB, modeA));
+ }
+}
+
+
+static void GLAPIENTRY
+save_BlendFuncSeparateEXT(GLenum sfactorRGB, GLenum dfactorRGB,
+ GLenum sfactorA, GLenum dfactorA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE, 4);
+ if (n) {
+ n[1].e = sfactorRGB;
+ n[2].e = dfactorRGB;
+ n[3].e = sfactorA;
+ n[4].e = dfactorA;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendFuncSeparateEXT(ctx->Exec,
+ (sfactorRGB, dfactorRGB, sfactorA, dfactorA));
+ }
+}
+
+
+static void GLAPIENTRY
+save_BlendFunc(GLenum srcfactor, GLenum dstfactor)
+{
+ save_BlendFuncSeparateEXT(srcfactor, dstfactor, srcfactor, dstfactor);
+}
+
+
+static void GLAPIENTRY
+save_BlendColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_COLOR, 4);
+ if (n) {
+ n[1].f = red;
+ n[2].f = green;
+ n[3].f = blue;
+ n[4].f = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendColor(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+/* GL_ARB_draw_buffers_blend */
+static void GLAPIENTRY
+save_BlendFuncSeparatei(GLuint buf, GLenum sfactorRGB, GLenum dfactorRGB,
+ GLenum sfactorA, GLenum dfactorA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE_I, 5);
+ if (n) {
+ n[1].ui = buf;
+ n[2].e = sfactorRGB;
+ n[3].e = dfactorRGB;
+ n[4].e = sfactorA;
+ n[5].e = dfactorA;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendFuncSeparateiARB(ctx->Exec, (buf, sfactorRGB, dfactorRGB,
+ sfactorA, dfactorA));
+ }
+}
+
+/* GL_ARB_draw_buffers_blend */
+static void GLAPIENTRY
+save_BlendFunci(GLuint buf, GLenum sfactor, GLenum dfactor)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_FUNC_SEPARATE_I, 3);
+ if (n) {
+ n[1].ui = buf;
+ n[2].e = sfactor;
+ n[3].e = dfactor;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendFunciARB(ctx->Exec, (buf, sfactor, dfactor));
+ }
+}
+
+/* GL_ARB_draw_buffers_blend */
+static void GLAPIENTRY
+save_BlendEquationi(GLuint buf, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_I, 2);
+ if (n) {
+ n[1].ui = buf;
+ n[2].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendEquationiARB(ctx->Exec, (buf, mode));
+ }
+}
+
+/* GL_ARB_draw_buffers_blend */
+static void GLAPIENTRY
+save_BlendEquationSeparatei(GLuint buf, GLenum modeRGB, GLenum modeA)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLEND_EQUATION_SEPARATE_I, 3);
+ if (n) {
+ n[1].ui = buf;
+ n[2].e = modeRGB;
+ n[3].e = modeA;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlendEquationSeparateiARB(ctx->Exec, (buf, modeRGB, modeA));
+ }
+}
+
+
+static void invalidate_saved_current_state( struct gl_context *ctx )
+{
+ GLint i;
+
+ for (i = 0; i < VERT_ATTRIB_MAX; i++)
+ ctx->ListState.ActiveAttribSize[i] = 0;
+
+ for (i = 0; i < MAT_ATTRIB_MAX; i++)
+ ctx->ListState.ActiveMaterialSize[i] = 0;
+
+ memset(&ctx->ListState.Current, 0, sizeof ctx->ListState.Current);
+
+ ctx->Driver.CurrentSavePrimitive = PRIM_UNKNOWN;
+}
+
+static void GLAPIENTRY
+save_CallList(GLuint list)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_CALL_LIST, 1);
+ if (n) {
+ n[1].ui = list;
+ }
+
+ /* After this, we don't know what state we're in. Invalidate all
+ * cached information previously gathered:
+ */
+ invalidate_saved_current_state( ctx );
+
+ if (ctx->ExecuteFlag) {
+ _mesa_CallList(list);
+ }
+}
+
+
+static void GLAPIENTRY
+save_CallLists(GLsizei num, GLenum type, const GLvoid * lists)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint i;
+ GLboolean typeErrorFlag;
+
+ SAVE_FLUSH_VERTICES(ctx);
+
+ switch (type) {
+ case GL_BYTE:
+ case GL_UNSIGNED_BYTE:
+ case GL_SHORT:
+ case GL_UNSIGNED_SHORT:
+ case GL_INT:
+ case GL_UNSIGNED_INT:
+ case GL_FLOAT:
+ case GL_2_BYTES:
+ case GL_3_BYTES:
+ case GL_4_BYTES:
+ typeErrorFlag = GL_FALSE;
+ break;
+ default:
+ typeErrorFlag = GL_TRUE;
+ }
+
+ for (i = 0; i < num; i++) {
+ GLint list = translate_id(i, type, lists);
+ Node *n = alloc_instruction(ctx, OPCODE_CALL_LIST_OFFSET, 2);
+ if (n) {
+ n[1].i = list;
+ n[2].b = typeErrorFlag;
+ }
+ }
+
+ /* After this, we don't know what state we're in. Invalidate all
+ * cached information previously gathered:
+ */
+ invalidate_saved_current_state( ctx );
+
+ if (ctx->ExecuteFlag) {
+ CALL_CallLists(ctx->Exec, (num, type, lists));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Clear(GLbitfield mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR, 1);
+ if (n) {
+ n[1].bf = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Clear(ctx->Exec, (mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearBufferiv(GLenum buffer, GLint drawbuffer, const GLint *value)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_IV, 6);
+ if (n) {
+ n[1].e = buffer;
+ n[2].i = drawbuffer;
+ n[3].i = value[0];
+ if (buffer == GL_COLOR) {
+ n[4].i = value[1];
+ n[5].i = value[2];
+ n[6].i = value[3];
+ }
+ else {
+ n[4].i = 0;
+ n[5].i = 0;
+ n[6].i = 0;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ClearBufferiv(ctx->Exec, (buffer, drawbuffer, value));*/
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearBufferuiv(GLenum buffer, GLint drawbuffer, const GLuint *value)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_UIV, 6);
+ if (n) {
+ n[1].e = buffer;
+ n[2].i = drawbuffer;
+ n[3].ui = value[0];
+ if (buffer == GL_COLOR) {
+ n[4].ui = value[1];
+ n[5].ui = value[2];
+ n[6].ui = value[3];
+ }
+ else {
+ n[4].ui = 0;
+ n[5].ui = 0;
+ n[6].ui = 0;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ClearBufferuiv(ctx->Exec, (buffer, drawbuffer, value));*/
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearBufferfv(GLenum buffer, GLint drawbuffer, const GLfloat *value)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_FV, 6);
+ if (n) {
+ n[1].e = buffer;
+ n[2].i = drawbuffer;
+ n[3].f = value[0];
+ if (buffer == GL_COLOR) {
+ n[4].f = value[1];
+ n[5].f = value[2];
+ n[6].f = value[3];
+ }
+ else {
+ n[4].f = 0.0F;
+ n[5].f = 0.0F;
+ n[6].f = 0.0F;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ClearBufferuiv(ctx->Exec, (buffer, drawbuffer, value));*/
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearBufferfi(GLenum buffer, GLint drawbuffer,
+ GLfloat depth, GLint stencil)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_BUFFER_FI, 4);
+ if (n) {
+ n[1].e = buffer;
+ n[2].i = drawbuffer;
+ n[3].f = depth;
+ n[4].i = stencil;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ClearBufferfi(ctx->Exec, (buffer, drawbuffer, depth, stencil));*/
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearAccum(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_ACCUM, 4);
+ if (n) {
+ n[1].f = red;
+ n[2].f = green;
+ n[3].f = blue;
+ n[4].f = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearAccum(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_COLOR, 4);
+ if (n) {
+ n[1].f = red;
+ n[2].f = green;
+ n[3].f = blue;
+ n[4].f = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearColor(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearDepth(GLclampd depth)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_DEPTH, 1);
+ if (n) {
+ n[1].f = (GLfloat) depth;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearDepth(ctx->Exec, (depth));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearIndex(GLfloat c)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_INDEX, 1);
+ if (n) {
+ n[1].f = c;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearIndex(ctx->Exec, (c));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClearStencil(GLint s)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEAR_STENCIL, 1);
+ if (n) {
+ n[1].i = s;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearStencil(ctx->Exec, (s));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ClipPlane(GLenum plane, const GLdouble * equ)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLIP_PLANE, 5);
+ if (n) {
+ n[1].e = plane;
+ n[2].f = (GLfloat) equ[0];
+ n[3].f = (GLfloat) equ[1];
+ n[4].f = (GLfloat) equ[2];
+ n[5].f = (GLfloat) equ[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClipPlane(ctx->Exec, (plane, equ));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_ColorMask(GLboolean red, GLboolean green,
+ GLboolean blue, GLboolean alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COLOR_MASK, 4);
+ if (n) {
+ n[1].b = red;
+ n[2].b = green;
+ n[3].b = blue;
+ n[4].b = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ColorMask(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ColorMaskIndexed(GLuint buf, GLboolean red, GLboolean green,
+ GLboolean blue, GLboolean alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COLOR_MASK_INDEXED, 5);
+ if (n) {
+ n[1].ui = buf;
+ n[2].b = red;
+ n[3].b = green;
+ n[4].b = blue;
+ n[5].b = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ColorMaskIndexedEXT(ctx->Exec, (buf, red, green, blue, alpha));*/
+ }
+}
+
+
+static void GLAPIENTRY
+save_ColorMaterial(GLenum face, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_COLOR_MATERIAL, 2);
+ if (n) {
+ n[1].e = face;
+ n[2].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ColorMaterial(ctx->Exec, (face, mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ColorTable(GLenum target, GLenum internalFormat,
+ GLsizei width, GLenum format, GLenum type,
+ const GLvoid * table)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (_mesa_is_proxy_texture(target)) {
+ /* execute immediately */
+ CALL_ColorTable(ctx->Exec, (target, internalFormat, width,
+ format, type, table));
+ }
+ else {
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COLOR_TABLE, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = internalFormat;
+ n[3].i = width;
+ n[4].e = format;
+ n[5].e = type;
+ n[6].data = unpack_image(ctx, 1, width, 1, 1, format, type, table,
+ &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ColorTable(ctx->Exec, (target, internalFormat, width,
+ format, type, table));
+ }
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_ColorTableParameterfv(GLenum target, GLenum pname,
+ const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_COLOR_TABLE_PARAMETER_FV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].f = params[0];
+ if (pname == GL_COLOR_TABLE_SGI ||
+ pname == GL_POST_CONVOLUTION_COLOR_TABLE_SGI ||
+ pname == GL_TEXTURE_COLOR_TABLE_SGI) {
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_ColorTableParameterfv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ColorTableParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_COLOR_TABLE_PARAMETER_IV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].i = params[0];
+ if (pname == GL_COLOR_TABLE_SGI ||
+ pname == GL_POST_CONVOLUTION_COLOR_TABLE_SGI ||
+ pname == GL_TEXTURE_COLOR_TABLE_SGI) {
+ n[4].i = params[1];
+ n[5].i = params[2];
+ n[6].i = params[3];
+ }
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_ColorTableParameteriv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_ColorSubTable(GLenum target, GLsizei start, GLsizei count,
+ GLenum format, GLenum type, const GLvoid * table)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COLOR_SUB_TABLE, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].i = start;
+ n[3].i = count;
+ n[4].e = format;
+ n[5].e = type;
+ n[6].data = unpack_image(ctx, 1, count, 1, 1, format, type, table,
+ &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ColorSubTable(ctx->Exec,
+ (target, start, count, format, type, table));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyColorSubTable(GLenum target, GLsizei start,
+ GLint x, GLint y, GLsizei width)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_COLOR_SUB_TABLE, 5);
+ if (n) {
+ n[1].e = target;
+ n[2].i = start;
+ n[3].i = x;
+ n[4].i = y;
+ n[5].i = width;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyColorSubTable(ctx->Exec, (target, start, x, y, width));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyColorTable(GLenum target, GLenum internalformat,
+ GLint x, GLint y, GLsizei width)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_COLOR_TABLE, 5);
+ if (n) {
+ n[1].e = target;
+ n[2].e = internalformat;
+ n[3].i = x;
+ n[4].i = y;
+ n[5].i = width;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyColorTable(ctx->Exec, (target, internalformat, x, y, width));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionFilter1D(GLenum target, GLenum internalFormat, GLsizei width,
+ GLenum format, GLenum type, const GLvoid * filter)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_FILTER_1D, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = internalFormat;
+ n[3].i = width;
+ n[4].e = format;
+ n[5].e = type;
+ n[6].data = unpack_image(ctx, 1, width, 1, 1, format, type, filter,
+ &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionFilter1D(ctx->Exec, (target, internalFormat, width,
+ format, type, filter));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionFilter2D(GLenum target, GLenum internalFormat,
+ GLsizei width, GLsizei height, GLenum format,
+ GLenum type, const GLvoid * filter)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_FILTER_2D, 7);
+ if (n) {
+ n[1].e = target;
+ n[2].e = internalFormat;
+ n[3].i = width;
+ n[4].i = height;
+ n[5].e = format;
+ n[6].e = type;
+ n[7].data = unpack_image(ctx, 2, width, height, 1, format, type, filter,
+ &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionFilter2D(ctx->Exec,
+ (target, internalFormat, width, height, format,
+ type, filter));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionParameteri(GLenum target, GLenum pname, GLint param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_I, 3);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].i = param;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionParameteri(ctx->Exec, (target, pname, param));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_IV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].i = params[0];
+ if (pname == GL_CONVOLUTION_BORDER_COLOR ||
+ pname == GL_CONVOLUTION_FILTER_SCALE ||
+ pname == GL_CONVOLUTION_FILTER_BIAS) {
+ n[4].i = params[1];
+ n[5].i = params[2];
+ n[6].i = params[3];
+ }
+ else {
+ n[4].i = n[5].i = n[6].i = 0;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionParameteriv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_F, 3);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].f = param;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionParameterf(ctx->Exec, (target, pname, param));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ConvolutionParameterfv(GLenum target, GLenum pname,
+ const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CONVOLUTION_PARAMETER_FV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].f = params[0];
+ if (pname == GL_CONVOLUTION_BORDER_COLOR ||
+ pname == GL_CONVOLUTION_FILTER_SCALE ||
+ pname == GL_CONVOLUTION_FILTER_BIAS) {
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ else {
+ n[4].f = n[5].f = n[6].f = 0.0F;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ConvolutionParameterfv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_PIXELS, 5);
+ if (n) {
+ n[1].i = x;
+ n[2].i = y;
+ n[3].i = (GLint) width;
+ n[4].i = (GLint) height;
+ n[5].e = type;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyPixels(ctx->Exec, (x, y, width, height, type));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_CopyTexImage1D(GLenum target, GLint level, GLenum internalformat,
+ GLint x, GLint y, GLsizei width, GLint border)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_TEX_IMAGE1D, 7);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].e = internalformat;
+ n[4].i = x;
+ n[5].i = y;
+ n[6].i = width;
+ n[7].i = border;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyTexImage1D(ctx->Exec, (target, level, internalformat,
+ x, y, width, border));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyTexImage2D(GLenum target, GLint level,
+ GLenum internalformat,
+ GLint x, GLint y, GLsizei width,
+ GLsizei height, GLint border)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_TEX_IMAGE2D, 8);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].e = internalformat;
+ n[4].i = x;
+ n[5].i = y;
+ n[6].i = width;
+ n[7].i = height;
+ n[8].i = border;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyTexImage2D(ctx->Exec, (target, level, internalformat,
+ x, y, width, height, border));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_CopyTexSubImage1D(GLenum target, GLint level,
+ GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE1D, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = x;
+ n[5].i = y;
+ n[6].i = width;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyTexSubImage1D(ctx->Exec,
+ (target, level, xoffset, x, y, width));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyTexSubImage2D(GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLint x, GLint y, GLsizei width, GLint height)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE2D, 8);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = x;
+ n[6].i = y;
+ n[7].i = width;
+ n[8].i = height;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyTexSubImage2D(ctx->Exec, (target, level, xoffset, yoffset,
+ x, y, width, height));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CopyTexSubImage3D(GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint x, GLint y, GLsizei width, GLint height)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_COPY_TEX_SUB_IMAGE3D, 9);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = zoffset;
+ n[6].i = x;
+ n[7].i = y;
+ n[8].i = width;
+ n[9].i = height;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CopyTexSubImage3D(ctx->Exec, (target, level,
+ xoffset, yoffset, zoffset,
+ x, y, width, height));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CullFace(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CULL_FACE, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CullFace(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DepthFunc(GLenum func)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DEPTH_FUNC, 1);
+ if (n) {
+ n[1].e = func;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DepthFunc(ctx->Exec, (func));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DepthMask(GLboolean mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DEPTH_MASK, 1);
+ if (n) {
+ n[1].b = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DepthMask(ctx->Exec, (mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DepthRange(GLclampd nearval, GLclampd farval)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DEPTH_RANGE, 2);
+ if (n) {
+ n[1].f = (GLfloat) nearval;
+ n[2].f = (GLfloat) farval;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DepthRange(ctx->Exec, (nearval, farval));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Disable(GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DISABLE, 1);
+ if (n) {
+ n[1].e = cap;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Disable(ctx->Exec, (cap));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DisableIndexed(GLuint index, GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DISABLE_INDEXED, 2);
+ if (n) {
+ n[1].ui = index;
+ n[2].e = cap;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DisableIndexedEXT(ctx->Exec, (index, cap));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DrawBuffer(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DRAW_BUFFER, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DrawBuffer(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_DrawPixels(GLsizei width, GLsizei height,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_DRAW_PIXELS, 5);
+ if (n) {
+ n[1].i = width;
+ n[2].i = height;
+ n[3].e = format;
+ n[4].e = type;
+ n[5].data = unpack_image(ctx, 2, width, height, 1, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DrawPixels(ctx->Exec, (width, height, format, type, pixels));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_Enable(GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ENABLE, 1);
+ if (n) {
+ n[1].e = cap;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Enable(ctx->Exec, (cap));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_EnableIndexed(GLuint index, GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ENABLE_INDEXED, 2);
+ if (n) {
+ n[1].ui = index;
+ n[2].e = cap;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EnableIndexedEXT(ctx->Exec, (index, cap));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_EvalMesh1(GLenum mode, GLint i1, GLint i2)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVALMESH1, 3);
+ if (n) {
+ n[1].e = mode;
+ n[2].i = i1;
+ n[3].i = i2;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalMesh1(ctx->Exec, (mode, i1, i2));
+ }
+}
+
+
+static void GLAPIENTRY
+save_EvalMesh2(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVALMESH2, 5);
+ if (n) {
+ n[1].e = mode;
+ n[2].i = i1;
+ n[3].i = i2;
+ n[4].i = j1;
+ n[5].i = j2;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalMesh2(ctx->Exec, (mode, i1, i2, j1, j2));
+ }
+}
+
+
+
+
+static void GLAPIENTRY
+save_Fogfv(GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_FOG, 5);
+ if (n) {
+ n[1].e = pname;
+ n[2].f = params[0];
+ n[3].f = params[1];
+ n[4].f = params[2];
+ n[5].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Fogfv(ctx->Exec, (pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Fogf(GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_Fogfv(pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_Fogiv(GLenum pname, const GLint *params)
+{
+ GLfloat p[4];
+ switch (pname) {
+ case GL_FOG_MODE:
+ case GL_FOG_DENSITY:
+ case GL_FOG_START:
+ case GL_FOG_END:
+ case GL_FOG_INDEX:
+ p[0] = (GLfloat) *params;
+ p[1] = 0.0f;
+ p[2] = 0.0f;
+ p[3] = 0.0f;
+ break;
+ case GL_FOG_COLOR:
+ p[0] = INT_TO_FLOAT(params[0]);
+ p[1] = INT_TO_FLOAT(params[1]);
+ p[2] = INT_TO_FLOAT(params[2]);
+ p[3] = INT_TO_FLOAT(params[3]);
+ break;
+ default:
+ /* Error will be caught later in gl_Fogfv */
+ ASSIGN_4V(p, 0.0F, 0.0F, 0.0F, 0.0F);
+ }
+ save_Fogfv(pname, p);
+}
+
+
+static void GLAPIENTRY
+save_Fogi(GLenum pname, GLint param)
+{
+ GLint parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0;
+ save_Fogiv(pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_FrontFace(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_FRONT_FACE, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_FrontFace(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Frustum(GLdouble left, GLdouble right,
+ GLdouble bottom, GLdouble top, GLdouble nearval, GLdouble farval)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_FRUSTUM, 6);
+ if (n) {
+ n[1].f = (GLfloat) left;
+ n[2].f = (GLfloat) right;
+ n[3].f = (GLfloat) bottom;
+ n[4].f = (GLfloat) top;
+ n[5].f = (GLfloat) nearval;
+ n[6].f = (GLfloat) farval;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Frustum(ctx->Exec, (left, right, bottom, top, nearval, farval));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Hint(GLenum target, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_HINT, 2);
+ if (n) {
+ n[1].e = target;
+ n[2].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Hint(ctx->Exec, (target, mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Histogram(GLenum target, GLsizei width, GLenum internalFormat,
+ GLboolean sink)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_HISTOGRAM, 4);
+ if (n) {
+ n[1].e = target;
+ n[2].i = width;
+ n[3].e = internalFormat;
+ n[4].b = sink;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Histogram(ctx->Exec, (target, width, internalFormat, sink));
+ }
+}
+
+
+static void GLAPIENTRY
+save_IndexMask(GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_INDEX_MASK, 1);
+ if (n) {
+ n[1].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_IndexMask(ctx->Exec, (mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_InitNames(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_INIT_NAMES, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_InitNames(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_Lightfv(GLenum light, GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LIGHT, 6);
+ if (n) {
+ GLint i, nParams;
+ n[1].e = light;
+ n[2].e = pname;
+ switch (pname) {
+ case GL_AMBIENT:
+ nParams = 4;
+ break;
+ case GL_DIFFUSE:
+ nParams = 4;
+ break;
+ case GL_SPECULAR:
+ nParams = 4;
+ break;
+ case GL_POSITION:
+ nParams = 4;
+ break;
+ case GL_SPOT_DIRECTION:
+ nParams = 3;
+ break;
+ case GL_SPOT_EXPONENT:
+ nParams = 1;
+ break;
+ case GL_SPOT_CUTOFF:
+ nParams = 1;
+ break;
+ case GL_CONSTANT_ATTENUATION:
+ nParams = 1;
+ break;
+ case GL_LINEAR_ATTENUATION:
+ nParams = 1;
+ break;
+ case GL_QUADRATIC_ATTENUATION:
+ nParams = 1;
+ break;
+ default:
+ nParams = 0;
+ }
+ for (i = 0; i < nParams; i++) {
+ n[3 + i].f = params[i];
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Lightfv(ctx->Exec, (light, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Lightf(GLenum light, GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_Lightfv(light, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_Lightiv(GLenum light, GLenum pname, const GLint *params)
+{
+ GLfloat fparam[4];
+ switch (pname) {
+ case GL_AMBIENT:
+ case GL_DIFFUSE:
+ case GL_SPECULAR:
+ fparam[0] = INT_TO_FLOAT(params[0]);
+ fparam[1] = INT_TO_FLOAT(params[1]);
+ fparam[2] = INT_TO_FLOAT(params[2]);
+ fparam[3] = INT_TO_FLOAT(params[3]);
+ break;
+ case GL_POSITION:
+ fparam[0] = (GLfloat) params[0];
+ fparam[1] = (GLfloat) params[1];
+ fparam[2] = (GLfloat) params[2];
+ fparam[3] = (GLfloat) params[3];
+ break;
+ case GL_SPOT_DIRECTION:
+ fparam[0] = (GLfloat) params[0];
+ fparam[1] = (GLfloat) params[1];
+ fparam[2] = (GLfloat) params[2];
+ break;
+ case GL_SPOT_EXPONENT:
+ case GL_SPOT_CUTOFF:
+ case GL_CONSTANT_ATTENUATION:
+ case GL_LINEAR_ATTENUATION:
+ case GL_QUADRATIC_ATTENUATION:
+ fparam[0] = (GLfloat) params[0];
+ break;
+ default:
+ /* error will be caught later in gl_Lightfv */
+ ;
+ }
+ save_Lightfv(light, pname, fparam);
+}
+
+
+static void GLAPIENTRY
+save_Lighti(GLenum light, GLenum pname, GLint param)
+{
+ GLint parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0;
+ save_Lightiv(light, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_LightModelfv(GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LIGHT_MODEL, 5);
+ if (n) {
+ n[1].e = pname;
+ n[2].f = params[0];
+ n[3].f = params[1];
+ n[4].f = params[2];
+ n[5].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LightModelfv(ctx->Exec, (pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_LightModelf(GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_LightModelfv(pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_LightModeliv(GLenum pname, const GLint *params)
+{
+ GLfloat fparam[4];
+ switch (pname) {
+ case GL_LIGHT_MODEL_AMBIENT:
+ fparam[0] = INT_TO_FLOAT(params[0]);
+ fparam[1] = INT_TO_FLOAT(params[1]);
+ fparam[2] = INT_TO_FLOAT(params[2]);
+ fparam[3] = INT_TO_FLOAT(params[3]);
+ break;
+ case GL_LIGHT_MODEL_LOCAL_VIEWER:
+ case GL_LIGHT_MODEL_TWO_SIDE:
+ case GL_LIGHT_MODEL_COLOR_CONTROL:
+ fparam[0] = (GLfloat) params[0];
+ fparam[1] = 0.0F;
+ fparam[2] = 0.0F;
+ fparam[3] = 0.0F;
+ break;
+ default:
+ /* Error will be caught later in gl_LightModelfv */
+ ASSIGN_4V(fparam, 0.0F, 0.0F, 0.0F, 0.0F);
+ }
+ save_LightModelfv(pname, fparam);
+}
+
+
+static void GLAPIENTRY
+save_LightModeli(GLenum pname, GLint param)
+{
+ GLint parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0;
+ save_LightModeliv(pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_LineStipple(GLint factor, GLushort pattern)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LINE_STIPPLE, 2);
+ if (n) {
+ n[1].i = factor;
+ n[2].us = pattern;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LineStipple(ctx->Exec, (factor, pattern));
+ }
+}
+
+
+static void GLAPIENTRY
+save_LineWidth(GLfloat width)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LINE_WIDTH, 1);
+ if (n) {
+ n[1].f = width;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LineWidth(ctx->Exec, (width));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ListBase(GLuint base)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LIST_BASE, 1);
+ if (n) {
+ n[1].ui = base;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ListBase(ctx->Exec, (base));
+ }
+}
+
+
+static void GLAPIENTRY
+save_LoadIdentity(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_LOAD_IDENTITY, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_LoadIdentity(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_LoadMatrixf(const GLfloat * m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LOAD_MATRIX, 16);
+ if (n) {
+ GLuint i;
+ for (i = 0; i < 16; i++) {
+ n[1 + i].f = m[i];
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LoadMatrixf(ctx->Exec, (m));
+ }
+}
+
+
+static void GLAPIENTRY
+save_LoadMatrixd(const GLdouble * m)
+{
+ GLfloat f[16];
+ GLint i;
+ for (i = 0; i < 16; i++) {
+ f[i] = (GLfloat) m[i];
+ }
+ save_LoadMatrixf(f);
+}
+
+
+static void GLAPIENTRY
+save_LoadName(GLuint name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LOAD_NAME, 1);
+ if (n) {
+ n[1].ui = name;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LoadName(ctx->Exec, (name));
+ }
+}
+
+
+static void GLAPIENTRY
+save_LogicOp(GLenum opcode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_LOGIC_OP, 1);
+ if (n) {
+ n[1].e = opcode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LogicOp(ctx->Exec, (opcode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Map1d(GLenum target, GLdouble u1, GLdouble u2, GLint stride,
+ GLint order, const GLdouble * points)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAP1, 6);
+ if (n) {
+ GLfloat *pnts = _mesa_copy_map_points1d(target, stride, order, points);
+ n[1].e = target;
+ n[2].f = (GLfloat) u1;
+ n[3].f = (GLfloat) u2;
+ n[4].i = _mesa_evaluator_components(target); /* stride */
+ n[5].i = order;
+ n[6].data = (void *) pnts;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Map1d(ctx->Exec, (target, u1, u2, stride, order, points));
+ }
+}
+
+static void GLAPIENTRY
+save_Map1f(GLenum target, GLfloat u1, GLfloat u2, GLint stride,
+ GLint order, const GLfloat * points)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAP1, 6);
+ if (n) {
+ GLfloat *pnts = _mesa_copy_map_points1f(target, stride, order, points);
+ n[1].e = target;
+ n[2].f = u1;
+ n[3].f = u2;
+ n[4].i = _mesa_evaluator_components(target); /* stride */
+ n[5].i = order;
+ n[6].data = (void *) pnts;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Map1f(ctx->Exec, (target, u1, u2, stride, order, points));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Map2d(GLenum target,
+ GLdouble u1, GLdouble u2, GLint ustride, GLint uorder,
+ GLdouble v1, GLdouble v2, GLint vstride, GLint vorder,
+ const GLdouble * points)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAP2, 10);
+ if (n) {
+ GLfloat *pnts = _mesa_copy_map_points2d(target, ustride, uorder,
+ vstride, vorder, points);
+ n[1].e = target;
+ n[2].f = (GLfloat) u1;
+ n[3].f = (GLfloat) u2;
+ n[4].f = (GLfloat) v1;
+ n[5].f = (GLfloat) v2;
+ /* XXX verify these strides are correct */
+ n[6].i = _mesa_evaluator_components(target) * vorder; /*ustride */
+ n[7].i = _mesa_evaluator_components(target); /*vstride */
+ n[8].i = uorder;
+ n[9].i = vorder;
+ n[10].data = (void *) pnts;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Map2d(ctx->Exec, (target,
+ u1, u2, ustride, uorder,
+ v1, v2, vstride, vorder, points));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Map2f(GLenum target,
+ GLfloat u1, GLfloat u2, GLint ustride, GLint uorder,
+ GLfloat v1, GLfloat v2, GLint vstride, GLint vorder,
+ const GLfloat * points)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAP2, 10);
+ if (n) {
+ GLfloat *pnts = _mesa_copy_map_points2f(target, ustride, uorder,
+ vstride, vorder, points);
+ n[1].e = target;
+ n[2].f = u1;
+ n[3].f = u2;
+ n[4].f = v1;
+ n[5].f = v2;
+ /* XXX verify these strides are correct */
+ n[6].i = _mesa_evaluator_components(target) * vorder; /*ustride */
+ n[7].i = _mesa_evaluator_components(target); /*vstride */
+ n[8].i = uorder;
+ n[9].i = vorder;
+ n[10].data = (void *) pnts;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Map2f(ctx->Exec, (target, u1, u2, ustride, uorder,
+ v1, v2, vstride, vorder, points));
+ }
+}
+
+
+static void GLAPIENTRY
+save_MapGrid1f(GLint un, GLfloat u1, GLfloat u2)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAPGRID1, 3);
+ if (n) {
+ n[1].i = un;
+ n[2].f = u1;
+ n[3].f = u2;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_MapGrid1f(ctx->Exec, (un, u1, u2));
+ }
+}
+
+
+static void GLAPIENTRY
+save_MapGrid1d(GLint un, GLdouble u1, GLdouble u2)
+{
+ save_MapGrid1f(un, (GLfloat) u1, (GLfloat) u2);
+}
+
+
+static void GLAPIENTRY
+save_MapGrid2f(GLint un, GLfloat u1, GLfloat u2,
+ GLint vn, GLfloat v1, GLfloat v2)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MAPGRID2, 6);
+ if (n) {
+ n[1].i = un;
+ n[2].f = u1;
+ n[3].f = u2;
+ n[4].i = vn;
+ n[5].f = v1;
+ n[6].f = v2;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_MapGrid2f(ctx->Exec, (un, u1, u2, vn, v1, v2));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_MapGrid2d(GLint un, GLdouble u1, GLdouble u2,
+ GLint vn, GLdouble v1, GLdouble v2)
+{
+ save_MapGrid2f(un, (GLfloat) u1, (GLfloat) u2,
+ vn, (GLfloat) v1, (GLfloat) v2);
+}
+
+
+static void GLAPIENTRY
+save_MatrixMode(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MATRIX_MODE, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_MatrixMode(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Minmax(GLenum target, GLenum internalFormat, GLboolean sink)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MIN_MAX, 3);
+ if (n) {
+ n[1].e = target;
+ n[2].e = internalFormat;
+ n[3].b = sink;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Minmax(ctx->Exec, (target, internalFormat, sink));
+ }
+}
+
+
+static void GLAPIENTRY
+save_MultMatrixf(const GLfloat * m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_MULT_MATRIX, 16);
+ if (n) {
+ GLuint i;
+ for (i = 0; i < 16; i++) {
+ n[1 + i].f = m[i];
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_MultMatrixf(ctx->Exec, (m));
+ }
+}
+
+
+static void GLAPIENTRY
+save_MultMatrixd(const GLdouble * m)
+{
+ GLfloat f[16];
+ GLint i;
+ for (i = 0; i < 16; i++) {
+ f[i] = (GLfloat) m[i];
+ }
+ save_MultMatrixf(f);
+}
+
+
+static void GLAPIENTRY
+save_NewList(GLuint name, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ /* It's an error to call this function while building a display list */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glNewList");
+ (void) name;
+ (void) mode;
+}
+
+
+
+static void GLAPIENTRY
+save_Ortho(GLdouble left, GLdouble right,
+ GLdouble bottom, GLdouble top, GLdouble nearval, GLdouble farval)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ORTHO, 6);
+ if (n) {
+ n[1].f = (GLfloat) left;
+ n[2].f = (GLfloat) right;
+ n[3].f = (GLfloat) bottom;
+ n[4].f = (GLfloat) top;
+ n[5].f = (GLfloat) nearval;
+ n[6].f = (GLfloat) farval;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Ortho(ctx->Exec, (left, right, bottom, top, nearval, farval));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PixelMapfv(GLenum map, GLint mapsize, const GLfloat *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PIXEL_MAP, 3);
+ if (n) {
+ n[1].e = map;
+ n[2].i = mapsize;
+ n[3].data = (void *) malloc(mapsize * sizeof(GLfloat));
+ memcpy(n[3].data, (void *) values, mapsize * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PixelMapfv(ctx->Exec, (map, mapsize, values));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PixelMapuiv(GLenum map, GLint mapsize, const GLuint *values)
+{
+ GLfloat fvalues[MAX_PIXEL_MAP_TABLE];
+ GLint i;
+ if (map == GL_PIXEL_MAP_I_TO_I || map == GL_PIXEL_MAP_S_TO_S) {
+ for (i = 0; i < mapsize; i++) {
+ fvalues[i] = (GLfloat) values[i];
+ }
+ }
+ else {
+ for (i = 0; i < mapsize; i++) {
+ fvalues[i] = UINT_TO_FLOAT(values[i]);
+ }
+ }
+ save_PixelMapfv(map, mapsize, fvalues);
+}
+
+
+static void GLAPIENTRY
+save_PixelMapusv(GLenum map, GLint mapsize, const GLushort *values)
+{
+ GLfloat fvalues[MAX_PIXEL_MAP_TABLE];
+ GLint i;
+ if (map == GL_PIXEL_MAP_I_TO_I || map == GL_PIXEL_MAP_S_TO_S) {
+ for (i = 0; i < mapsize; i++) {
+ fvalues[i] = (GLfloat) values[i];
+ }
+ }
+ else {
+ for (i = 0; i < mapsize; i++) {
+ fvalues[i] = USHORT_TO_FLOAT(values[i]);
+ }
+ }
+ save_PixelMapfv(map, mapsize, fvalues);
+}
+
+
+static void GLAPIENTRY
+save_PixelTransferf(GLenum pname, GLfloat param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PIXEL_TRANSFER, 2);
+ if (n) {
+ n[1].e = pname;
+ n[2].f = param;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PixelTransferf(ctx->Exec, (pname, param));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PixelTransferi(GLenum pname, GLint param)
+{
+ save_PixelTransferf(pname, (GLfloat) param);
+}
+
+
+static void GLAPIENTRY
+save_PixelZoom(GLfloat xfactor, GLfloat yfactor)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PIXEL_ZOOM, 2);
+ if (n) {
+ n[1].f = xfactor;
+ n[2].f = yfactor;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PixelZoom(ctx->Exec, (xfactor, yfactor));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PointParameterfvEXT(GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_POINT_PARAMETERS, 4);
+ if (n) {
+ n[1].e = pname;
+ n[2].f = params[0];
+ n[3].f = params[1];
+ n[4].f = params[2];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PointParameterfvEXT(ctx->Exec, (pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PointParameterfEXT(GLenum pname, GLfloat param)
+{
+ GLfloat parray[3];
+ parray[0] = param;
+ parray[1] = parray[2] = 0.0F;
+ save_PointParameterfvEXT(pname, parray);
+}
+
+static void GLAPIENTRY
+save_PointParameteriNV(GLenum pname, GLint param)
+{
+ GLfloat parray[3];
+ parray[0] = (GLfloat) param;
+ parray[1] = parray[2] = 0.0F;
+ save_PointParameterfvEXT(pname, parray);
+}
+
+static void GLAPIENTRY
+save_PointParameterivNV(GLenum pname, const GLint * param)
+{
+ GLfloat parray[3];
+ parray[0] = (GLfloat) param[0];
+ parray[1] = parray[2] = 0.0F;
+ save_PointParameterfvEXT(pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_PointSize(GLfloat size)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_POINT_SIZE, 1);
+ if (n) {
+ n[1].f = size;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PointSize(ctx->Exec, (size));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PolygonMode(GLenum face, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_POLYGON_MODE, 2);
+ if (n) {
+ n[1].e = face;
+ n[2].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PolygonMode(ctx->Exec, (face, mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PolygonStipple(const GLubyte * pattern)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_POLYGON_STIPPLE, 1);
+ if (n) {
+ n[1].data = unpack_image(ctx, 2, 32, 32, 1, GL_COLOR_INDEX, GL_BITMAP,
+ pattern, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PolygonStipple(ctx->Exec, ((GLubyte *) pattern));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PolygonOffset(GLfloat factor, GLfloat units)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_POLYGON_OFFSET, 2);
+ if (n) {
+ n[1].f = factor;
+ n[2].f = units;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PolygonOffset(ctx->Exec, (factor, units));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PolygonOffsetEXT(GLfloat factor, GLfloat bias)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ /* XXX mult by DepthMaxF here??? */
+ save_PolygonOffset(factor, ctx->DrawBuffer->_DepthMaxF * bias);
+}
+
+
+static void GLAPIENTRY
+save_PopAttrib(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_POP_ATTRIB, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_PopAttrib(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_PopMatrix(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_POP_MATRIX, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_PopMatrix(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_PopName(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_POP_NAME, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_PopName(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_PrioritizeTextures(GLsizei num, const GLuint * textures,
+ const GLclampf * priorities)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint i;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ for (i = 0; i < num; i++) {
+ Node *n;
+ n = alloc_instruction(ctx, OPCODE_PRIORITIZE_TEXTURE, 2);
+ if (n) {
+ n[1].ui = textures[i];
+ n[2].f = priorities[i];
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PrioritizeTextures(ctx->Exec, (num, textures, priorities));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PushAttrib(GLbitfield mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PUSH_ATTRIB, 1);
+ if (n) {
+ n[1].bf = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PushAttrib(ctx->Exec, (mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_PushMatrix(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_PUSH_MATRIX, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_PushMatrix(ctx->Exec, ());
+ }
+}
+
+
+static void GLAPIENTRY
+save_PushName(GLuint name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PUSH_NAME, 1);
+ if (n) {
+ n[1].ui = name;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PushName(ctx->Exec, (name));
+ }
+}
+
+
+static void GLAPIENTRY
+save_RasterPos4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_RASTER_POS, 4);
+ if (n) {
+ n[1].f = x;
+ n[2].f = y;
+ n[3].f = z;
+ n[4].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_RasterPos4f(ctx->Exec, (x, y, z, w));
+ }
+}
+
+static void GLAPIENTRY
+save_RasterPos2d(GLdouble x, GLdouble y)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2f(GLfloat x, GLfloat y)
+{
+ save_RasterPos4f(x, y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2i(GLint x, GLint y)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2s(GLshort x, GLshort y)
+{
+ save_RasterPos4f(x, y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3d(GLdouble x, GLdouble y, GLdouble z)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_RasterPos4f(x, y, z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3i(GLint x, GLint y, GLint z)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3s(GLshort x, GLshort y, GLshort z)
+{
+ save_RasterPos4f(x, y, z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos4d(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
+}
+
+static void GLAPIENTRY
+save_RasterPos4i(GLint x, GLint y, GLint z, GLint w)
+{
+ save_RasterPos4f((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
+}
+
+static void GLAPIENTRY
+save_RasterPos4s(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ save_RasterPos4f(x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_RasterPos2dv(const GLdouble * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2fv(const GLfloat * v)
+{
+ save_RasterPos4f(v[0], v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2iv(const GLint * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos2sv(const GLshort * v)
+{
+ save_RasterPos4f(v[0], v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3dv(const GLdouble * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3fv(const GLfloat * v)
+{
+ save_RasterPos4f(v[0], v[1], v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3iv(const GLint * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos3sv(const GLshort * v)
+{
+ save_RasterPos4f(v[0], v[1], v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_RasterPos4dv(const GLdouble * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1],
+ (GLfloat) v[2], (GLfloat) v[3]);
+}
+
+static void GLAPIENTRY
+save_RasterPos4fv(const GLfloat * v)
+{
+ save_RasterPos4f(v[0], v[1], v[2], v[3]);
+}
+
+static void GLAPIENTRY
+save_RasterPos4iv(const GLint * v)
+{
+ save_RasterPos4f((GLfloat) v[0], (GLfloat) v[1],
+ (GLfloat) v[2], (GLfloat) v[3]);
+}
+
+static void GLAPIENTRY
+save_RasterPos4sv(const GLshort * v)
+{
+ save_RasterPos4f(v[0], v[1], v[2], v[3]);
+}
+
+
+static void GLAPIENTRY
+save_PassThrough(GLfloat token)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PASSTHROUGH, 1);
+ if (n) {
+ n[1].f = token;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_PassThrough(ctx->Exec, (token));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ReadBuffer(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_READ_BUFFER, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ReadBuffer(ctx->Exec, (mode));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ResetHistogram(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_RESET_HISTOGRAM, 1);
+ if (n) {
+ n[1].e = target;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ResetHistogram(ctx->Exec, (target));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ResetMinmax(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_RESET_MIN_MAX, 1);
+ if (n) {
+ n[1].e = target;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ResetMinmax(ctx->Exec, (target));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Rotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ROTATE, 4);
+ if (n) {
+ n[1].f = angle;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Rotatef(ctx->Exec, (angle, x, y, z));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z)
+{
+ save_Rotatef((GLfloat) angle, (GLfloat) x, (GLfloat) y, (GLfloat) z);
+}
+
+
+static void GLAPIENTRY
+save_Scalef(GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_SCALE, 3);
+ if (n) {
+ n[1].f = x;
+ n[2].f = y;
+ n[3].f = z;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Scalef(ctx->Exec, (x, y, z));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Scaled(GLdouble x, GLdouble y, GLdouble z)
+{
+ save_Scalef((GLfloat) x, (GLfloat) y, (GLfloat) z);
+}
+
+
+static void GLAPIENTRY
+save_Scissor(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_SCISSOR, 4);
+ if (n) {
+ n[1].i = x;
+ n[2].i = y;
+ n[3].i = width;
+ n[4].i = height;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Scissor(ctx->Exec, (x, y, width, height));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ShadeModel(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END(ctx);
+
+ if (ctx->ExecuteFlag) {
+ CALL_ShadeModel(ctx->Exec, (mode));
+ }
+
+ if (ctx->ListState.Current.ShadeModel == mode)
+ return;
+
+ SAVE_FLUSH_VERTICES(ctx);
+
+ /* Only save the value if we know the statechange will take effect:
+ */
+ if (ctx->Driver.CurrentSavePrimitive == PRIM_OUTSIDE_BEGIN_END)
+ ctx->ListState.Current.ShadeModel = mode;
+
+ n = alloc_instruction(ctx, OPCODE_SHADE_MODEL, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilFunc(GLenum func, GLint ref, GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC, 3);
+ if (n) {
+ n[1].e = func;
+ n[2].i = ref;
+ n[3].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilFunc(ctx->Exec, (func, ref, mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilMask(GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_MASK, 1);
+ if (n) {
+ n[1].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilMask(ctx->Exec, (mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_OP, 3);
+ if (n) {
+ n[1].e = fail;
+ n[2].e = zfail;
+ n[3].e = zpass;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilOp(ctx->Exec, (fail, zfail, zpass));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
+ if (n) {
+ n[1].e = face;
+ n[2].e = func;
+ n[3].i = ref;
+ n[4].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilFuncSeparate(ctx->Exec, (face, func, ref, mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, GLint ref,
+ GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ /* GL_FRONT */
+ n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
+ if (n) {
+ n[1].e = GL_FRONT;
+ n[2].e = frontfunc;
+ n[3].i = ref;
+ n[4].ui = mask;
+ }
+ /* GL_BACK */
+ n = alloc_instruction(ctx, OPCODE_STENCIL_FUNC_SEPARATE, 4);
+ if (n) {
+ n[1].e = GL_BACK;
+ n[2].e = backfunc;
+ n[3].i = ref;
+ n[4].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilFuncSeparate(ctx->Exec, (GL_FRONT, frontfunc, ref, mask));
+ CALL_StencilFuncSeparate(ctx->Exec, (GL_BACK, backfunc, ref, mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilMaskSeparate(GLenum face, GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_MASK_SEPARATE, 2);
+ if (n) {
+ n[1].e = face;
+ n[2].ui = mask;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilMaskSeparate(ctx->Exec, (face, mask));
+ }
+}
+
+
+static void GLAPIENTRY
+save_StencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_STENCIL_OP_SEPARATE, 4);
+ if (n) {
+ n[1].e = face;
+ n[2].e = fail;
+ n[3].e = zfail;
+ n[4].e = zpass;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_StencilOpSeparate(ctx->Exec, (face, fail, zfail, zpass));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexEnvfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEXENV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ if (pname == GL_TEXTURE_ENV_COLOR) {
+ n[3].f = params[0];
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ else {
+ n[3].f = params[0];
+ n[4].f = n[5].f = n[6].f = 0.0F;
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexEnvfv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexEnvf(GLenum target, GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = (GLfloat) param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_TexEnvfv(target, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_TexEnvi(GLenum target, GLenum pname, GLint param)
+{
+ GLfloat p[4];
+ p[0] = (GLfloat) param;
+ p[1] = p[2] = p[3] = 0.0F;
+ save_TexEnvfv(target, pname, p);
+}
+
+
+static void GLAPIENTRY
+save_TexEnviv(GLenum target, GLenum pname, const GLint * param)
+{
+ GLfloat p[4];
+ if (pname == GL_TEXTURE_ENV_COLOR) {
+ p[0] = INT_TO_FLOAT(param[0]);
+ p[1] = INT_TO_FLOAT(param[1]);
+ p[2] = INT_TO_FLOAT(param[2]);
+ p[3] = INT_TO_FLOAT(param[3]);
+ }
+ else {
+ p[0] = (GLfloat) param[0];
+ p[1] = p[2] = p[3] = 0.0F;
+ }
+ save_TexEnvfv(target, pname, p);
+}
+
+
+static void GLAPIENTRY
+save_TexGenfv(GLenum coord, GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEXGEN, 6);
+ if (n) {
+ n[1].e = coord;
+ n[2].e = pname;
+ n[3].f = params[0];
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexGenfv(ctx->Exec, (coord, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexGeniv(GLenum coord, GLenum pname, const GLint *params)
+{
+ GLfloat p[4];
+ p[0] = (GLfloat) params[0];
+ p[1] = (GLfloat) params[1];
+ p[2] = (GLfloat) params[2];
+ p[3] = (GLfloat) params[3];
+ save_TexGenfv(coord, pname, p);
+}
+
+
+static void GLAPIENTRY
+save_TexGend(GLenum coord, GLenum pname, GLdouble param)
+{
+ GLfloat parray[4];
+ parray[0] = (GLfloat) param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_TexGenfv(coord, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_TexGendv(GLenum coord, GLenum pname, const GLdouble *params)
+{
+ GLfloat p[4];
+ p[0] = (GLfloat) params[0];
+ p[1] = (GLfloat) params[1];
+ p[2] = (GLfloat) params[2];
+ p[3] = (GLfloat) params[3];
+ save_TexGenfv(coord, pname, p);
+}
+
+
+static void GLAPIENTRY
+save_TexGenf(GLenum coord, GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_TexGenfv(coord, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_TexGeni(GLenum coord, GLenum pname, GLint param)
+{
+ GLint parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0;
+ save_TexGeniv(coord, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_TexParameterfv(GLenum target, GLenum pname, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEXPARAMETER, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].f = params[0];
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexParameterfv(ctx->Exec, (target, pname, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexParameterf(GLenum target, GLenum pname, GLfloat param)
+{
+ GLfloat parray[4];
+ parray[0] = param;
+ parray[1] = parray[2] = parray[3] = 0.0F;
+ save_TexParameterfv(target, pname, parray);
+}
+
+
+static void GLAPIENTRY
+save_TexParameteri(GLenum target, GLenum pname, GLint param)
+{
+ GLfloat fparam[4];
+ fparam[0] = (GLfloat) param;
+ fparam[1] = fparam[2] = fparam[3] = 0.0F;
+ save_TexParameterfv(target, pname, fparam);
+}
+
+
+static void GLAPIENTRY
+save_TexParameteriv(GLenum target, GLenum pname, const GLint *params)
+{
+ GLfloat fparam[4];
+ fparam[0] = (GLfloat) params[0];
+ fparam[1] = fparam[2] = fparam[3] = 0.0F;
+ save_TexParameterfv(target, pname, fparam);
+}
+
+
+static void GLAPIENTRY
+save_TexImage1D(GLenum target,
+ GLint level, GLint components,
+ GLsizei width, GLint border,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_1D) {
+ /* don't compile, execute immediately */
+ CALL_TexImage1D(ctx->Exec, (target, level, components, width,
+ border, format, type, pixels));
+ }
+ else {
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEX_IMAGE1D, 8);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = components;
+ n[4].i = (GLint) width;
+ n[5].i = border;
+ n[6].e = format;
+ n[7].e = type;
+ n[8].data = unpack_image(ctx, 1, width, 1, 1, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexImage1D(ctx->Exec, (target, level, components, width,
+ border, format, type, pixels));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexImage2D(GLenum target,
+ GLint level, GLint components,
+ GLsizei width, GLsizei height, GLint border,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_2D) {
+ /* don't compile, execute immediately */
+ CALL_TexImage2D(ctx->Exec, (target, level, components, width,
+ height, border, format, type, pixels));
+ }
+ else {
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEX_IMAGE2D, 9);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = components;
+ n[4].i = (GLint) width;
+ n[5].i = (GLint) height;
+ n[6].i = border;
+ n[7].e = format;
+ n[8].e = type;
+ n[9].data = unpack_image(ctx, 2, width, height, 1, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexImage2D(ctx->Exec, (target, level, components, width,
+ height, border, format, type, pixels));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexImage3D(GLenum target,
+ GLint level, GLint internalFormat,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLint border,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_3D) {
+ /* don't compile, execute immediately */
+ CALL_TexImage3D(ctx->Exec, (target, level, internalFormat, width,
+ height, depth, border, format, type,
+ pixels));
+ }
+ else {
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEX_IMAGE3D, 10);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = (GLint) internalFormat;
+ n[4].i = (GLint) width;
+ n[5].i = (GLint) height;
+ n[6].i = (GLint) depth;
+ n[7].i = border;
+ n[8].e = format;
+ n[9].e = type;
+ n[10].data = unpack_image(ctx, 3, width, height, depth, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexImage3D(ctx->Exec, (target, level, internalFormat, width,
+ height, depth, border, format, type,
+ pixels));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexSubImage1D(GLenum target, GLint level, GLint xoffset,
+ GLsizei width, GLenum format, GLenum type,
+ const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE1D, 7);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = (GLint) width;
+ n[5].e = format;
+ n[6].e = type;
+ n[7].data = unpack_image(ctx, 1, width, 1, 1, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexSubImage1D(ctx->Exec, (target, level, xoffset, width,
+ format, type, pixels));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexSubImage2D(GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLsizei width, GLsizei height,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE2D, 9);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = (GLint) width;
+ n[6].i = (GLint) height;
+ n[7].e = format;
+ n[8].e = type;
+ n[9].data = unpack_image(ctx, 2, width, height, 1, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexSubImage2D(ctx->Exec, (target, level, xoffset, yoffset,
+ width, height, format, type, pixels));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TexSubImage3D(GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_TEX_SUB_IMAGE3D, 11);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = zoffset;
+ n[6].i = (GLint) width;
+ n[7].i = (GLint) height;
+ n[8].i = (GLint) depth;
+ n[9].e = format;
+ n[10].e = type;
+ n[11].data = unpack_image(ctx, 3, width, height, depth, format, type,
+ pixels, &ctx->Unpack);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexSubImage3D(ctx->Exec, (target, level,
+ xoffset, yoffset, zoffset,
+ width, height, depth, format, type,
+ pixels));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Translatef(GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TRANSLATE, 3);
+ if (n) {
+ n[1].f = x;
+ n[2].f = y;
+ n[3].f = z;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Translatef(ctx->Exec, (x, y, z));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Translated(GLdouble x, GLdouble y, GLdouble z)
+{
+ save_Translatef((GLfloat) x, (GLfloat) y, (GLfloat) z);
+}
+
+
+
+static void GLAPIENTRY
+save_Viewport(GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_VIEWPORT, 4);
+ if (n) {
+ n[1].i = x;
+ n[2].i = y;
+ n[3].i = (GLint) width;
+ n[4].i = (GLint) height;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Viewport(ctx->Exec, (x, y, width, height));
+ }
+}
+
+
+static void GLAPIENTRY
+save_WindowPos4fMESA(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_WINDOW_POS, 4);
+ if (n) {
+ n[1].f = x;
+ n[2].f = y;
+ n[3].f = z;
+ n[4].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_WindowPos4fMESA(ctx->Exec, (x, y, z, w));
+ }
+}
+
+static void GLAPIENTRY
+save_WindowPos2dMESA(GLdouble x, GLdouble y)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2fMESA(GLfloat x, GLfloat y)
+{
+ save_WindowPos4fMESA(x, y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2iMESA(GLint x, GLint y)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2sMESA(GLshort x, GLshort y)
+{
+ save_WindowPos4fMESA(x, y, 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3dMESA(GLdouble x, GLdouble y, GLdouble z)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3fMESA(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_WindowPos4fMESA(x, y, z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3iMESA(GLint x, GLint y, GLint z)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3sMESA(GLshort x, GLshort y, GLshort z)
+{
+ save_WindowPos4fMESA(x, y, z, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos4dMESA(GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
+}
+
+static void GLAPIENTRY
+save_WindowPos4iMESA(GLint x, GLint y, GLint z, GLint w)
+{
+ save_WindowPos4fMESA((GLfloat) x, (GLfloat) y, (GLfloat) z, (GLfloat) w);
+}
+
+static void GLAPIENTRY
+save_WindowPos4sMESA(GLshort x, GLshort y, GLshort z, GLshort w)
+{
+ save_WindowPos4fMESA(x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_WindowPos2dvMESA(const GLdouble * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2fvMESA(const GLfloat * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2ivMESA(const GLint * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos2svMESA(const GLshort * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], 0.0F, 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3dvMESA(const GLdouble * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3fvMESA(const GLfloat * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3ivMESA(const GLint * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1], (GLfloat) v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos3svMESA(const GLshort * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], v[2], 1.0F);
+}
+
+static void GLAPIENTRY
+save_WindowPos4dvMESA(const GLdouble * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1],
+ (GLfloat) v[2], (GLfloat) v[3]);
+}
+
+static void GLAPIENTRY
+save_WindowPos4fvMESA(const GLfloat * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], v[2], v[3]);
+}
+
+static void GLAPIENTRY
+save_WindowPos4ivMESA(const GLint * v)
+{
+ save_WindowPos4fMESA((GLfloat) v[0], (GLfloat) v[1],
+ (GLfloat) v[2], (GLfloat) v[3]);
+}
+
+static void GLAPIENTRY
+save_WindowPos4svMESA(const GLshort * v)
+{
+ save_WindowPos4fMESA(v[0], v[1], v[2], v[3]);
+}
+
+
+
+/* GL_ARB_multitexture */
+static void GLAPIENTRY
+save_ActiveTextureARB(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ACTIVE_TEXTURE, 1);
+ if (n) {
+ n[1].e = target;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ActiveTextureARB(ctx->Exec, (target));
+ }
+}
+
+
+/* GL_ARB_transpose_matrix */
+
+static void GLAPIENTRY
+save_LoadTransposeMatrixdARB(const GLdouble m[16])
+{
+ GLfloat tm[16];
+ _math_transposefd(tm, m);
+ save_LoadMatrixf(tm);
+}
+
+
+static void GLAPIENTRY
+save_LoadTransposeMatrixfARB(const GLfloat m[16])
+{
+ GLfloat tm[16];
+ _math_transposef(tm, m);
+ save_LoadMatrixf(tm);
+}
+
+
+static void GLAPIENTRY
+save_MultTransposeMatrixdARB(const GLdouble m[16])
+{
+ GLfloat tm[16];
+ _math_transposefd(tm, m);
+ save_MultMatrixf(tm);
+}
+
+
+static void GLAPIENTRY
+save_MultTransposeMatrixfARB(const GLfloat m[16])
+{
+ GLfloat tm[16];
+ _math_transposef(tm, m);
+ save_MultMatrixf(tm);
+}
+
+
+/* GL_ARB_texture_compression */
+static void GLAPIENTRY
+save_CompressedTexImage1DARB(GLenum target, GLint level,
+ GLenum internalFormat, GLsizei width,
+ GLint border, GLsizei imageSize,
+ const GLvoid * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_1D) {
+ /* don't compile, execute immediately */
+ CALL_CompressedTexImage1DARB(ctx->Exec, (target, level, internalFormat,
+ width, border, imageSize,
+ data));
+ }
+ else {
+ Node *n;
+ GLvoid *image;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage1DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_1D, 7);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].e = internalFormat;
+ n[4].i = (GLint) width;
+ n[5].i = border;
+ n[6].i = imageSize;
+ n[7].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexImage1DARB(ctx->Exec,
+ (target, level, internalFormat, width,
+ border, imageSize, data));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_CompressedTexImage2DARB(GLenum target, GLint level,
+ GLenum internalFormat, GLsizei width,
+ GLsizei height, GLint border, GLsizei imageSize,
+ const GLvoid * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_2D) {
+ /* don't compile, execute immediately */
+ CALL_CompressedTexImage2DARB(ctx->Exec, (target, level, internalFormat,
+ width, height, border,
+ imageSize, data));
+ }
+ else {
+ Node *n;
+ GLvoid *image;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage2DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_2D, 8);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].e = internalFormat;
+ n[4].i = (GLint) width;
+ n[5].i = (GLint) height;
+ n[6].i = border;
+ n[7].i = imageSize;
+ n[8].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexImage2DARB(ctx->Exec,
+ (target, level, internalFormat, width,
+ height, border, imageSize, data));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_CompressedTexImage3DARB(GLenum target, GLint level,
+ GLenum internalFormat, GLsizei width,
+ GLsizei height, GLsizei depth, GLint border,
+ GLsizei imageSize, const GLvoid * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (target == GL_PROXY_TEXTURE_3D) {
+ /* don't compile, execute immediately */
+ CALL_CompressedTexImage3DARB(ctx->Exec, (target, level, internalFormat,
+ width, height, depth, border,
+ imageSize, data));
+ }
+ else {
+ Node *n;
+ GLvoid *image;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexImage3DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_IMAGE_3D, 9);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].e = internalFormat;
+ n[4].i = (GLint) width;
+ n[5].i = (GLint) height;
+ n[6].i = (GLint) depth;
+ n[7].i = border;
+ n[8].i = imageSize;
+ n[9].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexImage3DARB(ctx->Exec,
+ (target, level, internalFormat, width,
+ height, depth, border, imageSize,
+ data));
+ }
+ }
+}
+
+
+static void GLAPIENTRY
+save_CompressedTexSubImage1DARB(GLenum target, GLint level, GLint xoffset,
+ GLsizei width, GLenum format,
+ GLsizei imageSize, const GLvoid * data)
+{
+ Node *n;
+ GLvoid *image;
+
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage1DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D, 7);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = (GLint) width;
+ n[5].e = format;
+ n[6].i = imageSize;
+ n[7].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexSubImage1DARB(ctx->Exec, (target, level, xoffset,
+ width, format, imageSize,
+ data));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CompressedTexSubImage2DARB(GLenum target, GLint level, GLint xoffset,
+ GLint yoffset, GLsizei width, GLsizei height,
+ GLenum format, GLsizei imageSize,
+ const GLvoid * data)
+{
+ Node *n;
+ GLvoid *image;
+
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage2DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D, 9);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = (GLint) width;
+ n[6].i = (GLint) height;
+ n[7].e = format;
+ n[8].i = imageSize;
+ n[9].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexSubImage2DARB(ctx->Exec,
+ (target, level, xoffset, yoffset, width,
+ height, format, imageSize, data));
+ }
+}
+
+
+static void GLAPIENTRY
+save_CompressedTexSubImage3DARB(GLenum target, GLint level, GLint xoffset,
+ GLint yoffset, GLint zoffset, GLsizei width,
+ GLsizei height, GLsizei depth, GLenum format,
+ GLsizei imageSize, const GLvoid * data)
+{
+ Node *n;
+ GLvoid *image;
+
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ /* make copy of image */
+ image = malloc(imageSize);
+ if (!image) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage3DARB");
+ return;
+ }
+ memcpy(image, data, imageSize);
+ n = alloc_instruction(ctx, OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D, 11);
+ if (n) {
+ n[1].e = target;
+ n[2].i = level;
+ n[3].i = xoffset;
+ n[4].i = yoffset;
+ n[5].i = zoffset;
+ n[6].i = (GLint) width;
+ n[7].i = (GLint) height;
+ n[8].i = (GLint) depth;
+ n[9].e = format;
+ n[10].i = imageSize;
+ n[11].data = image;
+ }
+ else if (image) {
+ free(image);
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_CompressedTexSubImage3DARB(ctx->Exec,
+ (target, level, xoffset, yoffset,
+ zoffset, width, height, depth, format,
+ imageSize, data));
+ }
+}
+
+
+/* GL_ARB_multisample */
+static void GLAPIENTRY
+save_SampleCoverageARB(GLclampf value, GLboolean invert)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_SAMPLE_COVERAGE, 2);
+ if (n) {
+ n[1].f = value;
+ n[2].b = invert;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_SampleCoverageARB(ctx->Exec, (value, invert));
+ }
+}
+
+
+/*
+ * GL_NV_vertex_program
+ */
+#if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+static void GLAPIENTRY
+save_BindProgramNV(GLenum target, GLuint id)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BIND_PROGRAM_NV, 2);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = id;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BindProgramNV(ctx->Exec, (target, id));
+ }
+}
+
+static void GLAPIENTRY
+save_ProgramEnvParameter4fARB(GLenum target, GLuint index,
+ GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_ENV_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = x;
+ n[4].f = y;
+ n[5].f = z;
+ n[6].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramEnvParameter4fARB(ctx->Exec, (target, index, x, y, z, w));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramEnvParameter4fvARB(GLenum target, GLuint index,
+ const GLfloat *params)
+{
+ save_ProgramEnvParameter4fARB(target, index, params[0], params[1],
+ params[2], params[3]);
+}
+
+
+static void GLAPIENTRY
+save_ProgramEnvParameters4fvEXT(GLenum target, GLuint index, GLsizei count,
+ const GLfloat * params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ if (count > 0) {
+ GLint i;
+ const GLfloat * p = params;
+
+ for (i = 0 ; i < count ; i++) {
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_ENV_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = p[0];
+ n[4].f = p[1];
+ n[5].f = p[2];
+ n[6].f = p[3];
+ p += 4;
+ }
+ }
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramEnvParameters4fvEXT(ctx->Exec, (target, index, count, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramEnvParameter4dARB(GLenum target, GLuint index,
+ GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ save_ProgramEnvParameter4fARB(target, index,
+ (GLfloat) x,
+ (GLfloat) y, (GLfloat) z, (GLfloat) w);
+}
+
+
+static void GLAPIENTRY
+save_ProgramEnvParameter4dvARB(GLenum target, GLuint index,
+ const GLdouble *params)
+{
+ save_ProgramEnvParameter4fARB(target, index,
+ (GLfloat) params[0],
+ (GLfloat) params[1],
+ (GLfloat) params[2], (GLfloat) params[3]);
+}
+
+#endif /* FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program || FEATURE_NV_vertex_program */
+
+#if FEATURE_NV_vertex_program
+static void GLAPIENTRY
+save_ExecuteProgramNV(GLenum target, GLuint id, const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_EXECUTE_PROGRAM_NV, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = id;
+ n[3].f = params[0];
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ExecuteProgramNV(ctx->Exec, (target, id, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramParameters4dvNV(GLenum target, GLuint index,
+ GLsizei num, const GLdouble *params)
+{
+ GLint i;
+ for (i = 0; i < num; i++) {
+ save_ProgramEnvParameter4dvARB(target, index + i, params + 4 * i);
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramParameters4fvNV(GLenum target, GLuint index,
+ GLsizei num, const GLfloat *params)
+{
+ GLint i;
+ for (i = 0; i < num; i++) {
+ save_ProgramEnvParameter4fvARB(target, index + i, params + 4 * i);
+ }
+}
+
+
+static void GLAPIENTRY
+save_LoadProgramNV(GLenum target, GLuint id, GLsizei len,
+ const GLubyte * program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_LOAD_PROGRAM_NV, 4);
+ if (n) {
+ GLubyte *programCopy = (GLubyte *) malloc(len);
+ if (!programCopy) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glLoadProgramNV");
+ return;
+ }
+ memcpy(programCopy, program, len);
+ n[1].e = target;
+ n[2].ui = id;
+ n[3].i = len;
+ n[4].data = programCopy;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_LoadProgramNV(ctx->Exec, (target, id, len, program));
+ }
+}
+
+
+static void GLAPIENTRY
+save_RequestResidentProgramsNV(GLsizei num, const GLuint * ids)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_TRACK_MATRIX_NV, 2);
+ if (n) {
+ GLuint *idCopy = (GLuint *) malloc(num * sizeof(GLuint));
+ if (!idCopy) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glRequestResidentProgramsNV");
+ return;
+ }
+ memcpy(idCopy, ids, num * sizeof(GLuint));
+ n[1].i = num;
+ n[2].data = idCopy;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_RequestResidentProgramsNV(ctx->Exec, (num, ids));
+ }
+}
+
+
+static void GLAPIENTRY
+save_TrackMatrixNV(GLenum target, GLuint address,
+ GLenum matrix, GLenum transform)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TRACK_MATRIX_NV, 4);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = address;
+ n[3].e = matrix;
+ n[4].e = transform;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TrackMatrixNV(ctx->Exec, (target, address, matrix, transform));
+ }
+}
+#endif /* FEATURE_NV_vertex_program */
+
+
+/*
+ * GL_NV_fragment_program
+ */
+#if FEATURE_NV_fragment_program
+static void GLAPIENTRY
+save_ProgramLocalParameter4fARB(GLenum target, GLuint index,
+ GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = x;
+ n[4].f = y;
+ n[5].f = z;
+ n[6].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramLocalParameter4fARB(ctx->Exec, (target, index, x, y, z, w));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramLocalParameter4fvARB(GLenum target, GLuint index,
+ const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = params[0];
+ n[4].f = params[1];
+ n[5].f = params[2];
+ n[6].f = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramLocalParameter4fvARB(ctx->Exec, (target, index, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramLocalParameters4fvEXT(GLenum target, GLuint index, GLsizei count,
+ const GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ if (count > 0) {
+ GLint i;
+ const GLfloat * p = params;
+
+ for (i = 0 ; i < count ; i++) {
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = p[0];
+ n[4].f = p[1];
+ n[5].f = p[2];
+ n[6].f = p[3];
+ p += 4;
+ }
+ }
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramLocalParameters4fvEXT(ctx->Exec, (target, index, count, params));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramLocalParameter4dARB(GLenum target, GLuint index,
+ GLdouble x, GLdouble y,
+ GLdouble z, GLdouble w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = (GLfloat) x;
+ n[4].f = (GLfloat) y;
+ n[5].f = (GLfloat) z;
+ n[6].f = (GLfloat) w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramLocalParameter4dARB(ctx->Exec, (target, index, x, y, z, w));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramLocalParameter4dvARB(GLenum target, GLuint index,
+ const GLdouble *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_LOCAL_PARAMETER_ARB, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = index;
+ n[3].f = (GLfloat) params[0];
+ n[4].f = (GLfloat) params[1];
+ n[5].f = (GLfloat) params[2];
+ n[6].f = (GLfloat) params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramLocalParameter4dvARB(ctx->Exec, (target, index, params));
+ }
+}
+
+static void GLAPIENTRY
+save_ProgramNamedParameter4fNV(GLuint id, GLsizei len, const GLubyte * name,
+ GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_NAMED_PARAMETER_NV, 6);
+ if (n) {
+ GLubyte *nameCopy = (GLubyte *) malloc(len);
+ if (!nameCopy) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glProgramNamedParameter4fNV");
+ return;
+ }
+ memcpy(nameCopy, name, len);
+ n[1].ui = id;
+ n[2].i = len;
+ n[3].data = nameCopy;
+ n[4].f = x;
+ n[5].f = y;
+ n[6].f = z;
+ n[7].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramNamedParameter4fNV(ctx->Exec, (id, len, name, x, y, z, w));
+ }
+}
+
+
+static void GLAPIENTRY
+save_ProgramNamedParameter4fvNV(GLuint id, GLsizei len, const GLubyte * name,
+ const float v[])
+{
+ save_ProgramNamedParameter4fNV(id, len, name, v[0], v[1], v[2], v[3]);
+}
+
+
+static void GLAPIENTRY
+save_ProgramNamedParameter4dNV(GLuint id, GLsizei len, const GLubyte * name,
+ GLdouble x, GLdouble y, GLdouble z, GLdouble w)
+{
+ save_ProgramNamedParameter4fNV(id, len, name, (GLfloat) x, (GLfloat) y,
+ (GLfloat) z, (GLfloat) w);
+}
+
+
+static void GLAPIENTRY
+save_ProgramNamedParameter4dvNV(GLuint id, GLsizei len, const GLubyte * name,
+ const double v[])
+{
+ save_ProgramNamedParameter4fNV(id, len, name, (GLfloat) v[0],
+ (GLfloat) v[1], (GLfloat) v[2],
+ (GLfloat) v[3]);
+}
+
+#endif /* FEATURE_NV_fragment_program */
+
+
+
+/* GL_EXT_stencil_two_side */
+static void GLAPIENTRY
+save_ActiveStencilFaceEXT(GLenum face)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ACTIVE_STENCIL_FACE_EXT, 1);
+ if (n) {
+ n[1].e = face;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ActiveStencilFaceEXT(ctx->Exec, (face));
+ }
+}
+
+
+/* GL_EXT_depth_bounds_test */
+static void GLAPIENTRY
+save_DepthBoundsEXT(GLclampd zmin, GLclampd zmax)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DEPTH_BOUNDS_EXT, 2);
+ if (n) {
+ n[1].f = (GLfloat) zmin;
+ n[2].f = (GLfloat) zmax;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DepthBoundsEXT(ctx->Exec, (zmin, zmax));
+ }
+}
+
+
+
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+
+static void GLAPIENTRY
+save_ProgramStringARB(GLenum target, GLenum format, GLsizei len,
+ const GLvoid * string)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_PROGRAM_STRING_ARB, 4);
+ if (n) {
+ GLubyte *programCopy = (GLubyte *) malloc(len);
+ if (!programCopy) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glProgramStringARB");
+ return;
+ }
+ memcpy(programCopy, string, len);
+ n[1].e = target;
+ n[2].e = format;
+ n[3].i = len;
+ n[4].data = programCopy;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ProgramStringARB(ctx->Exec, (target, format, len, string));
+ }
+}
+
+#endif /* FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program */
+
+
+#if FEATURE_queryobj
+
+static void GLAPIENTRY
+save_BeginQueryARB(GLenum target, GLuint id)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BEGIN_QUERY_ARB, 2);
+ if (n) {
+ n[1].e = target;
+ n[2].ui = id;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BeginQueryARB(ctx->Exec, (target, id));
+ }
+}
+
+
+static void GLAPIENTRY
+save_EndQueryARB(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_END_QUERY_ARB, 1);
+ if (n) {
+ n[1].e = target;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EndQueryARB(ctx->Exec, (target));
+ }
+}
+
+#endif /* FEATURE_queryobj */
+
+
+static void GLAPIENTRY
+save_DrawBuffersARB(GLsizei count, const GLenum * buffers)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_DRAW_BUFFERS_ARB, 1 + MAX_DRAW_BUFFERS);
+ if (n) {
+ GLint i;
+ n[1].i = count;
+ if (count > MAX_DRAW_BUFFERS)
+ count = MAX_DRAW_BUFFERS;
+ for (i = 0; i < count; i++) {
+ n[2 + i].e = buffers[i];
+ }
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_DrawBuffersARB(ctx->Exec, (count, buffers));
+ }
+}
+
+static void GLAPIENTRY
+save_TexBumpParameterfvATI(GLenum pname, const GLfloat *param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ n = alloc_instruction(ctx, OPCODE_TEX_BUMP_PARAMETER_ATI, 5);
+ if (n) {
+ n[1].ui = pname;
+ n[2].f = param[0];
+ n[3].f = param[1];
+ n[4].f = param[2];
+ n[5].f = param[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexBumpParameterfvATI(ctx->Exec, (pname, param));
+ }
+}
+
+static void GLAPIENTRY
+save_TexBumpParameterivATI(GLenum pname, const GLint *param)
+{
+ GLfloat p[4];
+ p[0] = INT_TO_FLOAT(param[0]);
+ p[1] = INT_TO_FLOAT(param[1]);
+ p[2] = INT_TO_FLOAT(param[2]);
+ p[3] = INT_TO_FLOAT(param[3]);
+ save_TexBumpParameterfvATI(pname, p);
+}
+
+#if FEATURE_ATI_fragment_shader
+static void GLAPIENTRY
+save_BindFragmentShaderATI(GLuint id)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ n = alloc_instruction(ctx, OPCODE_BIND_FRAGMENT_SHADER_ATI, 1);
+ if (n) {
+ n[1].ui = id;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BindFragmentShaderATI(ctx->Exec, (id));
+ }
+}
+
+static void GLAPIENTRY
+save_SetFragmentShaderConstantATI(GLuint dst, const GLfloat *value)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+
+ n = alloc_instruction(ctx, OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI, 5);
+ if (n) {
+ n[1].ui = dst;
+ n[2].f = value[0];
+ n[3].f = value[1];
+ n[4].f = value[2];
+ n[5].f = value[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_SetFragmentShaderConstantATI(ctx->Exec, (dst, value));
+ }
+}
+#endif
+
+static void
+save_Attr1fNV(GLenum attr, GLfloat x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_1F_NV, 2);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 1;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, 0, 0, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib1fNV(ctx->Exec, (attr, x));
+ }
+}
+
+static void
+save_Attr2fNV(GLenum attr, GLfloat x, GLfloat y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_2F_NV, 3);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 2;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, 0, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib2fNV(ctx->Exec, (attr, x, y));
+ }
+}
+
+static void
+save_Attr3fNV(GLenum attr, GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_3F_NV, 4);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 3;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib3fNV(ctx->Exec, (attr, x, y, z));
+ }
+}
+
+static void
+save_Attr4fNV(GLenum attr, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_4F_NV, 5);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ n[5].f = w;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 4;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, w);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib4fNV(ctx->Exec, (attr, x, y, z, w));
+ }
+}
+
+
+static void
+save_Attr1fARB(GLenum attr, GLfloat x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_1F_ARB, 2);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 1;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, 0, 0, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib1fARB(ctx->Exec, (attr, x));
+ }
+}
+
+static void
+save_Attr2fARB(GLenum attr, GLfloat x, GLfloat y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_2F_ARB, 3);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 2;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, 0, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib2fARB(ctx->Exec, (attr, x, y));
+ }
+}
+
+static void
+save_Attr3fARB(GLenum attr, GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_3F_ARB, 4);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 3;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, 1);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib3fARB(ctx->Exec, (attr, x, y, z));
+ }
+}
+
+static void
+save_Attr4fARB(GLenum attr, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_ATTR_4F_ARB, 5);
+ if (n) {
+ n[1].e = attr;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ n[5].f = w;
+ }
+
+ ASSERT(attr < MAX_VERTEX_GENERIC_ATTRIBS);
+ ctx->ListState.ActiveAttribSize[attr] = 4;
+ ASSIGN_4V(ctx->ListState.CurrentAttrib[attr], x, y, z, w);
+
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttrib4fARB(ctx->Exec, (attr, x, y, z, w));
+ }
+}
+
+
+static void GLAPIENTRY
+save_EvalCoord1f(GLfloat x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVAL_C1, 1);
+ if (n) {
+ n[1].f = x;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalCoord1f(ctx->Exec, (x));
+ }
+}
+
+static void GLAPIENTRY
+save_EvalCoord1fv(const GLfloat * v)
+{
+ save_EvalCoord1f(v[0]);
+}
+
+static void GLAPIENTRY
+save_EvalCoord2f(GLfloat x, GLfloat y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVAL_C2, 2);
+ if (n) {
+ n[1].f = x;
+ n[2].f = y;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalCoord2f(ctx->Exec, (x, y));
+ }
+}
+
+static void GLAPIENTRY
+save_EvalCoord2fv(const GLfloat * v)
+{
+ save_EvalCoord2f(v[0], v[1]);
+}
+
+
+static void GLAPIENTRY
+save_EvalPoint1(GLint x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVAL_P1, 1);
+ if (n) {
+ n[1].i = x;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalPoint1(ctx->Exec, (x));
+ }
+}
+
+static void GLAPIENTRY
+save_EvalPoint2(GLint x, GLint y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_EVAL_P2, 2);
+ if (n) {
+ n[1].i = x;
+ n[2].i = y;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_EvalPoint2(ctx->Exec, (x, y));
+ }
+}
+
+static void GLAPIENTRY
+save_Indexf(GLfloat x)
+{
+ save_Attr1fNV(VERT_ATTRIB_COLOR_INDEX, x);
+}
+
+static void GLAPIENTRY
+save_Indexfv(const GLfloat * v)
+{
+ save_Attr1fNV(VERT_ATTRIB_COLOR_INDEX, v[0]);
+}
+
+static void GLAPIENTRY
+save_EdgeFlag(GLboolean x)
+{
+ save_Attr1fNV(VERT_ATTRIB_EDGEFLAG, x ? (GLfloat)1.0 : (GLfloat)0.0);
+}
+
+static INLINE GLboolean compare4fv( const GLfloat *a,
+ const GLfloat *b,
+ GLuint count )
+{
+ return memcmp( a, b, count * sizeof(GLfloat) ) == 0;
+}
+
+
+static void GLAPIENTRY
+save_Materialfv(GLenum face, GLenum pname, const GLfloat * param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ int args, i;
+ GLuint bitmask;
+
+ switch (face) {
+ case GL_BACK:
+ case GL_FRONT:
+ case GL_FRONT_AND_BACK:
+ break;
+ default:
+ _mesa_compile_error(ctx, GL_INVALID_ENUM, "material(face)");
+ return;
+ }
+
+ switch (pname) {
+ case GL_EMISSION:
+ case GL_AMBIENT:
+ case GL_DIFFUSE:
+ case GL_SPECULAR:
+ case GL_AMBIENT_AND_DIFFUSE:
+ args = 4;
+ break;
+ case GL_SHININESS:
+ args = 1;
+ break;
+ case GL_COLOR_INDEXES:
+ args = 3;
+ break;
+ default:
+ _mesa_compile_error(ctx, GL_INVALID_ENUM, "material(pname)");
+ return;
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_Materialfv(ctx->Exec, (face, pname, param));
+ }
+
+ bitmask = _mesa_material_bitmask(ctx, face, pname, ~0, NULL);
+
+ /* Try to eliminate redundant statechanges. Because it is legal to
+ * call glMaterial even inside begin/end calls, don't need to worry
+ * about ctx->Driver.CurrentSavePrimitive here.
+ */
+ for (i = 0; i < MAT_ATTRIB_MAX; i++) {
+ if (bitmask & (1 << i)) {
+ if (ctx->ListState.ActiveMaterialSize[i] == args &&
+ compare4fv(ctx->ListState.CurrentMaterial[i], param, args)) {
+ bitmask &= ~(1 << i);
+ }
+ else {
+ ctx->ListState.ActiveMaterialSize[i] = args;
+ COPY_SZ_4V(ctx->ListState.CurrentMaterial[i], args, param);
+ }
+ }
+ }
+
+ /* If this call has effect, return early:
+ */
+ if (bitmask == 0)
+ return;
+
+ SAVE_FLUSH_VERTICES(ctx);
+
+ n = alloc_instruction(ctx, OPCODE_MATERIAL, 6);
+ if (n) {
+ n[1].e = face;
+ n[2].e = pname;
+ for (i = 0; i < args; i++)
+ n[3 + i].f = param[i];
+ }
+}
+
+static void GLAPIENTRY
+save_Begin(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ GLboolean error = GL_FALSE;
+
+ if ( /*mode < GL_POINTS || */ mode > GL_POLYGON) {
+ _mesa_compile_error(ctx, GL_INVALID_ENUM, "Begin (mode)");
+ error = GL_TRUE;
+ }
+ else if (ctx->Driver.CurrentSavePrimitive == PRIM_UNKNOWN) {
+ /* Typically the first begin. This may raise an error on
+ * playback, depending on whether CallList is issued from inside
+ * a begin/end or not.
+ */
+ ctx->Driver.CurrentSavePrimitive = PRIM_INSIDE_UNKNOWN_PRIM;
+ }
+ else if (ctx->Driver.CurrentSavePrimitive == PRIM_OUTSIDE_BEGIN_END) {
+ ctx->Driver.CurrentSavePrimitive = mode;
+ }
+ else {
+ _mesa_compile_error(ctx, GL_INVALID_OPERATION, "recursive begin");
+ error = GL_TRUE;
+ }
+
+ if (!error) {
+ /* Give the driver an opportunity to hook in an optimized
+ * display list compiler.
+ */
+ if (ctx->Driver.NotifySaveBegin(ctx, mode))
+ return;
+
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_BEGIN, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ }
+
+ if (ctx->ExecuteFlag) {
+ CALL_Begin(ctx->Exec, (mode));
+ }
+}
+
+static void GLAPIENTRY
+save_End(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ SAVE_FLUSH_VERTICES(ctx);
+ (void) alloc_instruction(ctx, OPCODE_END, 0);
+ ctx->Driver.CurrentSavePrimitive = PRIM_OUTSIDE_BEGIN_END;
+ if (ctx->ExecuteFlag) {
+ CALL_End(ctx->Exec, ());
+ }
+}
+
+static void GLAPIENTRY
+save_Rectf(GLfloat a, GLfloat b, GLfloat c, GLfloat d)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ SAVE_FLUSH_VERTICES(ctx);
+ n = alloc_instruction(ctx, OPCODE_RECTF, 4);
+ if (n) {
+ n[1].f = a;
+ n[2].f = b;
+ n[3].f = c;
+ n[4].f = d;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Rectf(ctx->Exec, (a, b, c, d));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Vertex2f(GLfloat x, GLfloat y)
+{
+ save_Attr2fNV(VERT_ATTRIB_POS, x, y);
+}
+
+static void GLAPIENTRY
+save_Vertex2fv(const GLfloat * v)
+{
+ save_Attr2fNV(VERT_ATTRIB_POS, v[0], v[1]);
+}
+
+static void GLAPIENTRY
+save_Vertex3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_Attr3fNV(VERT_ATTRIB_POS, x, y, z);
+}
+
+static void GLAPIENTRY
+save_Vertex3fv(const GLfloat * v)
+{
+ save_Attr3fNV(VERT_ATTRIB_POS, v[0], v[1], v[2]);
+}
+
+static void GLAPIENTRY
+save_Vertex4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ save_Attr4fNV(VERT_ATTRIB_POS, x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_Vertex4fv(const GLfloat * v)
+{
+ save_Attr4fNV(VERT_ATTRIB_POS, v[0], v[1], v[2], v[3]);
+}
+
+static void GLAPIENTRY
+save_TexCoord1f(GLfloat x)
+{
+ save_Attr1fNV(VERT_ATTRIB_TEX0, x);
+}
+
+static void GLAPIENTRY
+save_TexCoord1fv(const GLfloat * v)
+{
+ save_Attr1fNV(VERT_ATTRIB_TEX0, v[0]);
+}
+
+static void GLAPIENTRY
+save_TexCoord2f(GLfloat x, GLfloat y)
+{
+ save_Attr2fNV(VERT_ATTRIB_TEX0, x, y);
+}
+
+static void GLAPIENTRY
+save_TexCoord2fv(const GLfloat * v)
+{
+ save_Attr2fNV(VERT_ATTRIB_TEX0, v[0], v[1]);
+}
+
+static void GLAPIENTRY
+save_TexCoord3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_Attr3fNV(VERT_ATTRIB_TEX0, x, y, z);
+}
+
+static void GLAPIENTRY
+save_TexCoord3fv(const GLfloat * v)
+{
+ save_Attr3fNV(VERT_ATTRIB_TEX0, v[0], v[1], v[2]);
+}
+
+static void GLAPIENTRY
+save_TexCoord4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ save_Attr4fNV(VERT_ATTRIB_TEX0, x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_TexCoord4fv(const GLfloat * v)
+{
+ save_Attr4fNV(VERT_ATTRIB_TEX0, v[0], v[1], v[2], v[3]);
+}
+
+static void GLAPIENTRY
+save_Normal3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_Attr3fNV(VERT_ATTRIB_NORMAL, x, y, z);
+}
+
+static void GLAPIENTRY
+save_Normal3fv(const GLfloat * v)
+{
+ save_Attr3fNV(VERT_ATTRIB_NORMAL, v[0], v[1], v[2]);
+}
+
+static void GLAPIENTRY
+save_FogCoordfEXT(GLfloat x)
+{
+ save_Attr1fNV(VERT_ATTRIB_FOG, x);
+}
+
+static void GLAPIENTRY
+save_FogCoordfvEXT(const GLfloat * v)
+{
+ save_Attr1fNV(VERT_ATTRIB_FOG, v[0]);
+}
+
+static void GLAPIENTRY
+save_Color3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_Attr3fNV(VERT_ATTRIB_COLOR0, x, y, z);
+}
+
+static void GLAPIENTRY
+save_Color3fv(const GLfloat * v)
+{
+ save_Attr3fNV(VERT_ATTRIB_COLOR0, v[0], v[1], v[2]);
+}
+
+static void GLAPIENTRY
+save_Color4f(GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ save_Attr4fNV(VERT_ATTRIB_COLOR0, x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_Color4fv(const GLfloat * v)
+{
+ save_Attr4fNV(VERT_ATTRIB_COLOR0, v[0], v[1], v[2], v[3]);
+}
+
+static void GLAPIENTRY
+save_SecondaryColor3fEXT(GLfloat x, GLfloat y, GLfloat z)
+{
+ save_Attr3fNV(VERT_ATTRIB_COLOR1, x, y, z);
+}
+
+static void GLAPIENTRY
+save_SecondaryColor3fvEXT(const GLfloat * v)
+{
+ save_Attr3fNV(VERT_ATTRIB_COLOR1, v[0], v[1], v[2]);
+}
+
+
+/* Just call the respective ATTR for texcoord
+ */
+static void GLAPIENTRY
+save_MultiTexCoord1f(GLenum target, GLfloat x)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr1fNV(attr, x);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord1fv(GLenum target, const GLfloat * v)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr1fNV(attr, v[0]);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord2f(GLenum target, GLfloat x, GLfloat y)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr2fNV(attr, x, y);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord2fv(GLenum target, const GLfloat * v)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr2fNV(attr, v[0], v[1]);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord3f(GLenum target, GLfloat x, GLfloat y, GLfloat z)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr3fNV(attr, x, y, z);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord3fv(GLenum target, const GLfloat * v)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr3fNV(attr, v[0], v[1], v[2]);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord4f(GLenum target, GLfloat x, GLfloat y,
+ GLfloat z, GLfloat w)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr4fNV(attr, x, y, z, w);
+}
+
+static void GLAPIENTRY
+save_MultiTexCoord4fv(GLenum target, const GLfloat * v)
+{
+ GLuint attr = (target & 0x7) + VERT_ATTRIB_TEX0;
+ save_Attr4fNV(attr, v[0], v[1], v[2], v[3]);
+}
+
+
+/**
+ * Record a GL_INVALID_VALUE error when a invalid vertex attribute
+ * index is found.
+ */
+static void
+index_error(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ _mesa_error(ctx, GL_INVALID_VALUE, "VertexAttribf(index)");
+}
+
+
+/* First level for NV_vertex_program:
+ *
+ * Check for errors at compile time?.
+ */
+static void GLAPIENTRY
+save_VertexAttrib1fNV(GLuint index, GLfloat x)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr1fNV(index, x);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib1fvNV(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr1fNV(index, v[0]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib2fNV(GLuint index, GLfloat x, GLfloat y)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr2fNV(index, x, y);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib2fvNV(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr2fNV(index, v[0], v[1]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib3fNV(GLuint index, GLfloat x, GLfloat y, GLfloat z)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr3fNV(index, x, y, z);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib3fvNV(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr3fNV(index, v[0], v[1], v[2]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib4fNV(GLuint index, GLfloat x, GLfloat y,
+ GLfloat z, GLfloat w)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr4fNV(index, x, y, z, w);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib4fvNV(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_NV_VERTEX_PROGRAM_INPUTS)
+ save_Attr4fNV(index, v[0], v[1], v[2], v[3]);
+ else
+ index_error();
+}
+
+
+
+
+static void GLAPIENTRY
+save_VertexAttrib1fARB(GLuint index, GLfloat x)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr1fARB(index, x);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib1fvARB(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr1fARB(index, v[0]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib2fARB(GLuint index, GLfloat x, GLfloat y)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr2fARB(index, x, y);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib2fvARB(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr2fARB(index, v[0], v[1]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib3fARB(GLuint index, GLfloat x, GLfloat y, GLfloat z)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr3fARB(index, x, y, z);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib3fvARB(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr3fARB(index, v[0], v[1], v[2]);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib4fARB(GLuint index, GLfloat x, GLfloat y, GLfloat z,
+ GLfloat w)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr4fARB(index, x, y, z, w);
+ else
+ index_error();
+}
+
+static void GLAPIENTRY
+save_VertexAttrib4fvARB(GLuint index, const GLfloat * v)
+{
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ save_Attr4fARB(index, v[0], v[1], v[2], v[3]);
+ else
+ index_error();
+}
+
+
+/* GL_ARB_shader_objects, GL_ARB_vertex/fragment_shader */
+
+static void GLAPIENTRY
+exec_BindAttribLocationARB(GLuint program, GLuint index, const GLchar *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_BindAttribLocationARB(ctx->Exec, (program, index, name));
+}
+
+static GLint GLAPIENTRY
+exec_GetAttribLocationARB(GLuint program, const GLchar *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_GetAttribLocationARB(ctx->Exec, (program, name));
+}
+
+static GLint GLAPIENTRY
+exec_GetUniformLocationARB(GLuint program, const GLchar *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_GetUniformLocationARB(ctx->Exec, (program, name));
+}
+/* XXX more shader functions needed here */
+
+
+#if FEATURE_EXT_framebuffer_blit
+static void GLAPIENTRY
+save_BlitFramebufferEXT(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
+ GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
+ GLbitfield mask, GLenum filter)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BLIT_FRAMEBUFFER, 10);
+ if (n) {
+ n[1].i = srcX0;
+ n[2].i = srcY0;
+ n[3].i = srcX1;
+ n[4].i = srcY1;
+ n[5].i = dstX0;
+ n[6].i = dstY0;
+ n[7].i = dstX1;
+ n[8].i = dstY1;
+ n[9].i = mask;
+ n[10].e = filter;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BlitFramebufferEXT(ctx->Exec, (srcX0, srcY0, srcX1, srcY1,
+ dstX0, dstY0, dstX1, dstY1,
+ mask, filter));
+ }
+}
+#endif
+
+
+/** GL_EXT_provoking_vertex */
+static void GLAPIENTRY
+save_ProvokingVertexEXT(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_PROVOKING_VERTEX, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_ProvokingVertexEXT(ctx->Exec, (mode));*/
+ _mesa_ProvokingVertexEXT(mode);
+ }
+}
+
+
+/** GL_EXT_transform_feedback */
+static void GLAPIENTRY
+save_BeginTransformFeedback(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_BEGIN_TRANSFORM_FEEDBACK, 1);
+ if (n) {
+ n[1].e = mode;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_BeginTransformFeedbackEXT(ctx->Exec, (mode));
+ }
+}
+
+
+/** GL_EXT_transform_feedback */
+static void GLAPIENTRY
+save_EndTransformFeedback(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ (void) alloc_instruction(ctx, OPCODE_END_TRANSFORM_FEEDBACK, 0);
+ if (ctx->ExecuteFlag) {
+ CALL_EndTransformFeedbackEXT(ctx->Exec, ());
+ }
+}
+
+
+/* aka UseProgram() */
+static void GLAPIENTRY
+save_UseProgramObjectARB(GLhandleARB program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_USE_PROGRAM, 1);
+ if (n) {
+ n[1].ui = program;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UseProgramObjectARB(ctx->Exec, (program));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Uniform1fARB(GLint location, GLfloat x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1F, 2);
+ if (n) {
+ n[1].i = location;
+ n[2].f = x;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform1fARB(ctx->Exec, (location, x));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Uniform2fARB(GLint location, GLfloat x, GLfloat y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2F, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].f = x;
+ n[3].f = y;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform2fARB(ctx->Exec, (location, x, y));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Uniform3fARB(GLint location, GLfloat x, GLfloat y, GLfloat z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3F, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform3fARB(ctx->Exec, (location, x, y, z));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Uniform4fARB(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4F, 5);
+ if (n) {
+ n[1].i = location;
+ n[2].f = x;
+ n[3].f = y;
+ n[4].f = z;
+ n[5].f = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform4fARB(ctx->Exec, (location, x, y, z, w));
+ }
+}
+
+
+/** Return copy of memory */
+static void *
+memdup(const void *src, GLsizei bytes)
+{
+ void *b = bytes >= 0 ? malloc(bytes) : NULL;
+ if (b)
+ memcpy(b, src, bytes);
+ return b;
+}
+
+
+static void GLAPIENTRY
+save_Uniform1fvARB(GLint location, GLsizei count, const GLfloat *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1FV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 1 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform1fvARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform2fvARB(GLint location, GLsizei count, const GLfloat *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2FV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 2 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform2fvARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform3fvARB(GLint location, GLsizei count, const GLfloat *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3FV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 3 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform3fvARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform4fvARB(GLint location, GLsizei count, const GLfloat *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4FV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 4 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform4fvARB(ctx->Exec, (location, count, v));
+ }
+}
+
+
+static void GLAPIENTRY
+save_Uniform1iARB(GLint location, GLint x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1I, 2);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform1iARB(ctx->Exec, (location, x));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform2iARB(GLint location, GLint x, GLint y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2I, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform2iARB(ctx->Exec, (location, x, y));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform3iARB(GLint location, GLint x, GLint y, GLint z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3I, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ n[4].i = z;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform3iARB(ctx->Exec, (location, x, y, z));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform4iARB(GLint location, GLint x, GLint y, GLint z, GLint w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4I, 5);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ n[4].i = z;
+ n[5].i = w;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform4iARB(ctx->Exec, (location, x, y, z, w));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_Uniform1ivARB(GLint location, GLsizei count, const GLint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1IV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 1 * sizeof(GLint));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform1ivARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform2ivARB(GLint location, GLsizei count, const GLint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2IV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 2 * sizeof(GLint));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform2ivARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform3ivARB(GLint location, GLsizei count, const GLint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3IV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 3 * sizeof(GLint));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform3ivARB(ctx->Exec, (location, count, v));
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform4ivARB(GLint location, GLsizei count, const GLint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4IV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 4 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_Uniform4ivARB(ctx->Exec, (location, count, v));
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_Uniform1ui(GLint location, GLuint x)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1UI, 2);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform1ui(ctx->Exec, (location, x));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform2ui(GLint location, GLuint x, GLuint y)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2UI, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform2ui(ctx->Exec, (location, x, y));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform3ui(GLint location, GLuint x, GLuint y, GLuint z)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3UI, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ n[4].i = z;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform3ui(ctx->Exec, (location, x, y, z));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform4ui(GLint location, GLuint x, GLuint y, GLuint z, GLuint w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4UI, 5);
+ if (n) {
+ n[1].i = location;
+ n[2].i = x;
+ n[3].i = y;
+ n[4].i = z;
+ n[5].i = w;
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform4ui(ctx->Exec, (location, x, y, z, w));*/
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_Uniform1uiv(GLint location, GLsizei count, const GLuint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_1UIV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 1 * sizeof(*v));
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform1uiv(ctx->Exec, (location, count, v));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform2uiv(GLint location, GLsizei count, const GLuint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_2UIV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 2 * sizeof(*v));
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform2uiv(ctx->Exec, (location, count, v));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform3uiv(GLint location, GLsizei count, const GLuint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_3UIV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 3 * sizeof(*v));
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform3uiv(ctx->Exec, (location, count, v));*/
+ }
+}
+
+static void GLAPIENTRY
+save_Uniform4uiv(GLint location, GLsizei count, const GLuint *v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_4UIV, 3);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].data = memdup(v, count * 4 * sizeof(*v));
+ }
+ if (ctx->ExecuteFlag) {
+ /*CALL_Uniform4uiv(ctx->Exec, (location, count, v));*/
+ }
+}
+
+
+
+static void GLAPIENTRY
+save_UniformMatrix2fvARB(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX22, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 2 * 2 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix2fvARB(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UniformMatrix3fvARB(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX33, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 3 * 3 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix3fvARB(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UniformMatrix4fvARB(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX44, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 4 * 4 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix4fvARB(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+
+static void GLAPIENTRY
+save_UniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX23, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 2 * 3 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix2x3fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX32, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 3 * 2 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix3x2fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+
+static void GLAPIENTRY
+save_UniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX24, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 2 * 4 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix2x4fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX42, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 4 * 2 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix4x2fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+
+static void GLAPIENTRY
+save_UniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX34, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 3 * 4 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix3x4fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose,
+ const GLfloat *m)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_UNIFORM_MATRIX43, 4);
+ if (n) {
+ n[1].i = location;
+ n[2].i = count;
+ n[3].b = transpose;
+ n[4].data = memdup(m, count * 4 * 3 * sizeof(GLfloat));
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UniformMatrix4x3fv(ctx->Exec, (location, count, transpose, m));
+ }
+}
+
+static void GLAPIENTRY
+save_UseShaderProgramEXT(GLenum type, GLuint program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_USE_SHADER_PROGRAM_EXT, 2);
+ if (n) {
+ n[1].ui = type;
+ n[2].ui = program;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_UseShaderProgramEXT(ctx->Exec, (type, program));
+ }
+}
+
+static void GLAPIENTRY
+save_ActiveProgramEXT(GLuint program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_ACTIVE_PROGRAM_EXT, 1);
+ if (n) {
+ n[1].ui = program;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ActiveProgramEXT(ctx->Exec, (program));
+ }
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+save_ClearColorIi(GLint red, GLint green, GLint blue, GLint alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEARCOLOR_I, 4);
+ if (n) {
+ n[1].i = red;
+ n[2].i = green;
+ n[3].i = blue;
+ n[4].i = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearColorIiEXT(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+save_ClearColorIui(GLuint red, GLuint green, GLuint blue, GLuint alpha)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_CLEARCOLOR_UI, 4);
+ if (n) {
+ n[1].ui = red;
+ n[2].ui = green;
+ n[3].ui = blue;
+ n[4].ui = alpha;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_ClearColorIuiEXT(ctx->Exec, (red, green, blue, alpha));
+ }
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+save_TexParameterIiv(GLenum target, GLenum pname, const GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEXPARAMETER_I, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].i = params[0];
+ n[4].i = params[1];
+ n[5].i = params[2];
+ n[6].i = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexParameterIivEXT(ctx->Exec, (target, pname, params));
+ }
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+save_TexParameterIuiv(GLenum target, GLenum pname, const GLuint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_TEXPARAMETER_UI, 6);
+ if (n) {
+ n[1].e = target;
+ n[2].e = pname;
+ n[3].ui = params[0];
+ n[4].ui = params[1];
+ n[5].ui = params[2];
+ n[6].ui = params[3];
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_TexParameterIuivEXT(ctx->Exec, (target, pname, params));
+ }
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+exec_GetTexParameterIiv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexParameterIivEXT(ctx->Exec, (target, pname, params));
+}
+
+/** GL_EXT_texture_integer */
+static void GLAPIENTRY
+exec_GetTexParameterIuiv(GLenum target, GLenum pname, GLuint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexParameterIuivEXT(ctx->Exec, (target, pname, params));
+}
+
+
+/* GL_ARB_instanced_arrays */
+static void
+save_VertexAttribDivisor(GLuint index, GLuint divisor)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ Node *n;
+ ASSERT_OUTSIDE_SAVE_BEGIN_END_AND_FLUSH(ctx);
+ n = alloc_instruction(ctx, OPCODE_VERTEX_ATTRIB_DIVISOR, 2);
+ if (n) {
+ n[1].ui = index;
+ n[2].ui = divisor;
+ }
+ if (ctx->ExecuteFlag) {
+ CALL_VertexAttribDivisorARB(ctx->Exec, (index, divisor));
+ }
+}
+
+
+
+/**
+ * Save an error-generating command into display list.
+ *
+ * KW: Will appear in the list before the vertex buffer containing the
+ * command that provoked the error. I don't see this as a problem.
+ */
+static void
+save_error(struct gl_context *ctx, GLenum error, const char *s)
+{
+ Node *n;
+ n = alloc_instruction(ctx, OPCODE_ERROR, 2);
+ if (n) {
+ n[1].e = error;
+ n[2].data = (void *) s;
+ }
+}
+
+
+/**
+ * Compile an error into current display list.
+ */
+void
+_mesa_compile_error(struct gl_context *ctx, GLenum error, const char *s)
+{
+ if (ctx->CompileFlag)
+ save_error(ctx, error, s);
+ if (ctx->ExecuteFlag)
+ _mesa_error(ctx, error, "%s", s);
+}
+
+
+/**
+ * Test if ID names a display list.
+ */
+static GLboolean
+islist(struct gl_context *ctx, GLuint list)
+{
+ if (list > 0 && lookup_list(ctx, list)) {
+ return GL_TRUE;
+ }
+ else {
+ return GL_FALSE;
+ }
+}
+
+
+
+/**********************************************************************/
+/* Display list execution */
+/**********************************************************************/
+
+
+/*
+ * Execute a display list. Note that the ListBase offset must have already
+ * been added before calling this function. I.e. the list argument is
+ * the absolute list number, not relative to ListBase.
+ * \param list - display list number
+ */
+static void
+execute_list(struct gl_context *ctx, GLuint list)
+{
+ struct gl_display_list *dlist;
+ Node *n;
+ GLboolean done;
+
+ if (list == 0 || !islist(ctx, list))
+ return;
+
+ if (ctx->ListState.CallDepth == MAX_LIST_NESTING) {
+ /* raise an error? */
+ return;
+ }
+
+ dlist = lookup_list(ctx, list);
+ if (!dlist)
+ return;
+
+ ctx->ListState.CallDepth++;
+
+ if (ctx->Driver.BeginCallList)
+ ctx->Driver.BeginCallList(ctx, dlist);
+
+ n = dlist->Head;
+
+ done = GL_FALSE;
+ while (!done) {
+ const OpCode opcode = n[0].opcode;
+
+ if (is_ext_opcode(opcode)) {
+ n += ext_opcode_execute(ctx, n);
+ }
+ else {
+ switch (opcode) {
+ case OPCODE_ERROR:
+ _mesa_error(ctx, n[1].e, "%s", (const char *) n[2].data);
+ break;
+ case OPCODE_ACCUM:
+ CALL_Accum(ctx->Exec, (n[1].e, n[2].f));
+ break;
+ case OPCODE_ALPHA_FUNC:
+ CALL_AlphaFunc(ctx->Exec, (n[1].e, n[2].f));
+ break;
+ case OPCODE_BIND_TEXTURE:
+ CALL_BindTexture(ctx->Exec, (n[1].e, n[2].ui));
+ break;
+ case OPCODE_BITMAP:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_Bitmap(ctx->Exec, ((GLsizei) n[1].i, (GLsizei) n[2].i,
+ n[3].f, n[4].f, n[5].f, n[6].f,
+ (const GLubyte *) n[7].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_BLEND_COLOR:
+ CALL_BlendColor(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_BLEND_EQUATION:
+ CALL_BlendEquation(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_BLEND_EQUATION_SEPARATE:
+ CALL_BlendEquationSeparateEXT(ctx->Exec, (n[1].e, n[2].e));
+ break;
+ case OPCODE_BLEND_FUNC_SEPARATE:
+ CALL_BlendFuncSeparateEXT(ctx->Exec,
+ (n[1].e, n[2].e, n[3].e, n[4].e));
+ break;
+
+ case OPCODE_BLEND_FUNC_I:
+ /* GL_ARB_draw_buffers_blend */
+ CALL_BlendFunciARB(ctx->Exec, (n[1].ui, n[2].e, n[3].e));
+ break;
+ case OPCODE_BLEND_FUNC_SEPARATE_I:
+ /* GL_ARB_draw_buffers_blend */
+ CALL_BlendFuncSeparateiARB(ctx->Exec, (n[1].ui, n[2].e, n[3].e,
+ n[4].e, n[5].e));
+ break;
+ case OPCODE_BLEND_EQUATION_I:
+ /* GL_ARB_draw_buffers_blend */
+ CALL_BlendEquationiARB(ctx->Exec, (n[1].ui, n[2].e));
+ break;
+ case OPCODE_BLEND_EQUATION_SEPARATE_I:
+ /* GL_ARB_draw_buffers_blend */
+ CALL_BlendEquationSeparateiARB(ctx->Exec,
+ (n[1].ui, n[2].e, n[3].e));
+ break;
+
+ case OPCODE_CALL_LIST:
+ /* Generated by glCallList(), don't add ListBase */
+ if (ctx->ListState.CallDepth < MAX_LIST_NESTING) {
+ execute_list(ctx, n[1].ui);
+ }
+ break;
+ case OPCODE_CALL_LIST_OFFSET:
+ /* Generated by glCallLists() so we must add ListBase */
+ if (n[2].b) {
+ /* user specified a bad data type at compile time */
+ _mesa_error(ctx, GL_INVALID_ENUM, "glCallLists(type)");
+ }
+ else if (ctx->ListState.CallDepth < MAX_LIST_NESTING) {
+ GLuint list = (GLuint) (ctx->List.ListBase + n[1].i);
+ execute_list(ctx, list);
+ }
+ break;
+ case OPCODE_CLEAR:
+ CALL_Clear(ctx->Exec, (n[1].bf));
+ break;
+ case OPCODE_CLEAR_BUFFER_IV:
+ {
+ GLint value[4];
+ value[0] = n[3].i;
+ value[1] = n[4].i;
+ value[2] = n[5].i;
+ value[3] = n[6].i;
+ /*CALL_ClearBufferiv(ctx->Exec, (n[1].e, n[2].i, value));*/
+ }
+ break;
+ case OPCODE_CLEAR_BUFFER_UIV:
+ {
+ GLuint value[4];
+ value[0] = n[3].ui;
+ value[1] = n[4].ui;
+ value[2] = n[5].ui;
+ value[3] = n[6].ui;
+ /*CALL_ClearBufferiv(ctx->Exec, (n[1].e, n[2].i, value));*/
+ }
+ break;
+ case OPCODE_CLEAR_BUFFER_FV:
+ {
+ GLfloat value[4];
+ value[0] = n[3].f;
+ value[1] = n[4].f;
+ value[2] = n[5].f;
+ value[3] = n[6].f;
+ /*CALL_ClearBufferfv(ctx->Exec, (n[1].e, n[2].i, value));*/
+ }
+ break;
+ case OPCODE_CLEAR_BUFFER_FI:
+ /*CALL_ClearBufferfi(ctx->Exec, (n[1].e, n[2].i, n[3].f, n[4].i));*/
+ break;
+ case OPCODE_CLEAR_COLOR:
+ CALL_ClearColor(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_CLEAR_ACCUM:
+ CALL_ClearAccum(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_CLEAR_DEPTH:
+ CALL_ClearDepth(ctx->Exec, ((GLclampd) n[1].f));
+ break;
+ case OPCODE_CLEAR_INDEX:
+ CALL_ClearIndex(ctx->Exec, ((GLfloat) n[1].ui));
+ break;
+ case OPCODE_CLEAR_STENCIL:
+ CALL_ClearStencil(ctx->Exec, (n[1].i));
+ break;
+ case OPCODE_CLIP_PLANE:
+ {
+ GLdouble eq[4];
+ eq[0] = n[2].f;
+ eq[1] = n[3].f;
+ eq[2] = n[4].f;
+ eq[3] = n[5].f;
+ CALL_ClipPlane(ctx->Exec, (n[1].e, eq));
+ }
+ break;
+ case OPCODE_COLOR_MASK:
+ CALL_ColorMask(ctx->Exec, (n[1].b, n[2].b, n[3].b, n[4].b));
+ break;
+ case OPCODE_COLOR_MASK_INDEXED:
+ CALL_ColorMaskIndexedEXT(ctx->Exec, (n[1].ui, n[2].b, n[3].b,
+ n[4].b, n[5].b));
+ break;
+ case OPCODE_COLOR_MATERIAL:
+ CALL_ColorMaterial(ctx->Exec, (n[1].e, n[2].e));
+ break;
+ case OPCODE_COLOR_TABLE:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_ColorTable(ctx->Exec, (n[1].e, n[2].e, n[3].i, n[4].e,
+ n[5].e, n[6].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_COLOR_TABLE_PARAMETER_FV:
+ {
+ GLfloat params[4];
+ params[0] = n[3].f;
+ params[1] = n[4].f;
+ params[2] = n[5].f;
+ params[3] = n[6].f;
+ CALL_ColorTableParameterfv(ctx->Exec,
+ (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_COLOR_TABLE_PARAMETER_IV:
+ {
+ GLint params[4];
+ params[0] = n[3].i;
+ params[1] = n[4].i;
+ params[2] = n[5].i;
+ params[3] = n[6].i;
+ CALL_ColorTableParameteriv(ctx->Exec,
+ (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_COLOR_SUB_TABLE:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_ColorSubTable(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].e, n[5].e, n[6].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_CONVOLUTION_FILTER_1D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_ConvolutionFilter1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].e, n[5].e,
+ n[6].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_CONVOLUTION_FILTER_2D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_ConvolutionFilter2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].e, n[6].e,
+ n[7].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_CONVOLUTION_PARAMETER_I:
+ CALL_ConvolutionParameteri(ctx->Exec, (n[1].e, n[2].e, n[3].i));
+ break;
+ case OPCODE_CONVOLUTION_PARAMETER_IV:
+ {
+ GLint params[4];
+ params[0] = n[3].i;
+ params[1] = n[4].i;
+ params[2] = n[5].i;
+ params[3] = n[6].i;
+ CALL_ConvolutionParameteriv(ctx->Exec,
+ (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_CONVOLUTION_PARAMETER_F:
+ CALL_ConvolutionParameterf(ctx->Exec, (n[1].e, n[2].e, n[3].f));
+ break;
+ case OPCODE_CONVOLUTION_PARAMETER_FV:
+ {
+ GLfloat params[4];
+ params[0] = n[3].f;
+ params[1] = n[4].f;
+ params[2] = n[5].f;
+ params[3] = n[6].f;
+ CALL_ConvolutionParameterfv(ctx->Exec,
+ (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_COPY_COLOR_SUB_TABLE:
+ CALL_CopyColorSubTable(ctx->Exec, (n[1].e, n[2].i,
+ n[3].i, n[4].i, n[5].i));
+ break;
+ case OPCODE_COPY_COLOR_TABLE:
+ CALL_CopyColorSubTable(ctx->Exec, (n[1].e, n[2].i,
+ n[3].i, n[4].i, n[5].i));
+ break;
+ case OPCODE_COPY_PIXELS:
+ CALL_CopyPixels(ctx->Exec, (n[1].i, n[2].i,
+ (GLsizei) n[3].i, (GLsizei) n[4].i,
+ n[5].e));
+ break;
+ case OPCODE_COPY_TEX_IMAGE1D:
+ CALL_CopyTexImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].i,
+ n[5].i, n[6].i, n[7].i));
+ break;
+ case OPCODE_COPY_TEX_IMAGE2D:
+ CALL_CopyTexImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].i,
+ n[5].i, n[6].i, n[7].i, n[8].i));
+ break;
+ case OPCODE_COPY_TEX_SUB_IMAGE1D:
+ CALL_CopyTexSubImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].i, n[6].i));
+ break;
+ case OPCODE_COPY_TEX_SUB_IMAGE2D:
+ CALL_CopyTexSubImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].i, n[6].i, n[7].i,
+ n[8].i));
+ break;
+ case OPCODE_COPY_TEX_SUB_IMAGE3D:
+ CALL_CopyTexSubImage3D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].i, n[6].i, n[7].i,
+ n[8].i, n[9].i));
+ break;
+ case OPCODE_CULL_FACE:
+ CALL_CullFace(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_DEPTH_FUNC:
+ CALL_DepthFunc(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_DEPTH_MASK:
+ CALL_DepthMask(ctx->Exec, (n[1].b));
+ break;
+ case OPCODE_DEPTH_RANGE:
+ CALL_DepthRange(ctx->Exec,
+ ((GLclampd) n[1].f, (GLclampd) n[2].f));
+ break;
+ case OPCODE_DISABLE:
+ CALL_Disable(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_DISABLE_INDEXED:
+ CALL_DisableIndexedEXT(ctx->Exec, (n[1].ui, n[2].e));
+ break;
+ case OPCODE_DRAW_BUFFER:
+ CALL_DrawBuffer(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_DRAW_PIXELS:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_DrawPixels(ctx->Exec, (n[1].i, n[2].i, n[3].e, n[4].e,
+ n[5].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_ENABLE:
+ CALL_Enable(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_ENABLE_INDEXED:
+ CALL_EnableIndexedEXT(ctx->Exec, (n[1].ui, n[2].e));
+ break;
+ case OPCODE_EVALMESH1:
+ CALL_EvalMesh1(ctx->Exec, (n[1].e, n[2].i, n[3].i));
+ break;
+ case OPCODE_EVALMESH2:
+ CALL_EvalMesh2(ctx->Exec,
+ (n[1].e, n[2].i, n[3].i, n[4].i, n[5].i));
+ break;
+ case OPCODE_FOG:
+ {
+ GLfloat p[4];
+ p[0] = n[2].f;
+ p[1] = n[3].f;
+ p[2] = n[4].f;
+ p[3] = n[5].f;
+ CALL_Fogfv(ctx->Exec, (n[1].e, p));
+ }
+ break;
+ case OPCODE_FRONT_FACE:
+ CALL_FrontFace(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_FRUSTUM:
+ CALL_Frustum(ctx->Exec,
+ (n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f));
+ break;
+ case OPCODE_HINT:
+ CALL_Hint(ctx->Exec, (n[1].e, n[2].e));
+ break;
+ case OPCODE_HISTOGRAM:
+ CALL_Histogram(ctx->Exec, (n[1].e, n[2].i, n[3].e, n[4].b));
+ break;
+ case OPCODE_INDEX_MASK:
+ CALL_IndexMask(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_INIT_NAMES:
+ CALL_InitNames(ctx->Exec, ());
+ break;
+ case OPCODE_LIGHT:
+ {
+ GLfloat p[4];
+ p[0] = n[3].f;
+ p[1] = n[4].f;
+ p[2] = n[5].f;
+ p[3] = n[6].f;
+ CALL_Lightfv(ctx->Exec, (n[1].e, n[2].e, p));
+ }
+ break;
+ case OPCODE_LIGHT_MODEL:
+ {
+ GLfloat p[4];
+ p[0] = n[2].f;
+ p[1] = n[3].f;
+ p[2] = n[4].f;
+ p[3] = n[5].f;
+ CALL_LightModelfv(ctx->Exec, (n[1].e, p));
+ }
+ break;
+ case OPCODE_LINE_STIPPLE:
+ CALL_LineStipple(ctx->Exec, (n[1].i, n[2].us));
+ break;
+ case OPCODE_LINE_WIDTH:
+ CALL_LineWidth(ctx->Exec, (n[1].f));
+ break;
+ case OPCODE_LIST_BASE:
+ CALL_ListBase(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_LOAD_IDENTITY:
+ CALL_LoadIdentity(ctx->Exec, ());
+ break;
+ case OPCODE_LOAD_MATRIX:
+ if (sizeof(Node) == sizeof(GLfloat)) {
+ CALL_LoadMatrixf(ctx->Exec, (&n[1].f));
+ }
+ else {
+ GLfloat m[16];
+ GLuint i;
+ for (i = 0; i < 16; i++) {
+ m[i] = n[1 + i].f;
+ }
+ CALL_LoadMatrixf(ctx->Exec, (m));
+ }
+ break;
+ case OPCODE_LOAD_NAME:
+ CALL_LoadName(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_LOGIC_OP:
+ CALL_LogicOp(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_MAP1:
+ {
+ GLenum target = n[1].e;
+ GLint ustride = _mesa_evaluator_components(target);
+ GLint uorder = n[5].i;
+ GLfloat u1 = n[2].f;
+ GLfloat u2 = n[3].f;
+ CALL_Map1f(ctx->Exec, (target, u1, u2, ustride, uorder,
+ (GLfloat *) n[6].data));
+ }
+ break;
+ case OPCODE_MAP2:
+ {
+ GLenum target = n[1].e;
+ GLfloat u1 = n[2].f;
+ GLfloat u2 = n[3].f;
+ GLfloat v1 = n[4].f;
+ GLfloat v2 = n[5].f;
+ GLint ustride = n[6].i;
+ GLint vstride = n[7].i;
+ GLint uorder = n[8].i;
+ GLint vorder = n[9].i;
+ CALL_Map2f(ctx->Exec, (target, u1, u2, ustride, uorder,
+ v1, v2, vstride, vorder,
+ (GLfloat *) n[10].data));
+ }
+ break;
+ case OPCODE_MAPGRID1:
+ CALL_MapGrid1f(ctx->Exec, (n[1].i, n[2].f, n[3].f));
+ break;
+ case OPCODE_MAPGRID2:
+ CALL_MapGrid2f(ctx->Exec,
+ (n[1].i, n[2].f, n[3].f, n[4].i, n[5].f, n[6].f));
+ break;
+ case OPCODE_MATRIX_MODE:
+ CALL_MatrixMode(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_MIN_MAX:
+ CALL_Minmax(ctx->Exec, (n[1].e, n[2].e, n[3].b));
+ break;
+ case OPCODE_MULT_MATRIX:
+ if (sizeof(Node) == sizeof(GLfloat)) {
+ CALL_MultMatrixf(ctx->Exec, (&n[1].f));
+ }
+ else {
+ GLfloat m[16];
+ GLuint i;
+ for (i = 0; i < 16; i++) {
+ m[i] = n[1 + i].f;
+ }
+ CALL_MultMatrixf(ctx->Exec, (m));
+ }
+ break;
+ case OPCODE_ORTHO:
+ CALL_Ortho(ctx->Exec,
+ (n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f));
+ break;
+ case OPCODE_PASSTHROUGH:
+ CALL_PassThrough(ctx->Exec, (n[1].f));
+ break;
+ case OPCODE_PIXEL_MAP:
+ CALL_PixelMapfv(ctx->Exec,
+ (n[1].e, n[2].i, (GLfloat *) n[3].data));
+ break;
+ case OPCODE_PIXEL_TRANSFER:
+ CALL_PixelTransferf(ctx->Exec, (n[1].e, n[2].f));
+ break;
+ case OPCODE_PIXEL_ZOOM:
+ CALL_PixelZoom(ctx->Exec, (n[1].f, n[2].f));
+ break;
+ case OPCODE_POINT_SIZE:
+ CALL_PointSize(ctx->Exec, (n[1].f));
+ break;
+ case OPCODE_POINT_PARAMETERS:
+ {
+ GLfloat params[3];
+ params[0] = n[2].f;
+ params[1] = n[3].f;
+ params[2] = n[4].f;
+ CALL_PointParameterfvEXT(ctx->Exec, (n[1].e, params));
+ }
+ break;
+ case OPCODE_POLYGON_MODE:
+ CALL_PolygonMode(ctx->Exec, (n[1].e, n[2].e));
+ break;
+ case OPCODE_POLYGON_STIPPLE:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_PolygonStipple(ctx->Exec, ((GLubyte *) n[1].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_POLYGON_OFFSET:
+ CALL_PolygonOffset(ctx->Exec, (n[1].f, n[2].f));
+ break;
+ case OPCODE_POP_ATTRIB:
+ CALL_PopAttrib(ctx->Exec, ());
+ break;
+ case OPCODE_POP_MATRIX:
+ CALL_PopMatrix(ctx->Exec, ());
+ break;
+ case OPCODE_POP_NAME:
+ CALL_PopName(ctx->Exec, ());
+ break;
+ case OPCODE_PRIORITIZE_TEXTURE:
+ CALL_PrioritizeTextures(ctx->Exec, (1, &n[1].ui, &n[2].f));
+ break;
+ case OPCODE_PUSH_ATTRIB:
+ CALL_PushAttrib(ctx->Exec, (n[1].bf));
+ break;
+ case OPCODE_PUSH_MATRIX:
+ CALL_PushMatrix(ctx->Exec, ());
+ break;
+ case OPCODE_PUSH_NAME:
+ CALL_PushName(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_RASTER_POS:
+ CALL_RasterPos4f(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_READ_BUFFER:
+ CALL_ReadBuffer(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_RESET_HISTOGRAM:
+ CALL_ResetHistogram(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_RESET_MIN_MAX:
+ CALL_ResetMinmax(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_ROTATE:
+ CALL_Rotatef(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_SCALE:
+ CALL_Scalef(ctx->Exec, (n[1].f, n[2].f, n[3].f));
+ break;
+ case OPCODE_SCISSOR:
+ CALL_Scissor(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
+ break;
+ case OPCODE_SHADE_MODEL:
+ CALL_ShadeModel(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_PROVOKING_VERTEX:
+ CALL_ProvokingVertexEXT(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_BEGIN_TRANSFORM_FEEDBACK:
+ CALL_BeginTransformFeedbackEXT(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_END_TRANSFORM_FEEDBACK:
+ CALL_EndTransformFeedbackEXT(ctx->Exec, ());
+ break;
+ case OPCODE_STENCIL_FUNC:
+ CALL_StencilFunc(ctx->Exec, (n[1].e, n[2].i, n[3].ui));
+ break;
+ case OPCODE_STENCIL_MASK:
+ CALL_StencilMask(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_STENCIL_OP:
+ CALL_StencilOp(ctx->Exec, (n[1].e, n[2].e, n[3].e));
+ break;
+ case OPCODE_STENCIL_FUNC_SEPARATE:
+ CALL_StencilFuncSeparate(ctx->Exec,
+ (n[1].e, n[2].e, n[3].i, n[4].ui));
+ break;
+ case OPCODE_STENCIL_MASK_SEPARATE:
+ CALL_StencilMaskSeparate(ctx->Exec, (n[1].e, n[2].ui));
+ break;
+ case OPCODE_STENCIL_OP_SEPARATE:
+ CALL_StencilOpSeparate(ctx->Exec,
+ (n[1].e, n[2].e, n[3].e, n[4].e));
+ break;
+ case OPCODE_TEXENV:
+ {
+ GLfloat params[4];
+ params[0] = n[3].f;
+ params[1] = n[4].f;
+ params[2] = n[5].f;
+ params[3] = n[6].f;
+ CALL_TexEnvfv(ctx->Exec, (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_TEXGEN:
+ {
+ GLfloat params[4];
+ params[0] = n[3].f;
+ params[1] = n[4].f;
+ params[2] = n[5].f;
+ params[3] = n[6].f;
+ CALL_TexGenfv(ctx->Exec, (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_TEXPARAMETER:
+ {
+ GLfloat params[4];
+ params[0] = n[3].f;
+ params[1] = n[4].f;
+ params[2] = n[5].f;
+ params[3] = n[6].f;
+ CALL_TexParameterfv(ctx->Exec, (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_TEX_IMAGE1D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexImage1D(ctx->Exec, (n[1].e, /* target */
+ n[2].i, /* level */
+ n[3].i, /* components */
+ n[4].i, /* width */
+ n[5].e, /* border */
+ n[6].e, /* format */
+ n[7].e, /* type */
+ n[8].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TEX_IMAGE2D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexImage2D(ctx->Exec, (n[1].e, /* target */
+ n[2].i, /* level */
+ n[3].i, /* components */
+ n[4].i, /* width */
+ n[5].i, /* height */
+ n[6].e, /* border */
+ n[7].e, /* format */
+ n[8].e, /* type */
+ n[9].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TEX_IMAGE3D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexImage3D(ctx->Exec, (n[1].e, /* target */
+ n[2].i, /* level */
+ n[3].i, /* components */
+ n[4].i, /* width */
+ n[5].i, /* height */
+ n[6].i, /* depth */
+ n[7].e, /* border */
+ n[8].e, /* format */
+ n[9].e, /* type */
+ n[10].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TEX_SUB_IMAGE1D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexSubImage1D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].e,
+ n[6].e, n[7].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TEX_SUB_IMAGE2D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexSubImage2D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].e,
+ n[6].i, n[7].e, n[8].e,
+ n[9].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TEX_SUB_IMAGE3D:
+ {
+ const struct gl_pixelstore_attrib save = ctx->Unpack;
+ ctx->Unpack = ctx->DefaultPacking;
+ CALL_TexSubImage3D(ctx->Exec, (n[1].e, n[2].i, n[3].i,
+ n[4].i, n[5].i, n[6].i, n[7].i,
+ n[8].i, n[9].e, n[10].e,
+ n[11].data));
+ ctx->Unpack = save; /* restore */
+ }
+ break;
+ case OPCODE_TRANSLATE:
+ CALL_Translatef(ctx->Exec, (n[1].f, n[2].f, n[3].f));
+ break;
+ case OPCODE_VIEWPORT:
+ CALL_Viewport(ctx->Exec, (n[1].i, n[2].i,
+ (GLsizei) n[3].i, (GLsizei) n[4].i));
+ break;
+ case OPCODE_WINDOW_POS:
+ CALL_WindowPos4fMESA(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_ACTIVE_TEXTURE: /* GL_ARB_multitexture */
+ CALL_ActiveTextureARB(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_1D: /* GL_ARB_texture_compression */
+ CALL_CompressedTexImage1DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
+ n[4].i, n[5].i, n[6].i,
+ n[7].data));
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_2D: /* GL_ARB_texture_compression */
+ CALL_CompressedTexImage2DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
+ n[4].i, n[5].i, n[6].i,
+ n[7].i, n[8].data));
+ break;
+ case OPCODE_COMPRESSED_TEX_IMAGE_3D: /* GL_ARB_texture_compression */
+ CALL_CompressedTexImage3DARB(ctx->Exec, (n[1].e, n[2].i, n[3].e,
+ n[4].i, n[5].i, n[6].i,
+ n[7].i, n[8].i,
+ n[9].data));
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_1D: /* GL_ARB_texture_compress */
+ CALL_CompressedTexSubImage1DARB(ctx->Exec,
+ (n[1].e, n[2].i, n[3].i, n[4].i,
+ n[5].e, n[6].i, n[7].data));
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_2D: /* GL_ARB_texture_compress */
+ CALL_CompressedTexSubImage2DARB(ctx->Exec,
+ (n[1].e, n[2].i, n[3].i, n[4].i,
+ n[5].i, n[6].i, n[7].e, n[8].i,
+ n[9].data));
+ break;
+ case OPCODE_COMPRESSED_TEX_SUB_IMAGE_3D: /* GL_ARB_texture_compress */
+ CALL_CompressedTexSubImage3DARB(ctx->Exec,
+ (n[1].e, n[2].i, n[3].i, n[4].i,
+ n[5].i, n[6].i, n[7].i, n[8].i,
+ n[9].e, n[10].i, n[11].data));
+ break;
+ case OPCODE_SAMPLE_COVERAGE: /* GL_ARB_multisample */
+ CALL_SampleCoverageARB(ctx->Exec, (n[1].f, n[2].b));
+ break;
+ case OPCODE_WINDOW_POS_ARB: /* GL_ARB_window_pos */
+ CALL_WindowPos3fMESA(ctx->Exec, (n[1].f, n[2].f, n[3].f));
+ break;
+#if FEATURE_NV_vertex_program || FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+ case OPCODE_BIND_PROGRAM_NV: /* GL_NV_vertex_program */
+ CALL_BindProgramNV(ctx->Exec, (n[1].e, n[2].ui));
+ break;
+#endif
+#if FEATURE_NV_vertex_program
+ case OPCODE_EXECUTE_PROGRAM_NV:
+ {
+ GLfloat v[4];
+ v[0] = n[3].f;
+ v[1] = n[4].f;
+ v[2] = n[5].f;
+ v[3] = n[6].f;
+ CALL_ExecuteProgramNV(ctx->Exec, (n[1].e, n[2].ui, v));
+ }
+ break;
+ case OPCODE_REQUEST_RESIDENT_PROGRAMS_NV:
+ CALL_RequestResidentProgramsNV(ctx->Exec, (n[1].ui,
+ (GLuint *) n[2].data));
+ break;
+ case OPCODE_LOAD_PROGRAM_NV:
+ CALL_LoadProgramNV(ctx->Exec, (n[1].e, n[2].ui, n[3].i,
+ (const GLubyte *) n[4].data));
+ break;
+ case OPCODE_TRACK_MATRIX_NV:
+ CALL_TrackMatrixNV(ctx->Exec, (n[1].e, n[2].ui, n[3].e, n[4].e));
+ break;
+#endif
+
+#if FEATURE_NV_fragment_program
+ case OPCODE_PROGRAM_LOCAL_PARAMETER_ARB:
+ CALL_ProgramLocalParameter4fARB(ctx->Exec,
+ (n[1].e, n[2].ui, n[3].f, n[4].f,
+ n[5].f, n[6].f));
+ break;
+ case OPCODE_PROGRAM_NAMED_PARAMETER_NV:
+ CALL_ProgramNamedParameter4fNV(ctx->Exec, (n[1].ui, n[2].i,
+ (const GLubyte *) n[3].
+ data, n[4].f, n[5].f,
+ n[6].f, n[7].f));
+ break;
+#endif
+
+ case OPCODE_ACTIVE_STENCIL_FACE_EXT:
+ CALL_ActiveStencilFaceEXT(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_DEPTH_BOUNDS_EXT:
+ CALL_DepthBoundsEXT(ctx->Exec, (n[1].f, n[2].f));
+ break;
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+ case OPCODE_PROGRAM_STRING_ARB:
+ CALL_ProgramStringARB(ctx->Exec,
+ (n[1].e, n[2].e, n[3].i, n[4].data));
+ break;
+#endif
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program || FEATURE_NV_vertex_program
+ case OPCODE_PROGRAM_ENV_PARAMETER_ARB:
+ CALL_ProgramEnvParameter4fARB(ctx->Exec, (n[1].e, n[2].ui, n[3].f,
+ n[4].f, n[5].f,
+ n[6].f));
+ break;
+#endif
+#if FEATURE_queryobj
+ case OPCODE_BEGIN_QUERY_ARB:
+ CALL_BeginQueryARB(ctx->Exec, (n[1].e, n[2].ui));
+ break;
+ case OPCODE_END_QUERY_ARB:
+ CALL_EndQueryARB(ctx->Exec, (n[1].e));
+ break;
+#endif
+ case OPCODE_DRAW_BUFFERS_ARB:
+ {
+ GLenum buffers[MAX_DRAW_BUFFERS];
+ GLint i, count = MIN2(n[1].i, MAX_DRAW_BUFFERS);
+ for (i = 0; i < count; i++)
+ buffers[i] = n[2 + i].e;
+ CALL_DrawBuffersARB(ctx->Exec, (n[1].i, buffers));
+ }
+ break;
+#if FEATURE_EXT_framebuffer_blit
+ case OPCODE_BLIT_FRAMEBUFFER:
+ CALL_BlitFramebufferEXT(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i,
+ n[5].i, n[6].i, n[7].i, n[8].i,
+ n[9].i, n[10].e));
+ break;
+#endif
+
+ case OPCODE_USE_PROGRAM:
+ CALL_UseProgramObjectARB(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_USE_SHADER_PROGRAM_EXT:
+ CALL_UseShaderProgramEXT(ctx->Exec, (n[1].ui, n[2].ui));
+ break;
+ case OPCODE_ACTIVE_PROGRAM_EXT:
+ CALL_ActiveProgramEXT(ctx->Exec, (n[1].ui));
+ break;
+ case OPCODE_UNIFORM_1F:
+ CALL_Uniform1fARB(ctx->Exec, (n[1].i, n[2].f));
+ break;
+ case OPCODE_UNIFORM_2F:
+ CALL_Uniform2fARB(ctx->Exec, (n[1].i, n[2].f, n[3].f));
+ break;
+ case OPCODE_UNIFORM_3F:
+ CALL_Uniform3fARB(ctx->Exec, (n[1].i, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_UNIFORM_4F:
+ CALL_Uniform4fARB(ctx->Exec,
+ (n[1].i, n[2].f, n[3].f, n[4].f, n[5].f));
+ break;
+ case OPCODE_UNIFORM_1FV:
+ CALL_Uniform1fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_2FV:
+ CALL_Uniform2fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_3FV:
+ CALL_Uniform3fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_4FV:
+ CALL_Uniform4fvARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_1I:
+ CALL_Uniform1iARB(ctx->Exec, (n[1].i, n[2].i));
+ break;
+ case OPCODE_UNIFORM_2I:
+ CALL_Uniform2iARB(ctx->Exec, (n[1].i, n[2].i, n[3].i));
+ break;
+ case OPCODE_UNIFORM_3I:
+ CALL_Uniform3iARB(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
+ break;
+ case OPCODE_UNIFORM_4I:
+ CALL_Uniform4iARB(ctx->Exec,
+ (n[1].i, n[2].i, n[3].i, n[4].i, n[5].i));
+ break;
+ case OPCODE_UNIFORM_1IV:
+ CALL_Uniform1ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_2IV:
+ CALL_Uniform2ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_3IV:
+ CALL_Uniform3ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_4IV:
+ CALL_Uniform4ivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));
+ break;
+ case OPCODE_UNIFORM_1UI:
+ /*CALL_Uniform1uiARB(ctx->Exec, (n[1].i, n[2].i));*/
+ break;
+ case OPCODE_UNIFORM_2UI:
+ /*CALL_Uniform2uiARB(ctx->Exec, (n[1].i, n[2].i, n[3].i));*/
+ break;
+ case OPCODE_UNIFORM_3UI:
+ /*CALL_Uniform3uiARB(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));*/
+ break;
+ case OPCODE_UNIFORM_4UI:
+ /*CALL_Uniform4uiARB(ctx->Exec,
+ (n[1].i, n[2].i, n[3].i, n[4].i, n[5].i));
+ */
+ break;
+ case OPCODE_UNIFORM_1UIV:
+ /*CALL_Uniform1uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
+ break;
+ case OPCODE_UNIFORM_2UIV:
+ /*CALL_Uniform2uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
+ break;
+ case OPCODE_UNIFORM_3UIV:
+ /*CALL_Uniform3uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
+ break;
+ case OPCODE_UNIFORM_4UIV:
+ /*CALL_Uniform4uivARB(ctx->Exec, (n[1].i, n[2].i, n[3].data));*/
+ break;
+ case OPCODE_UNIFORM_MATRIX22:
+ CALL_UniformMatrix2fvARB(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX33:
+ CALL_UniformMatrix3fvARB(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX44:
+ CALL_UniformMatrix4fvARB(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX23:
+ CALL_UniformMatrix2x3fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX32:
+ CALL_UniformMatrix3x2fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX24:
+ CALL_UniformMatrix2x4fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX42:
+ CALL_UniformMatrix4x2fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX34:
+ CALL_UniformMatrix3x4fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+ case OPCODE_UNIFORM_MATRIX43:
+ CALL_UniformMatrix4x3fv(ctx->Exec,
+ (n[1].i, n[2].i, n[3].b, n[4].data));
+ break;
+
+ case OPCODE_TEX_BUMP_PARAMETER_ATI:
+ {
+ GLfloat values[4];
+ GLuint i, pname = n[1].ui;
+
+ for (i = 0; i < 4; i++)
+ values[i] = n[1 + i].f;
+ CALL_TexBumpParameterfvATI(ctx->Exec, (pname, values));
+ }
+ break;
+#if FEATURE_ATI_fragment_shader
+ case OPCODE_BIND_FRAGMENT_SHADER_ATI:
+ CALL_BindFragmentShaderATI(ctx->Exec, (n[1].i));
+ break;
+ case OPCODE_SET_FRAGMENT_SHADER_CONSTANTS_ATI:
+ {
+ GLfloat values[4];
+ GLuint i, dst = n[1].ui;
+
+ for (i = 0; i < 4; i++)
+ values[i] = n[1 + i].f;
+ CALL_SetFragmentShaderConstantATI(ctx->Exec, (dst, values));
+ }
+ break;
+#endif
+ case OPCODE_ATTR_1F_NV:
+ CALL_VertexAttrib1fNV(ctx->Exec, (n[1].e, n[2].f));
+ break;
+ case OPCODE_ATTR_2F_NV:
+ /* Really shouldn't have to do this - the Node structure
+ * is convenient, but it would be better to store the data
+ * packed appropriately so that it can be sent directly
+ * on. With x86_64 becoming common, this will start to
+ * matter more.
+ */
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib2fvNV(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib2fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f));
+ break;
+ case OPCODE_ATTR_3F_NV:
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib3fvNV(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib3fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f,
+ n[4].f));
+ break;
+ case OPCODE_ATTR_4F_NV:
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib4fvNV(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib4fNV(ctx->Exec, (n[1].e, n[2].f, n[3].f,
+ n[4].f, n[5].f));
+ break;
+ case OPCODE_ATTR_1F_ARB:
+ CALL_VertexAttrib1fARB(ctx->Exec, (n[1].e, n[2].f));
+ break;
+ case OPCODE_ATTR_2F_ARB:
+ /* Really shouldn't have to do this - the Node structure
+ * is convenient, but it would be better to store the data
+ * packed appropriately so that it can be sent directly
+ * on. With x86_64 becoming common, this will start to
+ * matter more.
+ */
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib2fvARB(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib2fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f));
+ break;
+ case OPCODE_ATTR_3F_ARB:
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib3fvARB(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib3fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f,
+ n[4].f));
+ break;
+ case OPCODE_ATTR_4F_ARB:
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_VertexAttrib4fvARB(ctx->Exec, (n[1].e, &n[2].f));
+ else
+ CALL_VertexAttrib4fARB(ctx->Exec, (n[1].e, n[2].f, n[3].f,
+ n[4].f, n[5].f));
+ break;
+ case OPCODE_MATERIAL:
+ if (sizeof(Node) == sizeof(GLfloat))
+ CALL_Materialfv(ctx->Exec, (n[1].e, n[2].e, &n[3].f));
+ else {
+ GLfloat f[4];
+ f[0] = n[3].f;
+ f[1] = n[4].f;
+ f[2] = n[5].f;
+ f[3] = n[6].f;
+ CALL_Materialfv(ctx->Exec, (n[1].e, n[2].e, f));
+ }
+ break;
+ case OPCODE_BEGIN:
+ CALL_Begin(ctx->Exec, (n[1].e));
+ break;
+ case OPCODE_END:
+ CALL_End(ctx->Exec, ());
+ break;
+ case OPCODE_RECTF:
+ CALL_Rectf(ctx->Exec, (n[1].f, n[2].f, n[3].f, n[4].f));
+ break;
+ case OPCODE_EVAL_C1:
+ CALL_EvalCoord1f(ctx->Exec, (n[1].f));
+ break;
+ case OPCODE_EVAL_C2:
+ CALL_EvalCoord2f(ctx->Exec, (n[1].f, n[2].f));
+ break;
+ case OPCODE_EVAL_P1:
+ CALL_EvalPoint1(ctx->Exec, (n[1].i));
+ break;
+ case OPCODE_EVAL_P2:
+ CALL_EvalPoint2(ctx->Exec, (n[1].i, n[2].i));
+ break;
+
+ /* GL_EXT_texture_integer */
+ case OPCODE_CLEARCOLOR_I:
+ CALL_ClearColorIiEXT(ctx->Exec, (n[1].i, n[2].i, n[3].i, n[4].i));
+ break;
+ case OPCODE_CLEARCOLOR_UI:
+ CALL_ClearColorIuiEXT(ctx->Exec,
+ (n[1].ui, n[2].ui, n[3].ui, n[4].ui));
+ break;
+ case OPCODE_TEXPARAMETER_I:
+ {
+ GLint params[4];
+ params[0] = n[3].i;
+ params[1] = n[4].i;
+ params[2] = n[5].i;
+ params[3] = n[6].i;
+ CALL_TexParameterIivEXT(ctx->Exec, (n[1].e, n[2].e, params));
+ }
+ break;
+ case OPCODE_TEXPARAMETER_UI:
+ {
+ GLuint params[4];
+ params[0] = n[3].ui;
+ params[1] = n[4].ui;
+ params[2] = n[5].ui;
+ params[3] = n[6].ui;
+ CALL_TexParameterIuivEXT(ctx->Exec, (n[1].e, n[2].e, params));
+ }
+ break;
+
+ case OPCODE_VERTEX_ATTRIB_DIVISOR:
+ /* GL_ARB_instanced_arrays */
+ CALL_VertexAttribDivisorARB(ctx->Exec, (n[1].ui, n[2].ui));
+ break;
+
+ case OPCODE_CONTINUE:
+ n = (Node *) n[1].next;
+ break;
+ case OPCODE_END_OF_LIST:
+ done = GL_TRUE;
+ break;
+ default:
+ {
+ char msg[1000];
+ _mesa_snprintf(msg, sizeof(msg), "Error in execute_list: opcode=%d",
+ (int) opcode);
+ _mesa_problem(ctx, "%s", msg);
+ }
+ done = GL_TRUE;
+ }
+
+ /* increment n to point to next compiled command */
+ if (opcode != OPCODE_CONTINUE) {
+ n += InstSize[opcode];
+ }
+ }
+ }
+
+ if (ctx->Driver.EndCallList)
+ ctx->Driver.EndCallList(ctx);
+
+ ctx->ListState.CallDepth--;
+}
+
+
+
+/**********************************************************************/
+/* GL functions */
+/**********************************************************************/
+
+/**
+ * Test if a display list number is valid.
+ */
+static GLboolean GLAPIENTRY
+_mesa_IsList(GLuint list)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0); /* must be called before assert */
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
+ return islist(ctx, list);
+}
+
+
+/**
+ * Delete a sequence of consecutive display lists.
+ */
+static void GLAPIENTRY
+_mesa_DeleteLists(GLuint list, GLsizei range)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLuint i;
+ FLUSH_VERTICES(ctx, 0); /* must be called before assert */
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (range < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteLists");
+ return;
+ }
+ for (i = list; i < list + range; i++) {
+ destroy_list(ctx, i);
+ }
+}
+
+
+/**
+ * Return a display list number, n, such that lists n through n+range-1
+ * are free.
+ */
+static GLuint GLAPIENTRY
+_mesa_GenLists(GLsizei range)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLuint base;
+ FLUSH_VERTICES(ctx, 0); /* must be called before assert */
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, 0);
+
+ if (range < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGenLists");
+ return 0;
+ }
+ if (range == 0) {
+ return 0;
+ }
+
+ /*
+ * Make this an atomic operation
+ */
+ _glthread_LOCK_MUTEX(ctx->Shared->Mutex);
+
+ base = _mesa_HashFindFreeKeyBlock(ctx->Shared->DisplayList, range);
+ if (base) {
+ /* reserve the list IDs by with empty/dummy lists */
+ GLint i;
+ for (i = 0; i < range; i++) {
+ _mesa_HashInsert(ctx->Shared->DisplayList, base + i,
+ make_list(base + i, 1));
+ }
+ }
+
+ _glthread_UNLOCK_MUTEX(ctx->Shared->Mutex);
+
+ return base;
+}
+
+
+/**
+ * Begin a new display list.
+ */
+static void GLAPIENTRY
+_mesa_NewList(GLuint name, GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ FLUSH_CURRENT(ctx, 0); /* must be called before assert */
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glNewList %u %s\n", name,
+ _mesa_lookup_enum_by_nr(mode));
+
+ if (name == 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glNewList");
+ return;
+ }
+
+ if (mode != GL_COMPILE && mode != GL_COMPILE_AND_EXECUTE) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glNewList");
+ return;
+ }
+
+ if (ctx->ListState.CurrentList) {
+ /* already compiling a display list */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glNewList");
+ return;
+ }
+
+ ctx->CompileFlag = GL_TRUE;
+ ctx->ExecuteFlag = (mode == GL_COMPILE_AND_EXECUTE);
+
+ /* Reset acumulated list state:
+ */
+ invalidate_saved_current_state( ctx );
+
+ /* Allocate new display list */
+ ctx->ListState.CurrentList = make_list(name, BLOCK_SIZE);
+ ctx->ListState.CurrentBlock = ctx->ListState.CurrentList->Head;
+ ctx->ListState.CurrentPos = 0;
+
+ ctx->Driver.NewList(ctx, name, mode);
+
+ ctx->CurrentDispatch = ctx->Save;
+ _glapi_set_dispatch(ctx->CurrentDispatch);
+}
+
+
+/**
+ * End definition of current display list.
+ */
+static void GLAPIENTRY
+_mesa_EndList(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ SAVE_FLUSH_VERTICES(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glEndList\n");
+
+ /* Check that a list is under construction */
+ if (!ctx->ListState.CurrentList) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glEndList");
+ return;
+ }
+
+ /* Call before emitting END_OF_LIST, in case the driver wants to
+ * emit opcodes itself.
+ */
+ ctx->Driver.EndList(ctx);
+
+ (void) alloc_instruction(ctx, OPCODE_END_OF_LIST, 0);
+
+ /* Destroy old list, if any */
+ destroy_list(ctx, ctx->ListState.CurrentList->Name);
+
+ /* Install the new list */
+ _mesa_HashInsert(ctx->Shared->DisplayList,
+ ctx->ListState.CurrentList->Name,
+ ctx->ListState.CurrentList);
+
+
+ if (MESA_VERBOSE & VERBOSE_DISPLAY_LIST)
+ mesa_print_display_list(ctx->ListState.CurrentList->Name);
+
+ ctx->ListState.CurrentList = NULL;
+ ctx->ExecuteFlag = GL_TRUE;
+ ctx->CompileFlag = GL_FALSE;
+
+ ctx->CurrentDispatch = ctx->Exec;
+ _glapi_set_dispatch(ctx->CurrentDispatch);
+}
+
+
+void GLAPIENTRY
+_mesa_CallList(GLuint list)
+{
+ GLboolean save_compile_flag;
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_CURRENT(ctx, 0);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glCallList %d\n", list);
+
+ if (list == 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glCallList(list==0)");
+ return;
+ }
+
+ if (0)
+ mesa_print_display_list( list );
+
+ /* VERY IMPORTANT: Save the CompileFlag status, turn it off,
+ * execute the display list, and restore the CompileFlag.
+ */
+ save_compile_flag = ctx->CompileFlag;
+ if (save_compile_flag) {
+ ctx->CompileFlag = GL_FALSE;
+ }
+
+ execute_list(ctx, list);
+ ctx->CompileFlag = save_compile_flag;
+
+ /* also restore API function pointers to point to "save" versions */
+ if (save_compile_flag) {
+ ctx->CurrentDispatch = ctx->Save;
+ _glapi_set_dispatch(ctx->CurrentDispatch);
+ }
+}
+
+
+/**
+ * Execute glCallLists: call multiple display lists.
+ */
+void GLAPIENTRY
+_mesa_CallLists(GLsizei n, GLenum type, const GLvoid * lists)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint i;
+ GLboolean save_compile_flag;
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glCallLists %d\n", n);
+
+ switch (type) {
+ case GL_BYTE:
+ case GL_UNSIGNED_BYTE:
+ case GL_SHORT:
+ case GL_UNSIGNED_SHORT:
+ case GL_INT:
+ case GL_UNSIGNED_INT:
+ case GL_FLOAT:
+ case GL_2_BYTES:
+ case GL_3_BYTES:
+ case GL_4_BYTES:
+ /* OK */
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glCallLists(type)");
+ return;
+ }
+
+ /* Save the CompileFlag status, turn it off, execute display list,
+ * and restore the CompileFlag.
+ */
+ save_compile_flag = ctx->CompileFlag;
+ ctx->CompileFlag = GL_FALSE;
+
+ for (i = 0; i < n; i++) {
+ GLuint list = (GLuint) (ctx->List.ListBase + translate_id(i, type, lists));
+ execute_list(ctx, list);
+ }
+
+ ctx->CompileFlag = save_compile_flag;
+
+ /* also restore API function pointers to point to "save" versions */
+ if (save_compile_flag) {
+ ctx->CurrentDispatch = ctx->Save;
+ _glapi_set_dispatch(ctx->CurrentDispatch);
+ }
+}
+
+
+/**
+ * Set the offset added to list numbers in glCallLists.
+ */
+static void GLAPIENTRY
+_mesa_ListBase(GLuint base)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0); /* must be called before assert */
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+ ctx->List.ListBase = base;
+}
+
+
+/* Can no longer assume ctx->Exec->Func is equal to _mesa_Func.
+ */
+static void GLAPIENTRY
+exec_Finish(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_Finish(ctx->Exec, ());
+}
+
+static void GLAPIENTRY
+exec_Flush(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_Flush(ctx->Exec, ());
+}
+
+static void GLAPIENTRY
+exec_GetBooleanv(GLenum pname, GLboolean *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetBooleanv(ctx->Exec, (pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetClipPlane(GLenum plane, GLdouble * equation)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetClipPlane(ctx->Exec, (plane, equation));
+}
+
+static void GLAPIENTRY
+exec_GetDoublev(GLenum pname, GLdouble *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetDoublev(ctx->Exec, (pname, params));
+}
+
+static GLenum GLAPIENTRY
+exec_GetError(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_GetError(ctx->Exec, ());
+}
+
+static void GLAPIENTRY
+exec_GetFloatv(GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetFloatv(ctx->Exec, (pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetIntegerv(GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetIntegerv(ctx->Exec, (pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetLightfv(GLenum light, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetLightfv(ctx->Exec, (light, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetLightiv(GLenum light, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetLightiv(ctx->Exec, (light, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetMapdv(GLenum target, GLenum query, GLdouble * v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMapdv(ctx->Exec, (target, query, v));
+}
+
+static void GLAPIENTRY
+exec_GetMapfv(GLenum target, GLenum query, GLfloat * v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMapfv(ctx->Exec, (target, query, v));
+}
+
+static void GLAPIENTRY
+exec_GetMapiv(GLenum target, GLenum query, GLint * v)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMapiv(ctx->Exec, (target, query, v));
+}
+
+static void GLAPIENTRY
+exec_GetMaterialfv(GLenum face, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMaterialfv(ctx->Exec, (face, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetMaterialiv(GLenum face, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMaterialiv(ctx->Exec, (face, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetPixelMapfv(GLenum map, GLfloat *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetPixelMapfv(ctx->Exec, (map, values));
+}
+
+static void GLAPIENTRY
+exec_GetPixelMapuiv(GLenum map, GLuint *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetPixelMapuiv(ctx->Exec, (map, values));
+}
+
+static void GLAPIENTRY
+exec_GetPixelMapusv(GLenum map, GLushort *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetPixelMapusv(ctx->Exec, (map, values));
+}
+
+static void GLAPIENTRY
+exec_GetPolygonStipple(GLubyte * dest)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetPolygonStipple(ctx->Exec, (dest));
+}
+
+static const GLubyte *GLAPIENTRY
+exec_GetString(GLenum name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_GetString(ctx->Exec, (name));
+}
+
+static void GLAPIENTRY
+exec_GetTexEnvfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexEnvfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexEnviv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexEnviv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexGendv(GLenum coord, GLenum pname, GLdouble *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexGendv(ctx->Exec, (coord, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexGenfv(GLenum coord, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexGenfv(ctx->Exec, (coord, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexGeniv(GLenum coord, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexGeniv(ctx->Exec, (coord, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexImage(GLenum target, GLint level, GLenum format,
+ GLenum type, GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexImage(ctx->Exec, (target, level, format, type, pixels));
+}
+
+static void GLAPIENTRY
+exec_GetTexLevelParameterfv(GLenum target, GLint level,
+ GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexLevelParameterfv(ctx->Exec, (target, level, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexLevelParameteriv(GLenum target, GLint level,
+ GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexLevelParameteriv(ctx->Exec, (target, level, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexParameterfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetTexParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetTexParameteriv(ctx->Exec, (target, pname, params));
+}
+
+static GLboolean GLAPIENTRY
+exec_IsEnabled(GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_IsEnabled(ctx->Exec, (cap));
+}
+
+static void GLAPIENTRY
+exec_PixelStoref(GLenum pname, GLfloat param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_PixelStoref(ctx->Exec, (pname, param));
+}
+
+static void GLAPIENTRY
+exec_PixelStorei(GLenum pname, GLint param)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_PixelStorei(ctx->Exec, (pname, param));
+}
+
+static void GLAPIENTRY
+exec_ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height,
+ GLenum format, GLenum type, GLvoid * pixels)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_ReadPixels(ctx->Exec, (x, y, width, height, format, type, pixels));
+}
+
+static GLint GLAPIENTRY
+exec_RenderMode(GLenum mode)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_RenderMode(ctx->Exec, (mode));
+}
+
+static void GLAPIENTRY
+exec_FeedbackBuffer(GLsizei size, GLenum type, GLfloat * buffer)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_FeedbackBuffer(ctx->Exec, (size, type, buffer));
+}
+
+static void GLAPIENTRY
+exec_SelectBuffer(GLsizei size, GLuint * buffer)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_SelectBuffer(ctx->Exec, (size, buffer));
+}
+
+static GLboolean GLAPIENTRY
+exec_AreTexturesResident(GLsizei n, const GLuint * texName,
+ GLboolean * residences)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_AreTexturesResident(ctx->Exec, (n, texName, residences));
+}
+
+static void GLAPIENTRY
+exec_ColorPointer(GLint size, GLenum type, GLsizei stride, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_ColorPointer(ctx->Exec, (size, type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_DeleteTextures(GLsizei n, const GLuint * texName)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_DeleteTextures(ctx->Exec, (n, texName));
+}
+
+static void GLAPIENTRY
+exec_DisableClientState(GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_DisableClientState(ctx->Exec, (cap));
+}
+
+static void GLAPIENTRY
+exec_EdgeFlagPointer(GLsizei stride, const GLvoid * vptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_EdgeFlagPointer(ctx->Exec, (stride, vptr));
+}
+
+static void GLAPIENTRY
+exec_EnableClientState(GLenum cap)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_EnableClientState(ctx->Exec, (cap));
+}
+
+static void GLAPIENTRY
+exec_GenTextures(GLsizei n, GLuint * texName)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GenTextures(ctx->Exec, (n, texName));
+}
+
+static void GLAPIENTRY
+exec_GetPointerv(GLenum pname, GLvoid **params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetPointerv(ctx->Exec, (pname, params));
+}
+
+static void GLAPIENTRY
+exec_IndexPointer(GLenum type, GLsizei stride, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_IndexPointer(ctx->Exec, (type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_InterleavedArrays(GLenum format, GLsizei stride, const GLvoid * pointer)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_InterleavedArrays(ctx->Exec, (format, stride, pointer));
+}
+
+static GLboolean GLAPIENTRY
+exec_IsTexture(GLuint texture)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ return CALL_IsTexture(ctx->Exec, (texture));
+}
+
+static void GLAPIENTRY
+exec_NormalPointer(GLenum type, GLsizei stride, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_NormalPointer(ctx->Exec, (type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_PopClientAttrib(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_PopClientAttrib(ctx->Exec, ());
+}
+
+static void GLAPIENTRY
+exec_PushClientAttrib(GLbitfield mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_PushClientAttrib(ctx->Exec, (mask));
+}
+
+static void GLAPIENTRY
+exec_TexCoordPointer(GLint size, GLenum type, GLsizei stride,
+ const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_TexCoordPointer(ctx->Exec, (size, type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_GetCompressedTexImageARB(GLenum target, GLint level, GLvoid * img)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetCompressedTexImageARB(ctx->Exec, (target, level, img));
+}
+
+static void GLAPIENTRY
+exec_VertexPointer(GLint size, GLenum type, GLsizei stride,
+ const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_VertexPointer(ctx->Exec, (size, type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_CopyConvolutionFilter1D(GLenum target, GLenum internalFormat,
+ GLint x, GLint y, GLsizei width)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_CopyConvolutionFilter1D(ctx->Exec,
+ (target, internalFormat, x, y, width));
+}
+
+static void GLAPIENTRY
+exec_CopyConvolutionFilter2D(GLenum target, GLenum internalFormat,
+ GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_CopyConvolutionFilter2D(ctx->Exec,
+ (target, internalFormat, x, y, width,
+ height));
+}
+
+static void GLAPIENTRY
+exec_GetColorTable(GLenum target, GLenum format, GLenum type, GLvoid * data)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetColorTable(ctx->Exec, (target, format, type, data));
+}
+
+static void GLAPIENTRY
+exec_GetColorTableParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetColorTableParameterfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetColorTableParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetColorTableParameteriv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetConvolutionFilter(GLenum target, GLenum format, GLenum type,
+ GLvoid * image)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetConvolutionFilter(ctx->Exec, (target, format, type, image));
+}
+
+static void GLAPIENTRY
+exec_GetConvolutionParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetConvolutionParameterfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetConvolutionParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetConvolutionParameteriv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetHistogram(GLenum target, GLboolean reset, GLenum format,
+ GLenum type, GLvoid *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetHistogram(ctx->Exec, (target, reset, format, type, values));
+}
+
+static void GLAPIENTRY
+exec_GetHistogramParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetHistogramParameterfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetHistogramParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetHistogramParameteriv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetMinmax(GLenum target, GLboolean reset, GLenum format,
+ GLenum type, GLvoid *values)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMinmax(ctx->Exec, (target, reset, format, type, values));
+}
+
+static void GLAPIENTRY
+exec_GetMinmaxParameterfv(GLenum target, GLenum pname, GLfloat *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMinmaxParameterfv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetMinmaxParameteriv(GLenum target, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetMinmaxParameteriv(ctx->Exec, (target, pname, params));
+}
+
+static void GLAPIENTRY
+exec_GetSeparableFilter(GLenum target, GLenum format, GLenum type,
+ GLvoid *row, GLvoid *column, GLvoid *span)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_GetSeparableFilter(ctx->Exec,
+ (target, format, type, row, column, span));
+}
+
+static void GLAPIENTRY
+exec_SeparableFilter2D(GLenum target, GLenum internalFormat,
+ GLsizei width, GLsizei height, GLenum format,
+ GLenum type, const GLvoid *row, const GLvoid *column)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_SeparableFilter2D(ctx->Exec,
+ (target, internalFormat, width, height, format,
+ type, row, column));
+}
+
+static void GLAPIENTRY
+exec_ColorPointerEXT(GLint size, GLenum type, GLsizei stride,
+ GLsizei count, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_ColorPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_EdgeFlagPointerEXT(GLsizei stride, GLsizei count, const GLboolean *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_EdgeFlagPointerEXT(ctx->Exec, (stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_IndexPointerEXT(GLenum type, GLsizei stride, GLsizei count,
+ const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_IndexPointerEXT(ctx->Exec, (type, stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_NormalPointerEXT(GLenum type, GLsizei stride, GLsizei count,
+ const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_NormalPointerEXT(ctx->Exec, (type, stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_TexCoordPointerEXT(GLint size, GLenum type, GLsizei stride,
+ GLsizei count, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_TexCoordPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_VertexPointerEXT(GLint size, GLenum type, GLsizei stride,
+ GLsizei count, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_VertexPointerEXT(ctx->Exec, (size, type, stride, count, ptr));
+}
+
+static void GLAPIENTRY
+exec_LockArraysEXT(GLint first, GLsizei count)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_LockArraysEXT(ctx->Exec, (first, count));
+}
+
+static void GLAPIENTRY
+exec_UnlockArraysEXT(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_UnlockArraysEXT(ctx->Exec, ());
+}
+
+static void GLAPIENTRY
+exec_ClientActiveTextureARB(GLenum target)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_ClientActiveTextureARB(ctx->Exec, (target));
+}
+
+static void GLAPIENTRY
+exec_SecondaryColorPointerEXT(GLint size, GLenum type,
+ GLsizei stride, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_SecondaryColorPointerEXT(ctx->Exec, (size, type, stride, ptr));
+}
+
+static void GLAPIENTRY
+exec_FogCoordPointerEXT(GLenum type, GLsizei stride, const GLvoid *ptr)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_FogCoordPointerEXT(ctx->Exec, (type, stride, ptr));
+}
+
+/* GL_EXT_multi_draw_arrays */
+static void GLAPIENTRY
+exec_MultiDrawArraysEXT(GLenum mode, const GLint *first,
+ const GLsizei *count, GLsizei primcount)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_MultiDrawArraysEXT(ctx->Exec, (mode, first, count, primcount));
+}
+
+/* GL_IBM_multimode_draw_arrays */
+static void GLAPIENTRY
+exec_MultiModeDrawArraysIBM(const GLenum * mode, const GLint * first,
+ const GLsizei * count, GLsizei primcount,
+ GLint modestride)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_MultiModeDrawArraysIBM(ctx->Exec,
+ (mode, first, count, primcount, modestride));
+}
+
+/* GL_IBM_multimode_draw_arrays */
+static void GLAPIENTRY
+exec_MultiModeDrawElementsIBM(const GLenum * mode,
+ const GLsizei * count,
+ GLenum type,
+ const GLvoid * const *indices,
+ GLsizei primcount, GLint modestride)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ FLUSH_VERTICES(ctx, 0);
+ CALL_MultiModeDrawElementsIBM(ctx->Exec,
+ (mode, count, type, indices, primcount,
+ modestride));
+}
+
+
+
+/**
+ * Setup the given dispatch table to point to Mesa's display list
+ * building functions.
+ *
+ * This does not include any of the tnl functions - they are
+ * initialized from _mesa_init_api_defaults and from the active vtxfmt
+ * struct.
+ */
+struct _glapi_table *
+_mesa_create_save_table(void)
+{
+ struct _glapi_table *table;
+
+ table = _mesa_alloc_dispatch_table(_gloffset_COUNT);
+ if (table == NULL)
+ return NULL;
+
+ _mesa_loopback_init_api_table(table);
+
+ /* GL 1.0 */
+ SET_Accum(table, save_Accum);
+ SET_AlphaFunc(table, save_AlphaFunc);
+ SET_Bitmap(table, save_Bitmap);
+ SET_BlendFunc(table, save_BlendFunc);
+ SET_CallList(table, save_CallList);
+ SET_CallLists(table, save_CallLists);
+ SET_Clear(table, save_Clear);
+ SET_ClearAccum(table, save_ClearAccum);
+ SET_ClearColor(table, save_ClearColor);
+ SET_ClearDepth(table, save_ClearDepth);
+ SET_ClearIndex(table, save_ClearIndex);
+ SET_ClearStencil(table, save_ClearStencil);
+ SET_ClipPlane(table, save_ClipPlane);
+ SET_ColorMask(table, save_ColorMask);
+ SET_ColorMaskIndexedEXT(table, save_ColorMaskIndexed);
+ SET_ColorMaterial(table, save_ColorMaterial);
+ SET_CopyPixels(table, save_CopyPixels);
+ SET_CullFace(table, save_CullFace);
+ SET_DeleteLists(table, _mesa_DeleteLists);
+ SET_DepthFunc(table, save_DepthFunc);
+ SET_DepthMask(table, save_DepthMask);
+ SET_DepthRange(table, save_DepthRange);
+ SET_Disable(table, save_Disable);
+ SET_DisableIndexedEXT(table, save_DisableIndexed);
+ SET_DrawBuffer(table, save_DrawBuffer);
+ SET_DrawPixels(table, save_DrawPixels);
+ SET_Enable(table, save_Enable);
+ SET_EnableIndexedEXT(table, save_EnableIndexed);
+ SET_EndList(table, _mesa_EndList);
+ SET_EvalMesh1(table, save_EvalMesh1);
+ SET_EvalMesh2(table, save_EvalMesh2);
+ SET_Finish(table, exec_Finish);
+ SET_Flush(table, exec_Flush);
+ SET_Fogf(table, save_Fogf);
+ SET_Fogfv(table, save_Fogfv);
+ SET_Fogi(table, save_Fogi);
+ SET_Fogiv(table, save_Fogiv);
+ SET_FrontFace(table, save_FrontFace);
+ SET_Frustum(table, save_Frustum);
+ SET_GenLists(table, _mesa_GenLists);
+ SET_GetBooleanv(table, exec_GetBooleanv);
+ SET_GetClipPlane(table, exec_GetClipPlane);
+ SET_GetDoublev(table, exec_GetDoublev);
+ SET_GetError(table, exec_GetError);
+ SET_GetFloatv(table, exec_GetFloatv);
+ SET_GetIntegerv(table, exec_GetIntegerv);
+ SET_GetLightfv(table, exec_GetLightfv);
+ SET_GetLightiv(table, exec_GetLightiv);
+ SET_GetMapdv(table, exec_GetMapdv);
+ SET_GetMapfv(table, exec_GetMapfv);
+ SET_GetMapiv(table, exec_GetMapiv);
+ SET_GetMaterialfv(table, exec_GetMaterialfv);
+ SET_GetMaterialiv(table, exec_GetMaterialiv);
+ SET_GetPixelMapfv(table, exec_GetPixelMapfv);
+ SET_GetPixelMapuiv(table, exec_GetPixelMapuiv);
+ SET_GetPixelMapusv(table, exec_GetPixelMapusv);
+ SET_GetPolygonStipple(table, exec_GetPolygonStipple);
+ SET_GetString(table, exec_GetString);
+ SET_GetTexEnvfv(table, exec_GetTexEnvfv);
+ SET_GetTexEnviv(table, exec_GetTexEnviv);
+ SET_GetTexGendv(table, exec_GetTexGendv);
+ SET_GetTexGenfv(table, exec_GetTexGenfv);
+ SET_GetTexGeniv(table, exec_GetTexGeniv);
+ SET_GetTexImage(table, exec_GetTexImage);
+ SET_GetTexLevelParameterfv(table, exec_GetTexLevelParameterfv);
+ SET_GetTexLevelParameteriv(table, exec_GetTexLevelParameteriv);
+ SET_GetTexParameterfv(table, exec_GetTexParameterfv);
+ SET_GetTexParameteriv(table, exec_GetTexParameteriv);
+ SET_Hint(table, save_Hint);
+ SET_IndexMask(table, save_IndexMask);
+ SET_InitNames(table, save_InitNames);
+ SET_IsEnabled(table, exec_IsEnabled);
+ SET_IsList(table, _mesa_IsList);
+ SET_LightModelf(table, save_LightModelf);
+ SET_LightModelfv(table, save_LightModelfv);
+ SET_LightModeli(table, save_LightModeli);
+ SET_LightModeliv(table, save_LightModeliv);
+ SET_Lightf(table, save_Lightf);
+ SET_Lightfv(table, save_Lightfv);
+ SET_Lighti(table, save_Lighti);
+ SET_Lightiv(table, save_Lightiv);
+ SET_LineStipple(table, save_LineStipple);
+ SET_LineWidth(table, save_LineWidth);
+ SET_ListBase(table, save_ListBase);
+ SET_LoadIdentity(table, save_LoadIdentity);
+ SET_LoadMatrixd(table, save_LoadMatrixd);
+ SET_LoadMatrixf(table, save_LoadMatrixf);
+ SET_LoadName(table, save_LoadName);
+ SET_LogicOp(table, save_LogicOp);
+ SET_Map1d(table, save_Map1d);
+ SET_Map1f(table, save_Map1f);
+ SET_Map2d(table, save_Map2d);
+ SET_Map2f(table, save_Map2f);
+ SET_MapGrid1d(table, save_MapGrid1d);
+ SET_MapGrid1f(table, save_MapGrid1f);
+ SET_MapGrid2d(table, save_MapGrid2d);
+ SET_MapGrid2f(table, save_MapGrid2f);
+ SET_MatrixMode(table, save_MatrixMode);
+ SET_MultMatrixd(table, save_MultMatrixd);
+ SET_MultMatrixf(table, save_MultMatrixf);
+ SET_NewList(table, save_NewList);
+ SET_Ortho(table, save_Ortho);
+ SET_PassThrough(table, save_PassThrough);
+ SET_PixelMapfv(table, save_PixelMapfv);
+ SET_PixelMapuiv(table, save_PixelMapuiv);
+ SET_PixelMapusv(table, save_PixelMapusv);
+ SET_PixelStoref(table, exec_PixelStoref);
+ SET_PixelStorei(table, exec_PixelStorei);
+ SET_PixelTransferf(table, save_PixelTransferf);
+ SET_PixelTransferi(table, save_PixelTransferi);
+ SET_PixelZoom(table, save_PixelZoom);
+ SET_PointSize(table, save_PointSize);
+ SET_PolygonMode(table, save_PolygonMode);
+ SET_PolygonOffset(table, save_PolygonOffset);
+ SET_PolygonStipple(table, save_PolygonStipple);
+ SET_PopAttrib(table, save_PopAttrib);
+ SET_PopMatrix(table, save_PopMatrix);
+ SET_PopName(table, save_PopName);
+ SET_PushAttrib(table, save_PushAttrib);
+ SET_PushMatrix(table, save_PushMatrix);
+ SET_PushName(table, save_PushName);
+ SET_RasterPos2d(table, save_RasterPos2d);
+ SET_RasterPos2dv(table, save_RasterPos2dv);
+ SET_RasterPos2f(table, save_RasterPos2f);
+ SET_RasterPos2fv(table, save_RasterPos2fv);
+ SET_RasterPos2i(table, save_RasterPos2i);
+ SET_RasterPos2iv(table, save_RasterPos2iv);
+ SET_RasterPos2s(table, save_RasterPos2s);
+ SET_RasterPos2sv(table, save_RasterPos2sv);
+ SET_RasterPos3d(table, save_RasterPos3d);
+ SET_RasterPos3dv(table, save_RasterPos3dv);
+ SET_RasterPos3f(table, save_RasterPos3f);
+ SET_RasterPos3fv(table, save_RasterPos3fv);
+ SET_RasterPos3i(table, save_RasterPos3i);
+ SET_RasterPos3iv(table, save_RasterPos3iv);
+ SET_RasterPos3s(table, save_RasterPos3s);
+ SET_RasterPos3sv(table, save_RasterPos3sv);
+ SET_RasterPos4d(table, save_RasterPos4d);
+ SET_RasterPos4dv(table, save_RasterPos4dv);
+ SET_RasterPos4f(table, save_RasterPos4f);
+ SET_RasterPos4fv(table, save_RasterPos4fv);
+ SET_RasterPos4i(table, save_RasterPos4i);
+ SET_RasterPos4iv(table, save_RasterPos4iv);
+ SET_RasterPos4s(table, save_RasterPos4s);
+ SET_RasterPos4sv(table, save_RasterPos4sv);
+ SET_ReadBuffer(table, save_ReadBuffer);
+ SET_ReadPixels(table, exec_ReadPixels);
+ SET_RenderMode(table, exec_RenderMode);
+ SET_Rotated(table, save_Rotated);
+ SET_Rotatef(table, save_Rotatef);
+ SET_Scaled(table, save_Scaled);
+ SET_Scalef(table, save_Scalef);
+ SET_Scissor(table, save_Scissor);
+ SET_FeedbackBuffer(table, exec_FeedbackBuffer);
+ SET_SelectBuffer(table, exec_SelectBuffer);
+ SET_ShadeModel(table, save_ShadeModel);
+ SET_StencilFunc(table, save_StencilFunc);
+ SET_StencilMask(table, save_StencilMask);
+ SET_StencilOp(table, save_StencilOp);
+ SET_TexEnvf(table, save_TexEnvf);
+ SET_TexEnvfv(table, save_TexEnvfv);
+ SET_TexEnvi(table, save_TexEnvi);
+ SET_TexEnviv(table, save_TexEnviv);
+ SET_TexGend(table, save_TexGend);
+ SET_TexGendv(table, save_TexGendv);
+ SET_TexGenf(table, save_TexGenf);
+ SET_TexGenfv(table, save_TexGenfv);
+ SET_TexGeni(table, save_TexGeni);
+ SET_TexGeniv(table, save_TexGeniv);
+ SET_TexImage1D(table, save_TexImage1D);
+ SET_TexImage2D(table, save_TexImage2D);
+ SET_TexParameterf(table, save_TexParameterf);
+ SET_TexParameterfv(table, save_TexParameterfv);
+ SET_TexParameteri(table, save_TexParameteri);
+ SET_TexParameteriv(table, save_TexParameteriv);
+ SET_Translated(table, save_Translated);
+ SET_Translatef(table, save_Translatef);
+ SET_Viewport(table, save_Viewport);
+
+ /* GL 1.1 */
+ SET_AreTexturesResident(table, exec_AreTexturesResident);
+ SET_BindTexture(table, save_BindTexture);
+ SET_ColorPointer(table, exec_ColorPointer);
+ SET_CopyTexImage1D(table, save_CopyTexImage1D);
+ SET_CopyTexImage2D(table, save_CopyTexImage2D);
+ SET_CopyTexSubImage1D(table, save_CopyTexSubImage1D);
+ SET_CopyTexSubImage2D(table, save_CopyTexSubImage2D);
+ SET_DeleteTextures(table, exec_DeleteTextures);
+ SET_DisableClientState(table, exec_DisableClientState);
+ SET_EdgeFlagPointer(table, exec_EdgeFlagPointer);
+ SET_EnableClientState(table, exec_EnableClientState);
+ SET_GenTextures(table, exec_GenTextures);
+ SET_GetPointerv(table, exec_GetPointerv);
+ SET_IndexPointer(table, exec_IndexPointer);
+ SET_InterleavedArrays(table, exec_InterleavedArrays);
+ SET_IsTexture(table, exec_IsTexture);
+ SET_NormalPointer(table, exec_NormalPointer);
+ SET_PopClientAttrib(table, exec_PopClientAttrib);
+ SET_PrioritizeTextures(table, save_PrioritizeTextures);
+ SET_PushClientAttrib(table, exec_PushClientAttrib);
+ SET_TexCoordPointer(table, exec_TexCoordPointer);
+ SET_TexSubImage1D(table, save_TexSubImage1D);
+ SET_TexSubImage2D(table, save_TexSubImage2D);
+ SET_VertexPointer(table, exec_VertexPointer);
+
+ /* GL 1.2 */
+ SET_CopyTexSubImage3D(table, save_CopyTexSubImage3D);
+ SET_TexImage3D(table, save_TexImage3D);
+ SET_TexSubImage3D(table, save_TexSubImage3D);
+
+ /* GL 2.0 */
+ SET_StencilFuncSeparate(table, save_StencilFuncSeparate);
+ SET_StencilMaskSeparate(table, save_StencilMaskSeparate);
+ SET_StencilOpSeparate(table, save_StencilOpSeparate);
+
+ /* ATI_separate_stencil */
+ SET_StencilFuncSeparateATI(table, save_StencilFuncSeparateATI);
+
+ /* GL_ARB_imaging */
+ /* Not all are supported */
+ SET_BlendColor(table, save_BlendColor);
+ SET_BlendEquation(table, save_BlendEquation);
+ SET_ColorSubTable(table, save_ColorSubTable);
+ SET_ColorTable(table, save_ColorTable);
+ SET_ColorTableParameterfv(table, save_ColorTableParameterfv);
+ SET_ColorTableParameteriv(table, save_ColorTableParameteriv);
+ SET_ConvolutionFilter1D(table, save_ConvolutionFilter1D);
+ SET_ConvolutionFilter2D(table, save_ConvolutionFilter2D);
+ SET_ConvolutionParameterf(table, save_ConvolutionParameterf);
+ SET_ConvolutionParameterfv(table, save_ConvolutionParameterfv);
+ SET_ConvolutionParameteri(table, save_ConvolutionParameteri);
+ SET_ConvolutionParameteriv(table, save_ConvolutionParameteriv);
+ SET_CopyColorSubTable(table, save_CopyColorSubTable);
+ SET_CopyColorTable(table, save_CopyColorTable);
+ SET_CopyConvolutionFilter1D(table, exec_CopyConvolutionFilter1D);
+ SET_CopyConvolutionFilter2D(table, exec_CopyConvolutionFilter2D);
+ SET_GetColorTable(table, exec_GetColorTable);
+ SET_GetColorTableParameterfv(table, exec_GetColorTableParameterfv);
+ SET_GetColorTableParameteriv(table, exec_GetColorTableParameteriv);
+ SET_GetConvolutionFilter(table, exec_GetConvolutionFilter);
+ SET_GetConvolutionParameterfv(table, exec_GetConvolutionParameterfv);
+ SET_GetConvolutionParameteriv(table, exec_GetConvolutionParameteriv);
+ SET_GetHistogram(table, exec_GetHistogram);
+ SET_GetHistogramParameterfv(table, exec_GetHistogramParameterfv);
+ SET_GetHistogramParameteriv(table, exec_GetHistogramParameteriv);
+ SET_GetMinmax(table, exec_GetMinmax);
+ SET_GetMinmaxParameterfv(table, exec_GetMinmaxParameterfv);
+ SET_GetMinmaxParameteriv(table, exec_GetMinmaxParameteriv);
+ SET_GetSeparableFilter(table, exec_GetSeparableFilter);
+ SET_Histogram(table, save_Histogram);
+ SET_Minmax(table, save_Minmax);
+ SET_ResetHistogram(table, save_ResetHistogram);
+ SET_ResetMinmax(table, save_ResetMinmax);
+ SET_SeparableFilter2D(table, exec_SeparableFilter2D);
+
+ /* 2. GL_EXT_blend_color */
+#if 0
+ SET_BlendColorEXT(table, save_BlendColorEXT);
+#endif
+
+ /* 3. GL_EXT_polygon_offset */
+ SET_PolygonOffsetEXT(table, save_PolygonOffsetEXT);
+
+ /* 6. GL_EXT_texture3d */
+#if 0
+ SET_CopyTexSubImage3DEXT(table, save_CopyTexSubImage3D);
+ SET_TexImage3DEXT(table, save_TexImage3DEXT);
+ SET_TexSubImage3DEXT(table, save_TexSubImage3D);
+#endif
+
+ /* 14. GL_SGI_color_table */
+#if 0
+ SET_ColorTableSGI(table, save_ColorTable);
+ SET_ColorSubTableSGI(table, save_ColorSubTable);
+ SET_GetColorTableSGI(table, exec_GetColorTable);
+ SET_GetColorTableParameterfvSGI(table, exec_GetColorTableParameterfv);
+ SET_GetColorTableParameterivSGI(table, exec_GetColorTableParameteriv);
+#endif
+
+ /* 30. GL_EXT_vertex_array */
+ SET_ColorPointerEXT(table, exec_ColorPointerEXT);
+ SET_EdgeFlagPointerEXT(table, exec_EdgeFlagPointerEXT);
+ SET_IndexPointerEXT(table, exec_IndexPointerEXT);
+ SET_NormalPointerEXT(table, exec_NormalPointerEXT);
+ SET_TexCoordPointerEXT(table, exec_TexCoordPointerEXT);
+ SET_VertexPointerEXT(table, exec_VertexPointerEXT);
+
+ /* 37. GL_EXT_blend_minmax */
+#if 0
+ SET_BlendEquationEXT(table, save_BlendEquationEXT);
+#endif
+
+ /* 54. GL_EXT_point_parameters */
+ SET_PointParameterfEXT(table, save_PointParameterfEXT);
+ SET_PointParameterfvEXT(table, save_PointParameterfvEXT);
+
+ /* 97. GL_EXT_compiled_vertex_array */
+ SET_LockArraysEXT(table, exec_LockArraysEXT);
+ SET_UnlockArraysEXT(table, exec_UnlockArraysEXT);
+
+ /* 145. GL_EXT_secondary_color */
+ SET_SecondaryColorPointerEXT(table, exec_SecondaryColorPointerEXT);
+
+ /* 148. GL_EXT_multi_draw_arrays */
+ SET_MultiDrawArraysEXT(table, exec_MultiDrawArraysEXT);
+
+ /* 149. GL_EXT_fog_coord */
+ SET_FogCoordPointerEXT(table, exec_FogCoordPointerEXT);
+
+ /* 173. GL_EXT_blend_func_separate */
+ SET_BlendFuncSeparateEXT(table, save_BlendFuncSeparateEXT);
+
+ /* 196. GL_MESA_resize_buffers */
+ SET_ResizeBuffersMESA(table, _mesa_ResizeBuffersMESA);
+
+ /* 197. GL_MESA_window_pos */
+ SET_WindowPos2dMESA(table, save_WindowPos2dMESA);
+ SET_WindowPos2dvMESA(table, save_WindowPos2dvMESA);
+ SET_WindowPos2fMESA(table, save_WindowPos2fMESA);
+ SET_WindowPos2fvMESA(table, save_WindowPos2fvMESA);
+ SET_WindowPos2iMESA(table, save_WindowPos2iMESA);
+ SET_WindowPos2ivMESA(table, save_WindowPos2ivMESA);
+ SET_WindowPos2sMESA(table, save_WindowPos2sMESA);
+ SET_WindowPos2svMESA(table, save_WindowPos2svMESA);
+ SET_WindowPos3dMESA(table, save_WindowPos3dMESA);
+ SET_WindowPos3dvMESA(table, save_WindowPos3dvMESA);
+ SET_WindowPos3fMESA(table, save_WindowPos3fMESA);
+ SET_WindowPos3fvMESA(table, save_WindowPos3fvMESA);
+ SET_WindowPos3iMESA(table, save_WindowPos3iMESA);
+ SET_WindowPos3ivMESA(table, save_WindowPos3ivMESA);
+ SET_WindowPos3sMESA(table, save_WindowPos3sMESA);
+ SET_WindowPos3svMESA(table, save_WindowPos3svMESA);
+ SET_WindowPos4dMESA(table, save_WindowPos4dMESA);
+ SET_WindowPos4dvMESA(table, save_WindowPos4dvMESA);
+ SET_WindowPos4fMESA(table, save_WindowPos4fMESA);
+ SET_WindowPos4fvMESA(table, save_WindowPos4fvMESA);
+ SET_WindowPos4iMESA(table, save_WindowPos4iMESA);
+ SET_WindowPos4ivMESA(table, save_WindowPos4ivMESA);
+ SET_WindowPos4sMESA(table, save_WindowPos4sMESA);
+ SET_WindowPos4svMESA(table, save_WindowPos4svMESA);
+
+ /* 200. GL_IBM_multimode_draw_arrays */
+ SET_MultiModeDrawArraysIBM(table, exec_MultiModeDrawArraysIBM);
+ SET_MultiModeDrawElementsIBM(table, exec_MultiModeDrawElementsIBM);
+
+#if FEATURE_NV_vertex_program
+ /* 233. GL_NV_vertex_program */
+ /* The following commands DO NOT go into display lists:
+ * AreProgramsResidentNV, IsProgramNV, GenProgramsNV, DeleteProgramsNV,
+ * VertexAttribPointerNV, GetProgram*, GetVertexAttrib*
+ */
+ SET_BindProgramNV(table, save_BindProgramNV);
+ SET_DeleteProgramsNV(table, _mesa_DeletePrograms);
+ SET_ExecuteProgramNV(table, save_ExecuteProgramNV);
+ SET_GenProgramsNV(table, _mesa_GenPrograms);
+ SET_AreProgramsResidentNV(table, _mesa_AreProgramsResidentNV);
+ SET_RequestResidentProgramsNV(table, save_RequestResidentProgramsNV);
+ SET_GetProgramParameterfvNV(table, _mesa_GetProgramParameterfvNV);
+ SET_GetProgramParameterdvNV(table, _mesa_GetProgramParameterdvNV);
+ SET_GetProgramivNV(table, _mesa_GetProgramivNV);
+ SET_GetProgramStringNV(table, _mesa_GetProgramStringNV);
+ SET_GetTrackMatrixivNV(table, _mesa_GetTrackMatrixivNV);
+ SET_GetVertexAttribdvNV(table, _mesa_GetVertexAttribdvNV);
+ SET_GetVertexAttribfvNV(table, _mesa_GetVertexAttribfvNV);
+ SET_GetVertexAttribivNV(table, _mesa_GetVertexAttribivNV);
+ SET_GetVertexAttribPointervNV(table, _mesa_GetVertexAttribPointervNV);
+ SET_IsProgramNV(table, _mesa_IsProgramARB);
+ SET_LoadProgramNV(table, save_LoadProgramNV);
+ SET_ProgramEnvParameter4dARB(table, save_ProgramEnvParameter4dARB);
+ SET_ProgramEnvParameter4dvARB(table, save_ProgramEnvParameter4dvARB);
+ SET_ProgramEnvParameter4fARB(table, save_ProgramEnvParameter4fARB);
+ SET_ProgramEnvParameter4fvARB(table, save_ProgramEnvParameter4fvARB);
+ SET_ProgramParameters4dvNV(table, save_ProgramParameters4dvNV);
+ SET_ProgramParameters4fvNV(table, save_ProgramParameters4fvNV);
+ SET_TrackMatrixNV(table, save_TrackMatrixNV);
+ SET_VertexAttribPointerNV(table, _mesa_VertexAttribPointerNV);
+#endif
+
+ /* 244. GL_ATI_envmap_bumpmap */
+ SET_TexBumpParameterivATI(table, save_TexBumpParameterivATI);
+ SET_TexBumpParameterfvATI(table, save_TexBumpParameterfvATI);
+
+ /* 245. GL_ATI_fragment_shader */
+#if FEATURE_ATI_fragment_shader
+ SET_BindFragmentShaderATI(table, save_BindFragmentShaderATI);
+ SET_SetFragmentShaderConstantATI(table, save_SetFragmentShaderConstantATI);
+#endif
+
+ /* 282. GL_NV_fragment_program */
+#if FEATURE_NV_fragment_program
+ SET_ProgramNamedParameter4fNV(table, save_ProgramNamedParameter4fNV);
+ SET_ProgramNamedParameter4dNV(table, save_ProgramNamedParameter4dNV);
+ SET_ProgramNamedParameter4fvNV(table, save_ProgramNamedParameter4fvNV);
+ SET_ProgramNamedParameter4dvNV(table, save_ProgramNamedParameter4dvNV);
+ SET_GetProgramNamedParameterfvNV(table,
+ _mesa_GetProgramNamedParameterfvNV);
+ SET_GetProgramNamedParameterdvNV(table,
+ _mesa_GetProgramNamedParameterdvNV);
+ SET_ProgramLocalParameter4dARB(table, save_ProgramLocalParameter4dARB);
+ SET_ProgramLocalParameter4dvARB(table, save_ProgramLocalParameter4dvARB);
+ SET_ProgramLocalParameter4fARB(table, save_ProgramLocalParameter4fARB);
+ SET_ProgramLocalParameter4fvARB(table, save_ProgramLocalParameter4fvARB);
+ SET_GetProgramLocalParameterdvARB(table,
+ _mesa_GetProgramLocalParameterdvARB);
+ SET_GetProgramLocalParameterfvARB(table,
+ _mesa_GetProgramLocalParameterfvARB);
+#endif
+
+ /* 262. GL_NV_point_sprite */
+ SET_PointParameteriNV(table, save_PointParameteriNV);
+ SET_PointParameterivNV(table, save_PointParameterivNV);
+
+ /* 268. GL_EXT_stencil_two_side */
+ SET_ActiveStencilFaceEXT(table, save_ActiveStencilFaceEXT);
+
+ /* 273. GL_APPLE_vertex_array_object */
+ SET_BindVertexArrayAPPLE(table, _mesa_BindVertexArrayAPPLE);
+ SET_DeleteVertexArraysAPPLE(table, _mesa_DeleteVertexArraysAPPLE);
+ SET_GenVertexArraysAPPLE(table, _mesa_GenVertexArraysAPPLE);
+ SET_IsVertexArrayAPPLE(table, _mesa_IsVertexArrayAPPLE);
+
+ /* ???. GL_EXT_depth_bounds_test */
+ SET_DepthBoundsEXT(table, save_DepthBoundsEXT);
+
+ /* ARB 1. GL_ARB_multitexture */
+ SET_ActiveTextureARB(table, save_ActiveTextureARB);
+ SET_ClientActiveTextureARB(table, exec_ClientActiveTextureARB);
+
+ /* ARB 3. GL_ARB_transpose_matrix */
+ SET_LoadTransposeMatrixdARB(table, save_LoadTransposeMatrixdARB);
+ SET_LoadTransposeMatrixfARB(table, save_LoadTransposeMatrixfARB);
+ SET_MultTransposeMatrixdARB(table, save_MultTransposeMatrixdARB);
+ SET_MultTransposeMatrixfARB(table, save_MultTransposeMatrixfARB);
+
+ /* ARB 5. GL_ARB_multisample */
+ SET_SampleCoverageARB(table, save_SampleCoverageARB);
+
+ /* ARB 12. GL_ARB_texture_compression */
+ SET_CompressedTexImage3DARB(table, save_CompressedTexImage3DARB);
+ SET_CompressedTexImage2DARB(table, save_CompressedTexImage2DARB);
+ SET_CompressedTexImage1DARB(table, save_CompressedTexImage1DARB);
+ SET_CompressedTexSubImage3DARB(table, save_CompressedTexSubImage3DARB);
+ SET_CompressedTexSubImage2DARB(table, save_CompressedTexSubImage2DARB);
+ SET_CompressedTexSubImage1DARB(table, save_CompressedTexSubImage1DARB);
+ SET_GetCompressedTexImageARB(table, exec_GetCompressedTexImageARB);
+
+ /* ARB 14. GL_ARB_point_parameters */
+ /* aliased with EXT_point_parameters functions */
+
+ /* ARB 25. GL_ARB_window_pos */
+ /* aliased with MESA_window_pos functions */
+
+ /* ARB 26. GL_ARB_vertex_program */
+ /* ARB 27. GL_ARB_fragment_program */
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+ /* glVertexAttrib* functions alias the NV ones, handled elsewhere */
+ SET_VertexAttribPointerARB(table, _mesa_VertexAttribPointerARB);
+ SET_EnableVertexAttribArrayARB(table, _mesa_EnableVertexAttribArrayARB);
+ SET_DisableVertexAttribArrayARB(table, _mesa_DisableVertexAttribArrayARB);
+ SET_ProgramStringARB(table, save_ProgramStringARB);
+ SET_BindProgramNV(table, save_BindProgramNV);
+ SET_DeleteProgramsNV(table, _mesa_DeletePrograms);
+ SET_GenProgramsNV(table, _mesa_GenPrograms);
+ SET_IsProgramNV(table, _mesa_IsProgramARB);
+ SET_GetVertexAttribdvNV(table, _mesa_GetVertexAttribdvNV);
+ SET_GetVertexAttribfvNV(table, _mesa_GetVertexAttribfvNV);
+ SET_GetVertexAttribivNV(table, _mesa_GetVertexAttribivNV);
+ SET_GetVertexAttribPointervNV(table, _mesa_GetVertexAttribPointervNV);
+ SET_ProgramEnvParameter4dARB(table, save_ProgramEnvParameter4dARB);
+ SET_ProgramEnvParameter4dvARB(table, save_ProgramEnvParameter4dvARB);
+ SET_ProgramEnvParameter4fARB(table, save_ProgramEnvParameter4fARB);
+ SET_ProgramEnvParameter4fvARB(table, save_ProgramEnvParameter4fvARB);
+ SET_ProgramLocalParameter4dARB(table, save_ProgramLocalParameter4dARB);
+ SET_ProgramLocalParameter4dvARB(table, save_ProgramLocalParameter4dvARB);
+ SET_ProgramLocalParameter4fARB(table, save_ProgramLocalParameter4fARB);
+ SET_ProgramLocalParameter4fvARB(table, save_ProgramLocalParameter4fvARB);
+ SET_GetProgramEnvParameterdvARB(table, _mesa_GetProgramEnvParameterdvARB);
+ SET_GetProgramEnvParameterfvARB(table, _mesa_GetProgramEnvParameterfvARB);
+ SET_GetProgramLocalParameterdvARB(table,
+ _mesa_GetProgramLocalParameterdvARB);
+ SET_GetProgramLocalParameterfvARB(table,
+ _mesa_GetProgramLocalParameterfvARB);
+ SET_GetProgramivARB(table, _mesa_GetProgramivARB);
+ SET_GetProgramStringARB(table, _mesa_GetProgramStringARB);
+#endif
+
+ /* ARB 28. GL_ARB_vertex_buffer_object */
+#if FEATURE_ARB_vertex_buffer_object
+ /* None of the extension's functions get compiled */
+ SET_BindBufferARB(table, _mesa_BindBufferARB);
+ SET_BufferDataARB(table, _mesa_BufferDataARB);
+ SET_BufferSubDataARB(table, _mesa_BufferSubDataARB);
+ SET_DeleteBuffersARB(table, _mesa_DeleteBuffersARB);
+ SET_GenBuffersARB(table, _mesa_GenBuffersARB);
+ SET_GetBufferParameterivARB(table, _mesa_GetBufferParameterivARB);
+ SET_GetBufferPointervARB(table, _mesa_GetBufferPointervARB);
+ SET_GetBufferSubDataARB(table, _mesa_GetBufferSubDataARB);
+ SET_IsBufferARB(table, _mesa_IsBufferARB);
+ SET_MapBufferARB(table, _mesa_MapBufferARB);
+ SET_UnmapBufferARB(table, _mesa_UnmapBufferARB);
+#endif
+
+#if FEATURE_queryobj
+ SET_BeginQueryARB(table, save_BeginQueryARB);
+ SET_EndQueryARB(table, save_EndQueryARB);
+ SET_GenQueriesARB(table, _mesa_GenQueriesARB);
+ SET_DeleteQueriesARB(table, _mesa_DeleteQueriesARB);
+ SET_IsQueryARB(table, _mesa_IsQueryARB);
+ SET_GetQueryivARB(table, _mesa_GetQueryivARB);
+ SET_GetQueryObjectivARB(table, _mesa_GetQueryObjectivARB);
+ SET_GetQueryObjectuivARB(table, _mesa_GetQueryObjectuivARB);
+#endif
+ SET_DrawBuffersARB(table, save_DrawBuffersARB);
+
+#if FEATURE_EXT_framebuffer_blit
+ SET_BlitFramebufferEXT(table, save_BlitFramebufferEXT);
+#endif
+
+ /* GL_ARB_shader_objects */
+ SET_UseProgramObjectARB(table, save_UseProgramObjectARB);
+ SET_Uniform1fARB(table, save_Uniform1fARB);
+ SET_Uniform2fARB(table, save_Uniform2fARB);
+ SET_Uniform3fARB(table, save_Uniform3fARB);
+ SET_Uniform4fARB(table, save_Uniform4fARB);
+ SET_Uniform1fvARB(table, save_Uniform1fvARB);
+ SET_Uniform2fvARB(table, save_Uniform2fvARB);
+ SET_Uniform3fvARB(table, save_Uniform3fvARB);
+ SET_Uniform4fvARB(table, save_Uniform4fvARB);
+ SET_Uniform1iARB(table, save_Uniform1iARB);
+ SET_Uniform2iARB(table, save_Uniform2iARB);
+ SET_Uniform3iARB(table, save_Uniform3iARB);
+ SET_Uniform4iARB(table, save_Uniform4iARB);
+ SET_Uniform1ivARB(table, save_Uniform1ivARB);
+ SET_Uniform2ivARB(table, save_Uniform2ivARB);
+ SET_Uniform3ivARB(table, save_Uniform3ivARB);
+ SET_Uniform4ivARB(table, save_Uniform4ivARB);
+ SET_UniformMatrix2fvARB(table, save_UniformMatrix2fvARB);
+ SET_UniformMatrix3fvARB(table, save_UniformMatrix3fvARB);
+ SET_UniformMatrix4fvARB(table, save_UniformMatrix4fvARB);
+ SET_UniformMatrix2x3fv(table, save_UniformMatrix2x3fv);
+ SET_UniformMatrix3x2fv(table, save_UniformMatrix3x2fv);
+ SET_UniformMatrix2x4fv(table, save_UniformMatrix2x4fv);
+ SET_UniformMatrix4x2fv(table, save_UniformMatrix4x2fv);
+ SET_UniformMatrix3x4fv(table, save_UniformMatrix3x4fv);
+ SET_UniformMatrix4x3fv(table, save_UniformMatrix4x3fv);
+
+ /* ARB 30/31/32. GL_ARB_shader_objects, GL_ARB_vertex/fragment_shader */
+ SET_BindAttribLocationARB(table, exec_BindAttribLocationARB);
+ SET_GetAttribLocationARB(table, exec_GetAttribLocationARB);
+ SET_GetUniformLocationARB(table, exec_GetUniformLocationARB);
+ /* XXX additional functions need to be implemented here! */
+
+ /* 299. GL_EXT_blend_equation_separate */
+ SET_BlendEquationSeparateEXT(table, save_BlendEquationSeparateEXT);
+
+ /* GL_EXT_gpu_program_parameters */
+#if FEATURE_ARB_vertex_program || FEATURE_ARB_fragment_program
+ SET_ProgramEnvParameters4fvEXT(table, save_ProgramEnvParameters4fvEXT);
+ SET_ProgramLocalParameters4fvEXT(table, save_ProgramLocalParameters4fvEXT);
+#endif
+
+ /* ARB 50. GL_ARB_map_buffer_range */
+#if FEATURE_ARB_map_buffer_range
+ SET_MapBufferRange(table, _mesa_MapBufferRange); /* no dlist save */
+ SET_FlushMappedBufferRange(table, _mesa_FlushMappedBufferRange); /* no dl */
+#endif
+
+ /* ARB 59. GL_ARB_copy_buffer */
+ SET_CopyBufferSubData(table, _mesa_CopyBufferSubData); /* no dlist save */
+
+ /* 352. GL_EXT_transform_feedback */
+#if FEATURE_EXT_transform_feedback
+ SET_BeginTransformFeedbackEXT(table, save_BeginTransformFeedback);
+ SET_EndTransformFeedbackEXT(table, save_EndTransformFeedback);
+#endif
+
+ /* 364. GL_EXT_provoking_vertex */
+ SET_ProvokingVertexEXT(table, save_ProvokingVertexEXT);
+
+ /* 371. GL_APPLE_object_purgeable */
+#if FEATURE_APPLE_object_purgeable
+ SET_ObjectPurgeableAPPLE(table, _mesa_ObjectPurgeableAPPLE);
+ SET_ObjectUnpurgeableAPPLE(table, _mesa_ObjectUnpurgeableAPPLE);
+#endif
+
+ /* GL_EXT_texture_integer */
+ SET_ClearColorIiEXT(table, save_ClearColorIi);
+ SET_ClearColorIuiEXT(table, save_ClearColorIui);
+ SET_TexParameterIivEXT(table, save_TexParameterIiv);
+ SET_TexParameterIuivEXT(table, save_TexParameterIuiv);
+ SET_GetTexParameterIivEXT(table, exec_GetTexParameterIiv);
+ SET_GetTexParameterIuivEXT(table, exec_GetTexParameterIuiv);
+
+ /* 377. GL_EXT_separate_shader_objects */
+ SET_UseShaderProgramEXT(table, save_UseShaderProgramEXT);
+ SET_ActiveProgramEXT(table, save_ActiveProgramEXT);
+
+ /* GL 3.0 */
+#if 0
+ SET_ClearBufferiv(table, save_ClearBufferiv);
+ SET_ClearBufferuiv(table, save_ClearBufferuiv);
+ SET_ClearBufferfv(table, save_ClearBufferfv);
+ SET_ClearBufferfi(table, save_ClearBufferfi);
+ SET_Uniform1ui(table, save_Uniform1ui);
+ SET_Uniform2ui(table, save_Uniform2ui);
+ SET_Uniform3ui(table, save_Uniform3ui);
+ SET_Uniform4ui(table, save_Uniform4ui);
+ SET_Uniform1uiv(table, save_Uniform1uiv);
+ SET_Uniform2uiv(table, save_Uniform2uiv);
+ SET_Uniform3uiv(table, save_Uniform3uiv);
+ SET_Uniform4uiv(table, save_Uniform4uiv);
+#else
+ (void) save_ClearBufferiv;
+ (void) save_ClearBufferuiv;
+ (void) save_ClearBufferfv;
+ (void) save_ClearBufferfi;
+ (void) save_Uniform1ui;
+ (void) save_Uniform2ui;
+ (void) save_Uniform3ui;
+ (void) save_Uniform4ui;
+ (void) save_Uniform1uiv;
+ (void) save_Uniform2uiv;
+ (void) save_Uniform3uiv;
+ (void) save_Uniform4uiv;
+#endif
+
+ /* GL_ARB_instanced_arrays */
+ SET_VertexAttribDivisorARB(table, save_VertexAttribDivisor);
+
+ /* GL_ARB_draw_buffer_blend */
+ SET_BlendFunciARB(table, save_BlendFunci);
+ SET_BlendFuncSeparateiARB(table, save_BlendFuncSeparatei);
+ SET_BlendEquationiARB(table, save_BlendEquationi);
+ SET_BlendEquationSeparateiARB(table, save_BlendEquationSeparatei);
+
+ return table;
+}
+
+
+
+static const char *
+enum_string(GLenum k)
+{
+ return _mesa_lookup_enum_by_nr(k);
+}
+
+
+/**
+ * Print the commands in a display list. For debugging only.
+ * TODO: many commands aren't handled yet.
+ */
+static void GLAPIENTRY
+print_list(struct gl_context *ctx, GLuint list)
+{
+ struct gl_display_list *dlist;
+ Node *n;
+ GLboolean done;
+
+ if (!islist(ctx, list)) {
+ printf("%u is not a display list ID\n", list);
+ return;
+ }
+
+ dlist = lookup_list(ctx, list);
+ if (!dlist)
+ return;
+
+ n = dlist->Head;
+
+ printf("START-LIST %u, address %p\n", list, (void *) n);
+
+ done = n ? GL_FALSE : GL_TRUE;
+ while (!done) {
+ const OpCode opcode = n[0].opcode;
+
+ if (is_ext_opcode(opcode)) {
+ n += ext_opcode_print(ctx, n);
+ }
+ else {
+ switch (opcode) {
+ case OPCODE_ACCUM:
+ printf("Accum %s %g\n", enum_string(n[1].e), n[2].f);
+ break;
+ case OPCODE_BITMAP:
+ printf("Bitmap %d %d %g %g %g %g %p\n", n[1].i, n[2].i,
+ n[3].f, n[4].f, n[5].f, n[6].f, (void *) n[7].data);
+ break;
+ case OPCODE_CALL_LIST:
+ printf("CallList %d\n", (int) n[1].ui);
+ break;
+ case OPCODE_CALL_LIST_OFFSET:
+ printf("CallList %d + offset %u = %u\n", (int) n[1].ui,
+ ctx->List.ListBase, ctx->List.ListBase + n[1].ui);
+ break;
+ case OPCODE_COLOR_TABLE_PARAMETER_FV:
+ printf("ColorTableParameterfv %s %s %f %f %f %f\n",
+ enum_string(n[1].e), enum_string(n[2].e),
+ n[3].f, n[4].f, n[5].f, n[6].f);
+ break;
+ case OPCODE_COLOR_TABLE_PARAMETER_IV:
+ printf("ColorTableParameteriv %s %s %d %d %d %d\n",
+ enum_string(n[1].e), enum_string(n[2].e),
+ n[3].i, n[4].i, n[5].i, n[6].i);
+ break;
+ case OPCODE_DISABLE:
+ printf("Disable %s\n", enum_string(n[1].e));
+ break;
+ case OPCODE_ENABLE:
+ printf("Enable %s\n", enum_string(n[1].e));
+ break;
+ case OPCODE_FRUSTUM:
+ printf("Frustum %g %g %g %g %g %g\n",
+ n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f);
+ break;
+ case OPCODE_LINE_STIPPLE:
+ printf("LineStipple %d %x\n", n[1].i, (int) n[2].us);
+ break;
+ case OPCODE_LOAD_IDENTITY:
+ printf("LoadIdentity\n");
+ break;
+ case OPCODE_LOAD_MATRIX:
+ printf("LoadMatrix\n");
+ printf(" %8f %8f %8f %8f\n",
+ n[1].f, n[5].f, n[9].f, n[13].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[2].f, n[6].f, n[10].f, n[14].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[3].f, n[7].f, n[11].f, n[15].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[4].f, n[8].f, n[12].f, n[16].f);
+ break;
+ case OPCODE_MULT_MATRIX:
+ printf("MultMatrix (or Rotate)\n");
+ printf(" %8f %8f %8f %8f\n",
+ n[1].f, n[5].f, n[9].f, n[13].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[2].f, n[6].f, n[10].f, n[14].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[3].f, n[7].f, n[11].f, n[15].f);
+ printf(" %8f %8f %8f %8f\n",
+ n[4].f, n[8].f, n[12].f, n[16].f);
+ break;
+ case OPCODE_ORTHO:
+ printf("Ortho %g %g %g %g %g %g\n",
+ n[1].f, n[2].f, n[3].f, n[4].f, n[5].f, n[6].f);
+ break;
+ case OPCODE_POP_ATTRIB:
+ printf("PopAttrib\n");
+ break;
+ case OPCODE_POP_MATRIX:
+ printf("PopMatrix\n");
+ break;
+ case OPCODE_POP_NAME:
+ printf("PopName\n");
+ break;
+ case OPCODE_PUSH_ATTRIB:
+ printf("PushAttrib %x\n", n[1].bf);
+ break;
+ case OPCODE_PUSH_MATRIX:
+ printf("PushMatrix\n");
+ break;
+ case OPCODE_PUSH_NAME:
+ printf("PushName %d\n", (int) n[1].ui);
+ break;
+ case OPCODE_RASTER_POS:
+ printf("RasterPos %g %g %g %g\n",
+ n[1].f, n[2].f, n[3].f, n[4].f);
+ break;
+ case OPCODE_ROTATE:
+ printf("Rotate %g %g %g %g\n",
+ n[1].f, n[2].f, n[3].f, n[4].f);
+ break;
+ case OPCODE_SCALE:
+ printf("Scale %g %g %g\n", n[1].f, n[2].f, n[3].f);
+ break;
+ case OPCODE_TRANSLATE:
+ printf("Translate %g %g %g\n", n[1].f, n[2].f, n[3].f);
+ break;
+ case OPCODE_BIND_TEXTURE:
+ printf("BindTexture %s %d\n",
+ _mesa_lookup_enum_by_nr(n[1].ui), n[2].ui);
+ break;
+ case OPCODE_SHADE_MODEL:
+ printf("ShadeModel %s\n", _mesa_lookup_enum_by_nr(n[1].ui));
+ break;
+ case OPCODE_MAP1:
+ printf("Map1 %s %.3f %.3f %d %d\n",
+ _mesa_lookup_enum_by_nr(n[1].ui),
+ n[2].f, n[3].f, n[4].i, n[5].i);
+ break;
+ case OPCODE_MAP2:
+ printf("Map2 %s %.3f %.3f %.3f %.3f %d %d %d %d\n",
+ _mesa_lookup_enum_by_nr(n[1].ui),
+ n[2].f, n[3].f, n[4].f, n[5].f,
+ n[6].i, n[7].i, n[8].i, n[9].i);
+ break;
+ case OPCODE_MAPGRID1:
+ printf("MapGrid1 %d %.3f %.3f\n", n[1].i, n[2].f, n[3].f);
+ break;
+ case OPCODE_MAPGRID2:
+ printf("MapGrid2 %d %.3f %.3f, %d %.3f %.3f\n",
+ n[1].i, n[2].f, n[3].f, n[4].i, n[5].f, n[6].f);
+ break;
+ case OPCODE_EVALMESH1:
+ printf("EvalMesh1 %d %d\n", n[1].i, n[2].i);
+ break;
+ case OPCODE_EVALMESH2:
+ printf("EvalMesh2 %d %d %d %d\n",
+ n[1].i, n[2].i, n[3].i, n[4].i);
+ break;
+
+ case OPCODE_ATTR_1F_NV:
+ printf("ATTR_1F_NV attr %d: %f\n", n[1].i, n[2].f);
+ break;
+ case OPCODE_ATTR_2F_NV:
+ printf("ATTR_2F_NV attr %d: %f %f\n",
+ n[1].i, n[2].f, n[3].f);
+ break;
+ case OPCODE_ATTR_3F_NV:
+ printf("ATTR_3F_NV attr %d: %f %f %f\n",
+ n[1].i, n[2].f, n[3].f, n[4].f);
+ break;
+ case OPCODE_ATTR_4F_NV:
+ printf("ATTR_4F_NV attr %d: %f %f %f %f\n",
+ n[1].i, n[2].f, n[3].f, n[4].f, n[5].f);
+ break;
+ case OPCODE_ATTR_1F_ARB:
+ printf("ATTR_1F_ARB attr %d: %f\n", n[1].i, n[2].f);
+ break;
+ case OPCODE_ATTR_2F_ARB:
+ printf("ATTR_2F_ARB attr %d: %f %f\n",
+ n[1].i, n[2].f, n[3].f);
+ break;
+ case OPCODE_ATTR_3F_ARB:
+ printf("ATTR_3F_ARB attr %d: %f %f %f\n",
+ n[1].i, n[2].f, n[3].f, n[4].f);
+ break;
+ case OPCODE_ATTR_4F_ARB:
+ printf("ATTR_4F_ARB attr %d: %f %f %f %f\n",
+ n[1].i, n[2].f, n[3].f, n[4].f, n[5].f);
+ break;
+
+ case OPCODE_MATERIAL:
+ printf("MATERIAL %x %x: %f %f %f %f\n",
+ n[1].i, n[2].i, n[3].f, n[4].f, n[5].f, n[6].f);
+ break;
+ case OPCODE_BEGIN:
+ printf("BEGIN %x\n", n[1].i);
+ break;
+ case OPCODE_END:
+ printf("END\n");
+ break;
+ case OPCODE_RECTF:
+ printf("RECTF %f %f %f %f\n", n[1].f, n[2].f, n[3].f,
+ n[4].f);
+ break;
+ case OPCODE_EVAL_C1:
+ printf("EVAL_C1 %f\n", n[1].f);
+ break;
+ case OPCODE_EVAL_C2:
+ printf("EVAL_C2 %f %f\n", n[1].f, n[2].f);
+ break;
+ case OPCODE_EVAL_P1:
+ printf("EVAL_P1 %d\n", n[1].i);
+ break;
+ case OPCODE_EVAL_P2:
+ printf("EVAL_P2 %d %d\n", n[1].i, n[2].i);
+ break;
+
+ case OPCODE_PROVOKING_VERTEX:
+ printf("ProvokingVertex %s\n",
+ _mesa_lookup_enum_by_nr(n[1].ui));
+ break;
+
+ /*
+ * meta opcodes/commands
+ */
+ case OPCODE_ERROR:
+ printf("Error: %s %s\n",
+ enum_string(n[1].e), (const char *) n[2].data);
+ break;
+ case OPCODE_CONTINUE:
+ printf("DISPLAY-LIST-CONTINUE\n");
+ n = (Node *) n[1].next;
+ break;
+ case OPCODE_END_OF_LIST:
+ printf("END-LIST %u\n", list);
+ done = GL_TRUE;
+ break;
+ default:
+ if (opcode < 0 || opcode > OPCODE_END_OF_LIST) {
+ printf
+ ("ERROR IN DISPLAY LIST: opcode = %d, address = %p\n",
+ opcode, (void *) n);
+ return;
+ }
+ else {
+ printf("command %d, %u operands\n", opcode,
+ InstSize[opcode]);
+ }
+ }
+ /* increment n to point to next compiled command */
+ if (opcode != OPCODE_CONTINUE) {
+ n += InstSize[opcode];
+ }
+ }
+ }
+}
+
+
+
+/**
+ * Clients may call this function to help debug display list problems.
+ * This function is _ONLY_FOR_DEBUGGING_PURPOSES_. It may be removed,
+ * changed, or break in the future without notice.
+ */
+void
+mesa_print_display_list(GLuint list)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ print_list(ctx, list);
+}
+
+
+/**********************************************************************/
+/***** Initialization *****/
+/**********************************************************************/
+
+void
+_mesa_save_vtxfmt_init(GLvertexformat * vfmt)
+{
+ _MESA_INIT_ARRAYELT_VTXFMT(vfmt, _ae_);
+
+ vfmt->Begin = save_Begin;
+
+ _MESA_INIT_DLIST_VTXFMT(vfmt, save_);
+
+ vfmt->Color3f = save_Color3f;
+ vfmt->Color3fv = save_Color3fv;
+ vfmt->Color4f = save_Color4f;
+ vfmt->Color4fv = save_Color4fv;
+ vfmt->EdgeFlag = save_EdgeFlag;
+ vfmt->End = save_End;
+
+ _MESA_INIT_EVAL_VTXFMT(vfmt, save_);
+
+ vfmt->FogCoordfEXT = save_FogCoordfEXT;
+ vfmt->FogCoordfvEXT = save_FogCoordfvEXT;
+ vfmt->Indexf = save_Indexf;
+ vfmt->Indexfv = save_Indexfv;
+ vfmt->Materialfv = save_Materialfv;
+ vfmt->MultiTexCoord1fARB = save_MultiTexCoord1f;
+ vfmt->MultiTexCoord1fvARB = save_MultiTexCoord1fv;
+ vfmt->MultiTexCoord2fARB = save_MultiTexCoord2f;
+ vfmt->MultiTexCoord2fvARB = save_MultiTexCoord2fv;
+ vfmt->MultiTexCoord3fARB = save_MultiTexCoord3f;
+ vfmt->MultiTexCoord3fvARB = save_MultiTexCoord3fv;
+ vfmt->MultiTexCoord4fARB = save_MultiTexCoord4f;
+ vfmt->MultiTexCoord4fvARB = save_MultiTexCoord4fv;
+ vfmt->Normal3f = save_Normal3f;
+ vfmt->Normal3fv = save_Normal3fv;
+ vfmt->SecondaryColor3fEXT = save_SecondaryColor3fEXT;
+ vfmt->SecondaryColor3fvEXT = save_SecondaryColor3fvEXT;
+ vfmt->TexCoord1f = save_TexCoord1f;
+ vfmt->TexCoord1fv = save_TexCoord1fv;
+ vfmt->TexCoord2f = save_TexCoord2f;
+ vfmt->TexCoord2fv = save_TexCoord2fv;
+ vfmt->TexCoord3f = save_TexCoord3f;
+ vfmt->TexCoord3fv = save_TexCoord3fv;
+ vfmt->TexCoord4f = save_TexCoord4f;
+ vfmt->TexCoord4fv = save_TexCoord4fv;
+ vfmt->Vertex2f = save_Vertex2f;
+ vfmt->Vertex2fv = save_Vertex2fv;
+ vfmt->Vertex3f = save_Vertex3f;
+ vfmt->Vertex3fv = save_Vertex3fv;
+ vfmt->Vertex4f = save_Vertex4f;
+ vfmt->Vertex4fv = save_Vertex4fv;
+ vfmt->VertexAttrib1fNV = save_VertexAttrib1fNV;
+ vfmt->VertexAttrib1fvNV = save_VertexAttrib1fvNV;
+ vfmt->VertexAttrib2fNV = save_VertexAttrib2fNV;
+ vfmt->VertexAttrib2fvNV = save_VertexAttrib2fvNV;
+ vfmt->VertexAttrib3fNV = save_VertexAttrib3fNV;
+ vfmt->VertexAttrib3fvNV = save_VertexAttrib3fvNV;
+ vfmt->VertexAttrib4fNV = save_VertexAttrib4fNV;
+ vfmt->VertexAttrib4fvNV = save_VertexAttrib4fvNV;
+ vfmt->VertexAttrib1fARB = save_VertexAttrib1fARB;
+ vfmt->VertexAttrib1fvARB = save_VertexAttrib1fvARB;
+ vfmt->VertexAttrib2fARB = save_VertexAttrib2fARB;
+ vfmt->VertexAttrib2fvARB = save_VertexAttrib2fvARB;
+ vfmt->VertexAttrib3fARB = save_VertexAttrib3fARB;
+ vfmt->VertexAttrib3fvARB = save_VertexAttrib3fvARB;
+ vfmt->VertexAttrib4fARB = save_VertexAttrib4fARB;
+ vfmt->VertexAttrib4fvARB = save_VertexAttrib4fvARB;
+
+ vfmt->Rectf = save_Rectf;
+
+ /* The driver is required to implement these as
+ * 1) They can probably do a better job.
+ * 2) A lot of new mechanisms would have to be added to this module
+ * to support it. That code would probably never get used,
+ * because of (1).
+ */
+#if 0
+ vfmt->DrawArrays = 0;
+ vfmt->DrawElements = 0;
+ vfmt->DrawRangeElements = 0;
+ vfmt->MultiDrawElemementsEXT = 0;
+ vfmt->DrawElementsBaseVertex = 0;
+ vfmt->DrawRangeElementsBaseVertex = 0;
+ vfmt->MultiDrawElemementsBaseVertex = 0;
+#endif
+}
+
+
+void
+_mesa_install_dlist_vtxfmt(struct _glapi_table *disp,
+ const GLvertexformat *vfmt)
+{
+ SET_CallList(disp, vfmt->CallList);
+ SET_CallLists(disp, vfmt->CallLists);
+}
+
+
+void _mesa_init_dlist_dispatch(struct _glapi_table *disp)
+{
+ SET_CallList(disp, _mesa_CallList);
+ SET_CallLists(disp, _mesa_CallLists);
+
+ SET_DeleteLists(disp, _mesa_DeleteLists);
+ SET_EndList(disp, _mesa_EndList);
+ SET_GenLists(disp, _mesa_GenLists);
+ SET_IsList(disp, _mesa_IsList);
+ SET_ListBase(disp, _mesa_ListBase);
+ SET_NewList(disp, _mesa_NewList);
+}
+
+
+#endif /* FEATURE_dlist */
+
+
+/**
+ * Initialize display list state for given context.
+ */
+void
+_mesa_init_display_list(struct gl_context *ctx)
+{
+ static GLboolean tableInitialized = GL_FALSE;
+
+ /* zero-out the instruction size table, just once */
+ if (!tableInitialized) {
+ memset(InstSize, 0, sizeof(InstSize));
+ tableInitialized = GL_TRUE;
+ }
+
+ /* extension info */
+ ctx->ListExt = CALLOC_STRUCT(gl_list_extensions);
+
+ /* Display list */
+ ctx->ListState.CallDepth = 0;
+ ctx->ExecuteFlag = GL_TRUE;
+ ctx->CompileFlag = GL_FALSE;
+ ctx->ListState.CurrentBlock = NULL;
+ ctx->ListState.CurrentPos = 0;
+
+ /* Display List group */
+ ctx->List.ListBase = 0;
+
+#if FEATURE_dlist
+ _mesa_save_vtxfmt_init(&ctx->ListState.ListVtxfmt);
+#endif
+}
+
+
+void
+_mesa_free_display_list_data(struct gl_context *ctx)
+{
+ free(ctx->ListExt);
+ ctx->ListExt = NULL;
+}
diff --git a/mesalib/src/mesa/main/dlopen.c b/mesalib/src/mesa/main/dlopen.c
index 57a33292e..62d9023a9 100644
--- a/mesalib/src/mesa/main/dlopen.c
+++ b/mesalib/src/mesa/main/dlopen.c
@@ -51,7 +51,7 @@ _mesa_dlopen(const char *libname, int flags)
#elif defined(_GNU_SOURCE)
flags = RTLD_LAZY | RTLD_GLOBAL; /* Overriding flags at this time */
return dlopen(libname, flags);
-#elif defined(__MINGW32__)
+#elif defined(__MINGW32__) | defined(_MSC_VER)
return LoadLibraryA(libname);
#else
return NULL;
@@ -82,7 +82,7 @@ _mesa_dlsym(void *handle, const char *fname)
u.v = dlsym(handle, fname2);
#elif defined(_GNU_SOURCE)
u.v = dlsym(handle, fname);
-#elif defined(__MINGW32__)
+#elif defined(__MINGW32__) | defined(_MSC_VER)
u.v = (void *) GetProcAddress(handle, fname);
#else
u.v = NULL;
@@ -101,7 +101,7 @@ _mesa_dlclose(void *handle)
(void) handle;
#elif defined(_GNU_SOURCE)
dlclose(handle);
-#elif defined(__MINGW32__)
+#elif defined(__MINGW32__) | defined(_MSC_VER)
FreeLibrary(handle);
#else
(void) handle;
diff --git a/mesalib/src/mesa/main/hint.c b/mesalib/src/mesa/main/hint.c
index ff8d88fff..aea0d7022 100644
--- a/mesalib/src/mesa/main/hint.c
+++ b/mesalib/src/mesa/main/hint.c
@@ -1,147 +1,147 @@
-
-/*
- * Mesa 3-D graphics library
- * Version: 4.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.
- */
-
-
-#include "glheader.h"
-#include "enums.h"
-#include "context.h"
-#include "hint.h"
-#include "imports.h"
-#include "mtypes.h"
-
-
-
-void GLAPIENTRY
-_mesa_Hint( GLenum target, GLenum mode )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glHint %s %s\n",
- _mesa_lookup_enum_by_nr(target),
- _mesa_lookup_enum_by_nr(mode));
-
- if (mode != GL_NICEST && mode != GL_FASTEST && mode != GL_DONT_CARE) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glHint(mode)");
- return;
- }
-
- switch (target) {
- case GL_FOG_HINT:
- if (ctx->Hint.Fog == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.Fog = mode;
- break;
- case GL_LINE_SMOOTH_HINT:
- if (ctx->Hint.LineSmooth == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.LineSmooth = mode;
- break;
- case GL_PERSPECTIVE_CORRECTION_HINT:
- if (ctx->Hint.PerspectiveCorrection == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.PerspectiveCorrection = mode;
- break;
- case GL_POINT_SMOOTH_HINT:
- if (ctx->Hint.PointSmooth == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.PointSmooth = mode;
- break;
- case GL_POLYGON_SMOOTH_HINT:
- if (ctx->Hint.PolygonSmooth == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.PolygonSmooth = mode;
- break;
-
- /* GL_EXT_clip_volume_hint */
- case GL_CLIP_VOLUME_CLIPPING_HINT_EXT:
- if (ctx->Hint.ClipVolumeClipping == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.ClipVolumeClipping = mode;
- break;
-
- /* GL_ARB_texture_compression */
- case GL_TEXTURE_COMPRESSION_HINT_ARB:
- if (ctx->Hint.TextureCompression == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.TextureCompression = mode;
- break;
-
- /* GL_SGIS_generate_mipmap */
- case GL_GENERATE_MIPMAP_HINT_SGIS:
- if (ctx->Hint.GenerateMipmap == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.GenerateMipmap = mode;
- break;
-
- /* GL_ARB_fragment_shader */
- case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB:
- if (!ctx->Extensions.ARB_fragment_shader) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glHint(target)");
- return;
- }
- if (ctx->Hint.FragmentShaderDerivative == mode)
- return;
- FLUSH_VERTICES(ctx, _NEW_HINT);
- ctx->Hint.FragmentShaderDerivative = mode;
- break;
-
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glHint(target)");
- return;
- }
-
- if (ctx->Driver.Hint) {
- (*ctx->Driver.Hint)( ctx, target, mode );
- }
-}
-
-
-/**********************************************************************/
-/***** Initialization *****/
-/**********************************************************************/
-
-void _mesa_init_hint( struct gl_context * ctx )
-{
- /* Hint group */
- ctx->Hint.PerspectiveCorrection = GL_DONT_CARE;
- ctx->Hint.PointSmooth = GL_DONT_CARE;
- ctx->Hint.LineSmooth = GL_DONT_CARE;
- ctx->Hint.PolygonSmooth = GL_DONT_CARE;
- ctx->Hint.Fog = GL_DONT_CARE;
- ctx->Hint.ClipVolumeClipping = GL_DONT_CARE;
- ctx->Hint.TextureCompression = GL_DONT_CARE;
- ctx->Hint.GenerateMipmap = GL_DONT_CARE;
- ctx->Hint.FragmentShaderDerivative = GL_DONT_CARE;
-}
+
+/*
+ * Mesa 3-D graphics library
+ * Version: 4.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.
+ */
+
+
+#include "glheader.h"
+#include "enums.h"
+#include "context.h"
+#include "hint.h"
+#include "imports.h"
+#include "mtypes.h"
+
+
+
+void GLAPIENTRY
+_mesa_Hint( GLenum target, GLenum mode )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glHint %s %s\n",
+ _mesa_lookup_enum_by_nr(target),
+ _mesa_lookup_enum_by_nr(mode));
+
+ if (mode != GL_NICEST && mode != GL_FASTEST && mode != GL_DONT_CARE) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glHint(mode)");
+ return;
+ }
+
+ switch (target) {
+ case GL_FOG_HINT:
+ if (ctx->Hint.Fog == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.Fog = mode;
+ break;
+ case GL_LINE_SMOOTH_HINT:
+ if (ctx->Hint.LineSmooth == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.LineSmooth = mode;
+ break;
+ case GL_PERSPECTIVE_CORRECTION_HINT:
+ if (ctx->Hint.PerspectiveCorrection == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.PerspectiveCorrection = mode;
+ break;
+ case GL_POINT_SMOOTH_HINT:
+ if (ctx->Hint.PointSmooth == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.PointSmooth = mode;
+ break;
+ case GL_POLYGON_SMOOTH_HINT:
+ if (ctx->Hint.PolygonSmooth == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.PolygonSmooth = mode;
+ break;
+
+ /* GL_EXT_clip_volume_hint */
+ case GL_CLIP_VOLUME_CLIPPING_HINT_EXT:
+ if (ctx->Hint.ClipVolumeClipping == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.ClipVolumeClipping = mode;
+ break;
+
+ /* GL_ARB_texture_compression */
+ case GL_TEXTURE_COMPRESSION_HINT_ARB:
+ if (ctx->Hint.TextureCompression == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.TextureCompression = mode;
+ break;
+
+ /* GL_SGIS_generate_mipmap */
+ case GL_GENERATE_MIPMAP_HINT_SGIS:
+ if (ctx->Hint.GenerateMipmap == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.GenerateMipmap = mode;
+ break;
+
+ /* GL_ARB_fragment_shader */
+ case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB:
+ if (!ctx->Extensions.ARB_fragment_shader) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glHint(target)");
+ return;
+ }
+ if (ctx->Hint.FragmentShaderDerivative == mode)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_HINT);
+ ctx->Hint.FragmentShaderDerivative = mode;
+ break;
+
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glHint(target)");
+ return;
+ }
+
+ if (ctx->Driver.Hint) {
+ (*ctx->Driver.Hint)( ctx, target, mode );
+ }
+}
+
+
+/**********************************************************************/
+/***** Initialization *****/
+/**********************************************************************/
+
+void _mesa_init_hint( struct gl_context * ctx )
+{
+ /* Hint group */
+ ctx->Hint.PerspectiveCorrection = GL_DONT_CARE;
+ ctx->Hint.PointSmooth = GL_DONT_CARE;
+ ctx->Hint.LineSmooth = GL_DONT_CARE;
+ ctx->Hint.PolygonSmooth = GL_DONT_CARE;
+ ctx->Hint.Fog = GL_DONT_CARE;
+ ctx->Hint.ClipVolumeClipping = GL_DONT_CARE;
+ ctx->Hint.TextureCompression = GL_DONT_CARE;
+ ctx->Hint.GenerateMipmap = GL_DONT_CARE;
+ ctx->Hint.FragmentShaderDerivative = GL_DONT_CARE;
+}
diff --git a/mesalib/src/mesa/main/imports.c b/mesalib/src/mesa/main/imports.c
index bf89815f2..3f856402f 100644
--- a/mesalib/src/mesa/main/imports.c
+++ b/mesalib/src/mesa/main/imports.c
@@ -1,1028 +1,1028 @@
-/**
- * \file imports.c
- * Standard C library function wrappers.
- *
- * Imports are services which the device driver or window system or
- * operating system provides to the core renderer. The core renderer (Mesa)
- * will call these functions in order to do memory allocation, simple I/O,
- * etc.
- *
- * Some drivers will want to override/replace this file with something
- * specialized, but that'll be rare.
- *
- * Eventually, I want to move roll the glheader.h file into this.
- *
- * \todo Functions still needed:
- * - scanf
- * - qsort
- * - rand and RAND_MAX
- */
-
-/*
- * Mesa 3-D graphics library
- * Version: 7.1
- *
- * Copyright (C) 1999-2007 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.
- */
-
-
-
-#include "imports.h"
-#include "context.h"
-#include "mtypes.h"
-#include "version.h"
-
-#ifdef _GNU_SOURCE
-#include <locale.h>
-#ifdef __APPLE__
-#include <xlocale.h>
-#endif
-#endif
-
-
-#define MAXSTRING 4000 /* for vsnprintf() */
-
-#ifdef WIN32
-#define vsnprintf _vsnprintf
-#elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
-extern int vsnprintf(char *str, size_t count, const char *fmt, va_list arg);
-#ifdef __VMS
-#include "vsnprintf.c"
-#endif
-#endif
-
-/**********************************************************************/
-/** \name Memory */
-/*@{*/
-
-/**
- * Allocate aligned memory.
- *
- * \param bytes number of bytes to allocate.
- * \param alignment alignment (must be greater than zero).
- *
- * Allocates extra memory to accommodate rounding up the address for
- * alignment and to record the real malloc address.
- *
- * \sa _mesa_align_free().
- */
-void *
-_mesa_align_malloc(size_t bytes, unsigned long alignment)
-{
-#if defined(HAVE_POSIX_MEMALIGN)
- void *mem;
- int err = posix_memalign(& mem, alignment, bytes);
- if (err)
- return NULL;
- return mem;
-#elif defined(_WIN32) && defined(_MSC_VER)
- return _aligned_malloc(bytes, alignment);
-#else
- uintptr_t ptr, buf;
-
- ASSERT( alignment > 0 );
-
- ptr = (uintptr_t) malloc(bytes + alignment + sizeof(void *));
- if (!ptr)
- return NULL;
-
- buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
- *(uintptr_t *)(buf - sizeof(void *)) = ptr;
-
-#ifdef DEBUG
- /* mark the non-aligned area */
- while ( ptr < buf - sizeof(void *) ) {
- *(unsigned long *)ptr = 0xcdcdcdcd;
- ptr += sizeof(unsigned long);
- }
-#endif
-
- return (void *) buf;
-#endif /* defined(HAVE_POSIX_MEMALIGN) */
-}
-
-/**
- * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
- * malloc()
- */
-void *
-_mesa_align_calloc(size_t bytes, unsigned long alignment)
-{
-#if defined(HAVE_POSIX_MEMALIGN)
- void *mem;
-
- mem = _mesa_align_malloc(bytes, alignment);
- if (mem != NULL) {
- (void) memset(mem, 0, bytes);
- }
-
- return mem;
-#elif defined(_WIN32) && defined(_MSC_VER)
- void *mem;
-
- mem = _aligned_malloc(bytes, alignment);
- if (mem != NULL) {
- (void) memset(mem, 0, bytes);
- }
-
- return mem;
-#else
- uintptr_t ptr, buf;
-
- ASSERT( alignment > 0 );
-
- ptr = (uintptr_t) calloc(1, bytes + alignment + sizeof(void *));
- if (!ptr)
- return NULL;
-
- buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
- *(uintptr_t *)(buf - sizeof(void *)) = ptr;
-
-#ifdef DEBUG
- /* mark the non-aligned area */
- while ( ptr < buf - sizeof(void *) ) {
- *(unsigned long *)ptr = 0xcdcdcdcd;
- ptr += sizeof(unsigned long);
- }
-#endif
-
- return (void *)buf;
-#endif /* defined(HAVE_POSIX_MEMALIGN) */
-}
-
-/**
- * Free memory which was allocated with either _mesa_align_malloc()
- * or _mesa_align_calloc().
- * \param ptr pointer to the memory to be freed.
- * The actual address to free is stored in the word immediately before the
- * address the client sees.
- */
-void
-_mesa_align_free(void *ptr)
-{
-#if defined(HAVE_POSIX_MEMALIGN)
- free(ptr);
-#elif defined(_WIN32) && defined(_MSC_VER)
- _aligned_free(ptr);
-#else
- void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
- void *realAddr = *cubbyHole;
- free(realAddr);
-#endif /* defined(HAVE_POSIX_MEMALIGN) */
-}
-
-/**
- * Reallocate memory, with alignment.
- */
-void *
-_mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
- unsigned long alignment)
-{
-#if defined(_WIN32) && defined(_MSC_VER)
- (void) oldSize;
- return _aligned_realloc(oldBuffer, newSize, alignment);
-#else
- const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
- void *newBuf = _mesa_align_malloc(newSize, alignment);
- if (newBuf && oldBuffer && copySize > 0) {
- memcpy(newBuf, oldBuffer, copySize);
- }
- if (oldBuffer)
- _mesa_align_free(oldBuffer);
- return newBuf;
-#endif
-}
-
-
-
-/** Reallocate memory */
-void *
-_mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
-{
- const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
- void *newBuffer = malloc(newSize);
- if (newBuffer && oldBuffer && copySize > 0)
- memcpy(newBuffer, oldBuffer, copySize);
- if (oldBuffer)
- free(oldBuffer);
- return newBuffer;
-}
-
-/**
- * Fill memory with a constant 16bit word.
- * \param dst destination pointer.
- * \param val value.
- * \param n number of words.
- */
-void
-_mesa_memset16( unsigned short *dst, unsigned short val, size_t n )
-{
- while (n-- > 0)
- *dst++ = val;
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name Math */
-/*@{*/
-
-/** Wrapper around sqrt() */
-double
-_mesa_sqrtd(double x)
-{
- return sqrt(x);
-}
-
-
-/*
- * A High Speed, Low Precision Square Root
- * by Paul Lalonde and Robert Dawson
- * from "Graphics Gems", Academic Press, 1990
- *
- * SPARC implementation of a fast square root by table
- * lookup.
- * SPARC floating point format is as follows:
- *
- * BIT 31 30 23 22 0
- * sign exponent mantissa
- */
-static short sqrttab[0x100]; /* declare table of square roots */
-
-void
-_mesa_init_sqrt_table(void)
-{
-#if defined(USE_IEEE) && !defined(DEBUG)
- unsigned short i;
- fi_type fi; /* to access the bits of a float in C quickly */
- /* we use a union defined in glheader.h */
-
- for(i=0; i<= 0x7f; i++) {
- fi.i = 0;
-
- /*
- * Build a float with the bit pattern i as mantissa
- * and an exponent of 0, stored as 127
- */
-
- fi.i = (i << 16) | (127 << 23);
- fi.f = _mesa_sqrtd(fi.f);
-
- /*
- * Take the square root then strip the first 7 bits of
- * the mantissa into the table
- */
-
- sqrttab[i] = (fi.i & 0x7fffff) >> 16;
-
- /*
- * Repeat the process, this time with an exponent of
- * 1, stored as 128
- */
-
- fi.i = 0;
- fi.i = (i << 16) | (128 << 23);
- fi.f = sqrt(fi.f);
- sqrttab[i+0x80] = (fi.i & 0x7fffff) >> 16;
- }
-#else
- (void) sqrttab; /* silence compiler warnings */
-#endif /*HAVE_FAST_MATH*/
-}
-
-
-/**
- * Single precision square root.
- */
-float
-_mesa_sqrtf( float x )
-{
-#if defined(USE_IEEE) && !defined(DEBUG)
- fi_type num;
- /* to access the bits of a float in C
- * we use a union from glheader.h */
-
- short e; /* the exponent */
- if (x == 0.0F) return 0.0F; /* check for square root of 0 */
- num.f = x;
- e = (num.i >> 23) - 127; /* get the exponent - on a SPARC the */
- /* exponent is stored with 127 added */
- num.i &= 0x7fffff; /* leave only the mantissa */
- if (e & 0x01) num.i |= 0x800000;
- /* the exponent is odd so we have to */
- /* look it up in the second half of */
- /* the lookup table, so we set the */
- /* high bit */
- e >>= 1; /* divide the exponent by two */
- /* note that in C the shift */
- /* operators are sign preserving */
- /* for signed operands */
- /* Do the table lookup, based on the quaternary mantissa,
- * then reconstruct the result back into a float
- */
- num.i = ((sqrttab[num.i >> 16]) << 16) | ((e + 127) << 23);
-
- return num.f;
-#else
- return (float) _mesa_sqrtd((double) x);
-#endif
-}
-
-
-/**
- inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
- written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
- and Vesa Karvonen.
-*/
-float
-_mesa_inv_sqrtf(float n)
-{
-#if defined(USE_IEEE) && !defined(DEBUG)
- float r0, x0, y0;
- float r1, x1, y1;
- float r2, x2, y2;
-#if 0 /* not used, see below -BP */
- float r3, x3, y3;
-#endif
- fi_type u;
- unsigned int magic;
-
- /*
- Exponent part of the magic number -
-
- We want to:
- 1. subtract the bias from the exponent,
- 2. negate it
- 3. divide by two (rounding towards -inf)
- 4. add the bias back
-
- Which is the same as subtracting the exponent from 381 and dividing
- by 2.
-
- floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
- */
-
- magic = 381 << 23;
-
- /*
- Significand part of magic number -
-
- With the current magic number, "(magic - u.i) >> 1" will give you:
-
- for 1 <= u.f <= 2: 1.25 - u.f / 4
- for 2 <= u.f <= 4: 1.00 - u.f / 8
-
- This isn't a bad approximation of 1/sqrt. The maximum difference from
- 1/sqrt will be around .06. After three Newton-Raphson iterations, the
- maximum difference is less than 4.5e-8. (Which is actually close
- enough to make the following bias academic...)
-
- To get a better approximation you can add a bias to the magic
- number. For example, if you subtract 1/2 of the maximum difference in
- the first approximation (.03), you will get the following function:
-
- for 1 <= u.f <= 2: 1.22 - u.f / 4
- for 2 <= u.f <= 3.76: 0.97 - u.f / 8
- for 3.76 <= u.f <= 4: 0.72 - u.f / 16
- (The 3.76 to 4 range is where the result is < .5.)
-
- This is the closest possible initial approximation, but with a maximum
- error of 8e-11 after three NR iterations, it is still not perfect. If
- you subtract 0.0332281 instead of .03, the maximum error will be
- 2.5e-11 after three NR iterations, which should be about as close as
- is possible.
-
- for 1 <= u.f <= 2: 1.2167719 - u.f / 4
- for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
- for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
-
- */
-
- magic -= (int)(0.0332281 * (1 << 25));
-
- u.f = n;
- u.i = (magic - u.i) >> 1;
-
- /*
- Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
- allows more parallelism. From what I understand, the parallelism
- comes at the cost of less precision, because it lets error
- accumulate across iterations.
- */
- x0 = 1.0f;
- y0 = 0.5f * n;
- r0 = u.f;
-
- x1 = x0 * r0;
- y1 = y0 * r0 * r0;
- r1 = 1.5f - y1;
-
- x2 = x1 * r1;
- y2 = y1 * r1 * r1;
- r2 = 1.5f - y2;
-
-#if 1
- return x2 * r2; /* we can stop here, and be conformant -BP */
-#else
- x3 = x2 * r2;
- y3 = y2 * r2 * r2;
- r3 = 1.5f - y3;
-
- return x3 * r3;
-#endif
-#else
- return (float) (1.0 / sqrt(n));
-#endif
-}
-
-#ifndef __GNUC__
-/**
- * Find the first bit set in a word.
- */
-int
-_mesa_ffs(int32_t i)
-{
-#if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
- register int bit = 0;
- if (i != 0) {
- if ((i & 0xffff) == 0) {
- bit += 16;
- i >>= 16;
- }
- if ((i & 0xff) == 0) {
- bit += 8;
- i >>= 8;
- }
- if ((i & 0xf) == 0) {
- bit += 4;
- i >>= 4;
- }
- while ((i & 1) == 0) {
- bit++;
- i >>= 1;
- }
- bit++;
- }
- return bit;
-#else
- return ffs(i);
-#endif
-}
-
-
-/**
- * Find position of first bit set in given value.
- * XXX Warning: this function can only be used on 64-bit systems!
- * \return position of least-significant bit set, starting at 1, return zero
- * if no bits set.
- */
-int
-_mesa_ffsll(int64_t val)
-{
- int bit;
-
- assert(sizeof(val) == 8);
-
- bit = _mesa_ffs((int32_t)val);
- if (bit != 0)
- return bit;
-
- bit = _mesa_ffs((int32_t)(val >> 32));
- if (bit != 0)
- return 32 + bit;
-
- return 0;
-}
-
-
-#if ((_GNUC__ == 3 && __GNUC_MINOR__ < 4) || __GNUC__ < 4)
-/**
- * Return number of bits set in given GLuint.
- */
-unsigned int
-_mesa_bitcount(unsigned int n)
-{
- unsigned int bits;
- for (bits = 0; n > 0; n = n >> 1) {
- bits += (n & 1);
- }
- return bits;
-}
-#endif
-#endif
-
-
-/**
- * Convert a 4-byte float to a 2-byte half float.
- * Based on code from:
- * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
- */
-GLhalfARB
-_mesa_float_to_half(float val)
-{
- const fi_type fi = {val};
- const int flt_m = fi.i & 0x7fffff;
- const int flt_e = (fi.i >> 23) & 0xff;
- const int flt_s = (fi.i >> 31) & 0x1;
- int s, e, m = 0;
- GLhalfARB result;
-
- /* sign bit */
- s = flt_s;
-
- /* handle special cases */
- if ((flt_e == 0) && (flt_m == 0)) {
- /* zero */
- /* m = 0; - already set */
- e = 0;
- }
- else if ((flt_e == 0) && (flt_m != 0)) {
- /* denorm -- denorm float maps to 0 half */
- /* m = 0; - already set */
- e = 0;
- }
- else if ((flt_e == 0xff) && (flt_m == 0)) {
- /* infinity */
- /* m = 0; - already set */
- e = 31;
- }
- else if ((flt_e == 0xff) && (flt_m != 0)) {
- /* NaN */
- m = 1;
- e = 31;
- }
- else {
- /* regular number */
- const int new_exp = flt_e - 127;
- if (new_exp < -24) {
- /* this maps to 0 */
- /* m = 0; - already set */
- e = 0;
- }
- else if (new_exp < -14) {
- /* this maps to a denorm */
- unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
- e = 0;
- switch (exp_val) {
- case 0:
- _mesa_warning(NULL,
- "float_to_half: logical error in denorm creation!\n");
- /* m = 0; - already set */
- break;
- case 1: m = 512 + (flt_m >> 14); break;
- case 2: m = 256 + (flt_m >> 15); break;
- case 3: m = 128 + (flt_m >> 16); break;
- case 4: m = 64 + (flt_m >> 17); break;
- case 5: m = 32 + (flt_m >> 18); break;
- case 6: m = 16 + (flt_m >> 19); break;
- case 7: m = 8 + (flt_m >> 20); break;
- case 8: m = 4 + (flt_m >> 21); break;
- case 9: m = 2 + (flt_m >> 22); break;
- case 10: m = 1; break;
- }
- }
- else if (new_exp > 15) {
- /* map this value to infinity */
- /* m = 0; - already set */
- e = 31;
- }
- else {
- /* regular */
- e = new_exp + 15;
- m = flt_m >> 13;
- }
- }
-
- result = (s << 15) | (e << 10) | m;
- return result;
-}
-
-
-/**
- * Convert a 2-byte half float to a 4-byte float.
- * Based on code from:
- * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
- */
-float
-_mesa_half_to_float(GLhalfARB val)
-{
- /* XXX could also use a 64K-entry lookup table */
- const int m = val & 0x3ff;
- const int e = (val >> 10) & 0x1f;
- const int s = (val >> 15) & 0x1;
- int flt_m, flt_e, flt_s;
- fi_type fi;
- float result;
-
- /* sign bit */
- flt_s = s;
-
- /* handle special cases */
- if ((e == 0) && (m == 0)) {
- /* zero */
- flt_m = 0;
- flt_e = 0;
- }
- else if ((e == 0) && (m != 0)) {
- /* denorm -- denorm half will fit in non-denorm single */
- const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
- float mantissa = ((float) (m)) / 1024.0f;
- float sign = s ? -1.0f : 1.0f;
- return sign * mantissa * half_denorm;
- }
- else if ((e == 31) && (m == 0)) {
- /* infinity */
- flt_e = 0xff;
- flt_m = 0;
- }
- else if ((e == 31) && (m != 0)) {
- /* NaN */
- flt_e = 0xff;
- flt_m = 1;
- }
- else {
- /* regular */
- flt_e = e + 112;
- flt_m = m << 13;
- }
-
- fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
- result = fi.f;
- return result;
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name Sort & Search */
-/*@{*/
-
-/**
- * Wrapper for bsearch().
- */
-void *
-_mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
- int (*compar)(const void *, const void *) )
-{
-#if defined(_WIN32_WCE)
- void *mid;
- int cmp;
- while (nmemb) {
- nmemb >>= 1;
- mid = (char *)base + nmemb * size;
- cmp = (*compar)(key, mid);
- if (cmp == 0)
- return mid;
- if (cmp > 0) {
- base = (char *)mid + size;
- --nmemb;
- }
- }
- return NULL;
-#else
- return bsearch(key, base, nmemb, size, compar);
-#endif
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name Environment vars */
-/*@{*/
-
-/**
- * Wrapper for getenv().
- */
-char *
-_mesa_getenv( const char *var )
-{
-#if defined(_XBOX) || defined(_WIN32_WCE)
- return NULL;
-#else
- return getenv(var);
-#endif
-}
-
-/*@}*/
-
-
-/**********************************************************************/
-/** \name String */
-/*@{*/
-
-/**
- * Implemented using malloc() and strcpy.
- * Note that NULL is handled accordingly.
- */
-char *
-_mesa_strdup( const char *s )
-{
- if (s) {
- size_t l = strlen(s);
- char *s2 = (char *) malloc(l + 1);
- if (s2)
- strcpy(s2, s);
- return s2;
- }
- else {
- return NULL;
- }
-}
-
-/** Wrapper around strtof() */
-float
-_mesa_strtof( const char *s, char **end )
-{
-#if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
- static locale_t loc = NULL;
- if (!loc) {
- loc = newlocale(LC_CTYPE_MASK, "C", NULL);
- }
- return strtof_l(s, end, loc);
-#elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
- return strtof(s, end);
-#else
- return (float)strtod(s, end);
-#endif
-}
-
-/** Compute simple checksum/hash for a string */
-unsigned int
-_mesa_str_checksum(const char *str)
-{
- /* This could probably be much better */
- unsigned int sum, i;
- const char *c;
- sum = i = 1;
- for (c = str; *c; c++, i++)
- sum += *c * (i % 100);
- return sum + i;
-}
-
-
-/*@}*/
-
-
-/** Wrapper around vsnprintf() */
-int
-_mesa_snprintf( char *str, size_t size, const char *fmt, ... )
-{
- int r;
- va_list args;
- va_start( args, fmt );
- r = vsnprintf( str, size, fmt, args );
- va_end( args );
- return r;
-}
-
-
-/**********************************************************************/
-/** \name Diagnostics */
-/*@{*/
-
-static void
-output_if_debug(const char *prefixString, const char *outputString,
- GLboolean newline)
-{
- static int debug = -1;
-
- /* Check the MESA_DEBUG environment variable if it hasn't
- * been checked yet. We only have to check it once...
- */
- if (debug == -1) {
- char *env = _mesa_getenv("MESA_DEBUG");
-
- /* In a debug build, we print warning messages *unless*
- * MESA_DEBUG is 0. In a non-debug build, we don't
- * print warning messages *unless* MESA_DEBUG is
- * set *to any value*.
- */
-#ifdef DEBUG
- debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
-#else
- debug = (env != NULL) ? 1 : 0;
-#endif
- }
-
- /* Now only print the string if we're required to do so. */
- if (debug) {
- fprintf(stderr, "%s: %s", prefixString, outputString);
- if (newline)
- fprintf(stderr, "\n");
-
-#if defined(_WIN32) && !defined(_WIN32_WCE)
- /* stderr from windows applications without console is not usually
- * visible, so communicate with the debugger instead */
- {
- char buf[4096];
- _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
- OutputDebugStringA(buf);
- }
-#endif
- }
-}
-
-
-/**
- * Return string version of GL error code.
- */
-static const char *
-error_string( GLenum error )
-{
- switch (error) {
- case GL_NO_ERROR:
- return "GL_NO_ERROR";
- case GL_INVALID_VALUE:
- return "GL_INVALID_VALUE";
- case GL_INVALID_ENUM:
- return "GL_INVALID_ENUM";
- case GL_INVALID_OPERATION:
- return "GL_INVALID_OPERATION";
- case GL_STACK_OVERFLOW:
- return "GL_STACK_OVERFLOW";
- case GL_STACK_UNDERFLOW:
- return "GL_STACK_UNDERFLOW";
- case GL_OUT_OF_MEMORY:
- return "GL_OUT_OF_MEMORY";
- case GL_TABLE_TOO_LARGE:
- return "GL_TABLE_TOO_LARGE";
- case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
- return "GL_INVALID_FRAMEBUFFER_OPERATION";
- default:
- return "unknown";
- }
-}
-
-
-/**
- * When a new type of error is recorded, print a message describing
- * previous errors which were accumulated.
- */
-static void
-flush_delayed_errors( struct gl_context *ctx )
-{
- char s[MAXSTRING];
-
- if (ctx->ErrorDebugCount) {
- _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
- ctx->ErrorDebugCount,
- error_string(ctx->ErrorValue));
-
- output_if_debug("Mesa", s, GL_TRUE);
-
- ctx->ErrorDebugCount = 0;
- }
-}
-
-
-/**
- * Report a warning (a recoverable error condition) to stderr if
- * either DEBUG is defined or the MESA_DEBUG env var is set.
- *
- * \param ctx GL context.
- * \param fmtString printf()-like format string.
- */
-void
-_mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
-{
- char str[MAXSTRING];
- va_list args;
- va_start( args, fmtString );
- (void) vsnprintf( str, MAXSTRING, fmtString, args );
- va_end( args );
-
- if (ctx)
- flush_delayed_errors( ctx );
-
- output_if_debug("Mesa warning", str, GL_TRUE);
-}
-
-
-/**
- * Report an internal implementation problem.
- * Prints the message to stderr via fprintf().
- *
- * \param ctx GL context.
- * \param fmtString problem description string.
- */
-void
-_mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
-{
- va_list args;
- char str[MAXSTRING];
- (void) ctx;
-
- va_start( args, fmtString );
- vsnprintf( str, MAXSTRING, fmtString, args );
- va_end( args );
-
- fprintf(stderr, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING, str);
- fprintf(stderr, "Please report at bugs.freedesktop.org\n");
-}
-
-
-/**
- * Record an OpenGL state error. These usually occur when the user
- * passes invalid parameters to a GL function.
- *
- * If debugging is enabled (either at compile-time via the DEBUG macro, or
- * run-time via the MESA_DEBUG environment variable), report the error with
- * _mesa_debug().
- *
- * \param ctx the GL context.
- * \param error the error value.
- * \param fmtString printf() style format string, followed by optional args
- */
-void
-_mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
-{
- static GLint debug = -1;
-
- /* Check debug environment variable only once:
- */
- if (debug == -1) {
- const char *debugEnv = _mesa_getenv("MESA_DEBUG");
-
-#ifdef DEBUG
- if (debugEnv && strstr(debugEnv, "silent"))
- debug = GL_FALSE;
- else
- debug = GL_TRUE;
-#else
- if (debugEnv)
- debug = GL_TRUE;
- else
- debug = GL_FALSE;
-#endif
- }
-
- if (debug) {
- if (ctx->ErrorValue == error &&
- ctx->ErrorDebugFmtString == fmtString) {
- ctx->ErrorDebugCount++;
- }
- else {
- char s[MAXSTRING], s2[MAXSTRING];
- va_list args;
-
- flush_delayed_errors( ctx );
-
- va_start(args, fmtString);
- vsnprintf(s, MAXSTRING, fmtString, args);
- va_end(args);
-
- _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
- output_if_debug("Mesa: User error", s2, GL_TRUE);
-
- ctx->ErrorDebugFmtString = fmtString;
- ctx->ErrorDebugCount = 0;
- }
- }
-
- _mesa_record_error(ctx, error);
-}
-
-
-/**
- * Report debug information. Print error message to stderr via fprintf().
- * No-op if DEBUG mode not enabled.
- *
- * \param ctx GL context.
- * \param fmtString printf()-style format string, followed by optional args.
- */
-void
-_mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
-{
-#ifdef DEBUG
- char s[MAXSTRING];
- va_list args;
- va_start(args, fmtString);
- vsnprintf(s, MAXSTRING, fmtString, args);
- va_end(args);
- output_if_debug("Mesa", s, GL_FALSE);
-#endif /* DEBUG */
- (void) ctx;
- (void) fmtString;
-}
-
-/*@}*/
+/**
+ * \file imports.c
+ * Standard C library function wrappers.
+ *
+ * Imports are services which the device driver or window system or
+ * operating system provides to the core renderer. The core renderer (Mesa)
+ * will call these functions in order to do memory allocation, simple I/O,
+ * etc.
+ *
+ * Some drivers will want to override/replace this file with something
+ * specialized, but that'll be rare.
+ *
+ * Eventually, I want to move roll the glheader.h file into this.
+ *
+ * \todo Functions still needed:
+ * - scanf
+ * - qsort
+ * - rand and RAND_MAX
+ */
+
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.1
+ *
+ * Copyright (C) 1999-2007 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.
+ */
+
+
+
+#include "imports.h"
+#include "context.h"
+#include "mtypes.h"
+#include "version.h"
+
+#ifdef _GNU_SOURCE
+#include <locale.h>
+#ifdef __APPLE__
+#include <xlocale.h>
+#endif
+#endif
+
+
+#define MAXSTRING 4000 /* for vsnprintf() */
+
+#ifdef WIN32
+#define vsnprintf _vsnprintf
+#elif defined(__IBMC__) || defined(__IBMCPP__) || ( defined(__VMS) && __CRTL_VER < 70312000 )
+extern int vsnprintf(char *str, size_t count, const char *fmt, va_list arg);
+#ifdef __VMS
+#include "vsnprintf.c"
+#endif
+#endif
+
+/**********************************************************************/
+/** \name Memory */
+/*@{*/
+
+/**
+ * Allocate aligned memory.
+ *
+ * \param bytes number of bytes to allocate.
+ * \param alignment alignment (must be greater than zero).
+ *
+ * Allocates extra memory to accommodate rounding up the address for
+ * alignment and to record the real malloc address.
+ *
+ * \sa _mesa_align_free().
+ */
+void *
+_mesa_align_malloc(size_t bytes, unsigned long alignment)
+{
+#if defined(HAVE_POSIX_MEMALIGN)
+ void *mem;
+ int err = posix_memalign(& mem, alignment, bytes);
+ if (err)
+ return NULL;
+ return mem;
+#elif defined(_WIN32) && defined(_MSC_VER)
+ return _aligned_malloc(bytes, alignment);
+#else
+ uintptr_t ptr, buf;
+
+ ASSERT( alignment > 0 );
+
+ ptr = (uintptr_t) malloc(bytes + alignment + sizeof(void *));
+ if (!ptr)
+ return NULL;
+
+ buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
+ *(uintptr_t *)(buf - sizeof(void *)) = ptr;
+
+#ifdef DEBUG
+ /* mark the non-aligned area */
+ while ( ptr < buf - sizeof(void *) ) {
+ *(unsigned long *)ptr = 0xcdcdcdcd;
+ ptr += sizeof(unsigned long);
+ }
+#endif
+
+ return (void *) buf;
+#endif /* defined(HAVE_POSIX_MEMALIGN) */
+}
+
+/**
+ * Same as _mesa_align_malloc(), but using calloc(1, ) instead of
+ * malloc()
+ */
+void *
+_mesa_align_calloc(size_t bytes, unsigned long alignment)
+{
+#if defined(HAVE_POSIX_MEMALIGN)
+ void *mem;
+
+ mem = _mesa_align_malloc(bytes, alignment);
+ if (mem != NULL) {
+ (void) memset(mem, 0, bytes);
+ }
+
+ return mem;
+#elif defined(_WIN32) && defined(_MSC_VER)
+ void *mem;
+
+ mem = _aligned_malloc(bytes, alignment);
+ if (mem != NULL) {
+ (void) memset(mem, 0, bytes);
+ }
+
+ return mem;
+#else
+ uintptr_t ptr, buf;
+
+ ASSERT( alignment > 0 );
+
+ ptr = (uintptr_t) calloc(1, bytes + alignment + sizeof(void *));
+ if (!ptr)
+ return NULL;
+
+ buf = (ptr + alignment + sizeof(void *)) & ~(uintptr_t)(alignment - 1);
+ *(uintptr_t *)(buf - sizeof(void *)) = ptr;
+
+#ifdef DEBUG
+ /* mark the non-aligned area */
+ while ( ptr < buf - sizeof(void *) ) {
+ *(unsigned long *)ptr = 0xcdcdcdcd;
+ ptr += sizeof(unsigned long);
+ }
+#endif
+
+ return (void *)buf;
+#endif /* defined(HAVE_POSIX_MEMALIGN) */
+}
+
+/**
+ * Free memory which was allocated with either _mesa_align_malloc()
+ * or _mesa_align_calloc().
+ * \param ptr pointer to the memory to be freed.
+ * The actual address to free is stored in the word immediately before the
+ * address the client sees.
+ */
+void
+_mesa_align_free(void *ptr)
+{
+#if defined(HAVE_POSIX_MEMALIGN)
+ free(ptr);
+#elif defined(_WIN32) && defined(_MSC_VER)
+ _aligned_free(ptr);
+#else
+ void **cubbyHole = (void **) ((char *) ptr - sizeof(void *));
+ void *realAddr = *cubbyHole;
+ free(realAddr);
+#endif /* defined(HAVE_POSIX_MEMALIGN) */
+}
+
+/**
+ * Reallocate memory, with alignment.
+ */
+void *
+_mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
+ unsigned long alignment)
+{
+#if defined(_WIN32) && defined(_MSC_VER)
+ (void) oldSize;
+ return _aligned_realloc(oldBuffer, newSize, alignment);
+#else
+ const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
+ void *newBuf = _mesa_align_malloc(newSize, alignment);
+ if (newBuf && oldBuffer && copySize > 0) {
+ memcpy(newBuf, oldBuffer, copySize);
+ }
+ if (oldBuffer)
+ _mesa_align_free(oldBuffer);
+ return newBuf;
+#endif
+}
+
+
+
+/** Reallocate memory */
+void *
+_mesa_realloc(void *oldBuffer, size_t oldSize, size_t newSize)
+{
+ const size_t copySize = (oldSize < newSize) ? oldSize : newSize;
+ void *newBuffer = malloc(newSize);
+ if (newBuffer && oldBuffer && copySize > 0)
+ memcpy(newBuffer, oldBuffer, copySize);
+ if (oldBuffer)
+ free(oldBuffer);
+ return newBuffer;
+}
+
+/**
+ * Fill memory with a constant 16bit word.
+ * \param dst destination pointer.
+ * \param val value.
+ * \param n number of words.
+ */
+void
+_mesa_memset16( unsigned short *dst, unsigned short val, size_t n )
+{
+ while (n-- > 0)
+ *dst++ = val;
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name Math */
+/*@{*/
+
+/** Wrapper around sqrt() */
+double
+_mesa_sqrtd(double x)
+{
+ return sqrt(x);
+}
+
+
+/*
+ * A High Speed, Low Precision Square Root
+ * by Paul Lalonde and Robert Dawson
+ * from "Graphics Gems", Academic Press, 1990
+ *
+ * SPARC implementation of a fast square root by table
+ * lookup.
+ * SPARC floating point format is as follows:
+ *
+ * BIT 31 30 23 22 0
+ * sign exponent mantissa
+ */
+static short sqrttab[0x100]; /* declare table of square roots */
+
+void
+_mesa_init_sqrt_table(void)
+{
+#if defined(USE_IEEE) && !defined(DEBUG)
+ unsigned short i;
+ fi_type fi; /* to access the bits of a float in C quickly */
+ /* we use a union defined in glheader.h */
+
+ for(i=0; i<= 0x7f; i++) {
+ fi.i = 0;
+
+ /*
+ * Build a float with the bit pattern i as mantissa
+ * and an exponent of 0, stored as 127
+ */
+
+ fi.i = (i << 16) | (127 << 23);
+ fi.f = _mesa_sqrtd(fi.f);
+
+ /*
+ * Take the square root then strip the first 7 bits of
+ * the mantissa into the table
+ */
+
+ sqrttab[i] = (fi.i & 0x7fffff) >> 16;
+
+ /*
+ * Repeat the process, this time with an exponent of
+ * 1, stored as 128
+ */
+
+ fi.i = 0;
+ fi.i = (i << 16) | (128 << 23);
+ fi.f = sqrt(fi.f);
+ sqrttab[i+0x80] = (fi.i & 0x7fffff) >> 16;
+ }
+#else
+ (void) sqrttab; /* silence compiler warnings */
+#endif /*HAVE_FAST_MATH*/
+}
+
+
+/**
+ * Single precision square root.
+ */
+float
+_mesa_sqrtf( float x )
+{
+#if defined(USE_IEEE) && !defined(DEBUG)
+ fi_type num;
+ /* to access the bits of a float in C
+ * we use a union from glheader.h */
+
+ short e; /* the exponent */
+ if (x == 0.0F) return 0.0F; /* check for square root of 0 */
+ num.f = x;
+ e = (num.i >> 23) - 127; /* get the exponent - on a SPARC the */
+ /* exponent is stored with 127 added */
+ num.i &= 0x7fffff; /* leave only the mantissa */
+ if (e & 0x01) num.i |= 0x800000;
+ /* the exponent is odd so we have to */
+ /* look it up in the second half of */
+ /* the lookup table, so we set the */
+ /* high bit */
+ e >>= 1; /* divide the exponent by two */
+ /* note that in C the shift */
+ /* operators are sign preserving */
+ /* for signed operands */
+ /* Do the table lookup, based on the quaternary mantissa,
+ * then reconstruct the result back into a float
+ */
+ num.i = ((sqrttab[num.i >> 16]) << 16) | ((e + 127) << 23);
+
+ return num.f;
+#else
+ return (float) _mesa_sqrtd((double) x);
+#endif
+}
+
+
+/**
+ inv_sqrt - A single precision 1/sqrt routine for IEEE format floats.
+ written by Josh Vanderhoof, based on newsgroup posts by James Van Buskirk
+ and Vesa Karvonen.
+*/
+float
+_mesa_inv_sqrtf(float n)
+{
+#if defined(USE_IEEE) && !defined(DEBUG)
+ float r0, x0, y0;
+ float r1, x1, y1;
+ float r2, x2, y2;
+#if 0 /* not used, see below -BP */
+ float r3, x3, y3;
+#endif
+ fi_type u;
+ unsigned int magic;
+
+ /*
+ Exponent part of the magic number -
+
+ We want to:
+ 1. subtract the bias from the exponent,
+ 2. negate it
+ 3. divide by two (rounding towards -inf)
+ 4. add the bias back
+
+ Which is the same as subtracting the exponent from 381 and dividing
+ by 2.
+
+ floor(-(x - 127) / 2) + 127 = floor((381 - x) / 2)
+ */
+
+ magic = 381 << 23;
+
+ /*
+ Significand part of magic number -
+
+ With the current magic number, "(magic - u.i) >> 1" will give you:
+
+ for 1 <= u.f <= 2: 1.25 - u.f / 4
+ for 2 <= u.f <= 4: 1.00 - u.f / 8
+
+ This isn't a bad approximation of 1/sqrt. The maximum difference from
+ 1/sqrt will be around .06. After three Newton-Raphson iterations, the
+ maximum difference is less than 4.5e-8. (Which is actually close
+ enough to make the following bias academic...)
+
+ To get a better approximation you can add a bias to the magic
+ number. For example, if you subtract 1/2 of the maximum difference in
+ the first approximation (.03), you will get the following function:
+
+ for 1 <= u.f <= 2: 1.22 - u.f / 4
+ for 2 <= u.f <= 3.76: 0.97 - u.f / 8
+ for 3.76 <= u.f <= 4: 0.72 - u.f / 16
+ (The 3.76 to 4 range is where the result is < .5.)
+
+ This is the closest possible initial approximation, but with a maximum
+ error of 8e-11 after three NR iterations, it is still not perfect. If
+ you subtract 0.0332281 instead of .03, the maximum error will be
+ 2.5e-11 after three NR iterations, which should be about as close as
+ is possible.
+
+ for 1 <= u.f <= 2: 1.2167719 - u.f / 4
+ for 2 <= u.f <= 3.73: 0.9667719 - u.f / 8
+ for 3.73 <= u.f <= 4: 0.7167719 - u.f / 16
+
+ */
+
+ magic -= (int)(0.0332281 * (1 << 25));
+
+ u.f = n;
+ u.i = (magic - u.i) >> 1;
+
+ /*
+ Instead of Newton-Raphson, we use Goldschmidt's algorithm, which
+ allows more parallelism. From what I understand, the parallelism
+ comes at the cost of less precision, because it lets error
+ accumulate across iterations.
+ */
+ x0 = 1.0f;
+ y0 = 0.5f * n;
+ r0 = u.f;
+
+ x1 = x0 * r0;
+ y1 = y0 * r0 * r0;
+ r1 = 1.5f - y1;
+
+ x2 = x1 * r1;
+ y2 = y1 * r1 * r1;
+ r2 = 1.5f - y2;
+
+#if 1
+ return x2 * r2; /* we can stop here, and be conformant -BP */
+#else
+ x3 = x2 * r2;
+ y3 = y2 * r2 * r2;
+ r3 = 1.5f - y3;
+
+ return x3 * r3;
+#endif
+#else
+ return (float) (1.0 / sqrt(n));
+#endif
+}
+
+#ifndef __GNUC__
+/**
+ * Find the first bit set in a word.
+ */
+int
+_mesa_ffs(int32_t i)
+{
+#if (defined(_WIN32) ) || defined(__IBMC__) || defined(__IBMCPP__)
+ register int bit = 0;
+ if (i != 0) {
+ if ((i & 0xffff) == 0) {
+ bit += 16;
+ i >>= 16;
+ }
+ if ((i & 0xff) == 0) {
+ bit += 8;
+ i >>= 8;
+ }
+ if ((i & 0xf) == 0) {
+ bit += 4;
+ i >>= 4;
+ }
+ while ((i & 1) == 0) {
+ bit++;
+ i >>= 1;
+ }
+ bit++;
+ }
+ return bit;
+#else
+ return ffs(i);
+#endif
+}
+
+
+/**
+ * Find position of first bit set in given value.
+ * XXX Warning: this function can only be used on 64-bit systems!
+ * \return position of least-significant bit set, starting at 1, return zero
+ * if no bits set.
+ */
+int
+_mesa_ffsll(int64_t val)
+{
+ int bit;
+
+ assert(sizeof(val) == 8);
+
+ bit = _mesa_ffs((int32_t)val);
+ if (bit != 0)
+ return bit;
+
+ bit = _mesa_ffs((int32_t)(val >> 32));
+ if (bit != 0)
+ return 32 + bit;
+
+ return 0;
+}
+
+
+#if ((_GNUC__ == 3 && __GNUC_MINOR__ < 4) || __GNUC__ < 4)
+/**
+ * Return number of bits set in given GLuint.
+ */
+unsigned int
+_mesa_bitcount(unsigned int n)
+{
+ unsigned int bits;
+ for (bits = 0; n > 0; n = n >> 1) {
+ bits += (n & 1);
+ }
+ return bits;
+}
+#endif
+#endif
+
+
+/**
+ * Convert a 4-byte float to a 2-byte half float.
+ * Based on code from:
+ * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
+ */
+GLhalfARB
+_mesa_float_to_half(float val)
+{
+ const fi_type fi = {val};
+ const int flt_m = fi.i & 0x7fffff;
+ const int flt_e = (fi.i >> 23) & 0xff;
+ const int flt_s = (fi.i >> 31) & 0x1;
+ int s, e, m = 0;
+ GLhalfARB result;
+
+ /* sign bit */
+ s = flt_s;
+
+ /* handle special cases */
+ if ((flt_e == 0) && (flt_m == 0)) {
+ /* zero */
+ /* m = 0; - already set */
+ e = 0;
+ }
+ else if ((flt_e == 0) && (flt_m != 0)) {
+ /* denorm -- denorm float maps to 0 half */
+ /* m = 0; - already set */
+ e = 0;
+ }
+ else if ((flt_e == 0xff) && (flt_m == 0)) {
+ /* infinity */
+ /* m = 0; - already set */
+ e = 31;
+ }
+ else if ((flt_e == 0xff) && (flt_m != 0)) {
+ /* NaN */
+ m = 1;
+ e = 31;
+ }
+ else {
+ /* regular number */
+ const int new_exp = flt_e - 127;
+ if (new_exp < -24) {
+ /* this maps to 0 */
+ /* m = 0; - already set */
+ e = 0;
+ }
+ else if (new_exp < -14) {
+ /* this maps to a denorm */
+ unsigned int exp_val = (unsigned int) (-14 - new_exp); /* 2^-exp_val*/
+ e = 0;
+ switch (exp_val) {
+ case 0:
+ _mesa_warning(NULL,
+ "float_to_half: logical error in denorm creation!\n");
+ /* m = 0; - already set */
+ break;
+ case 1: m = 512 + (flt_m >> 14); break;
+ case 2: m = 256 + (flt_m >> 15); break;
+ case 3: m = 128 + (flt_m >> 16); break;
+ case 4: m = 64 + (flt_m >> 17); break;
+ case 5: m = 32 + (flt_m >> 18); break;
+ case 6: m = 16 + (flt_m >> 19); break;
+ case 7: m = 8 + (flt_m >> 20); break;
+ case 8: m = 4 + (flt_m >> 21); break;
+ case 9: m = 2 + (flt_m >> 22); break;
+ case 10: m = 1; break;
+ }
+ }
+ else if (new_exp > 15) {
+ /* map this value to infinity */
+ /* m = 0; - already set */
+ e = 31;
+ }
+ else {
+ /* regular */
+ e = new_exp + 15;
+ m = flt_m >> 13;
+ }
+ }
+
+ result = (s << 15) | (e << 10) | m;
+ return result;
+}
+
+
+/**
+ * Convert a 2-byte half float to a 4-byte float.
+ * Based on code from:
+ * http://www.opengl.org/discussion_boards/ubb/Forum3/HTML/008786.html
+ */
+float
+_mesa_half_to_float(GLhalfARB val)
+{
+ /* XXX could also use a 64K-entry lookup table */
+ const int m = val & 0x3ff;
+ const int e = (val >> 10) & 0x1f;
+ const int s = (val >> 15) & 0x1;
+ int flt_m, flt_e, flt_s;
+ fi_type fi;
+ float result;
+
+ /* sign bit */
+ flt_s = s;
+
+ /* handle special cases */
+ if ((e == 0) && (m == 0)) {
+ /* zero */
+ flt_m = 0;
+ flt_e = 0;
+ }
+ else if ((e == 0) && (m != 0)) {
+ /* denorm -- denorm half will fit in non-denorm single */
+ const float half_denorm = 1.0f / 16384.0f; /* 2^-14 */
+ float mantissa = ((float) (m)) / 1024.0f;
+ float sign = s ? -1.0f : 1.0f;
+ return sign * mantissa * half_denorm;
+ }
+ else if ((e == 31) && (m == 0)) {
+ /* infinity */
+ flt_e = 0xff;
+ flt_m = 0;
+ }
+ else if ((e == 31) && (m != 0)) {
+ /* NaN */
+ flt_e = 0xff;
+ flt_m = 1;
+ }
+ else {
+ /* regular */
+ flt_e = e + 112;
+ flt_m = m << 13;
+ }
+
+ fi.i = (flt_s << 31) | (flt_e << 23) | flt_m;
+ result = fi.f;
+ return result;
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name Sort & Search */
+/*@{*/
+
+/**
+ * Wrapper for bsearch().
+ */
+void *
+_mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
+ int (*compar)(const void *, const void *) )
+{
+#if defined(_WIN32_WCE)
+ void *mid;
+ int cmp;
+ while (nmemb) {
+ nmemb >>= 1;
+ mid = (char *)base + nmemb * size;
+ cmp = (*compar)(key, mid);
+ if (cmp == 0)
+ return mid;
+ if (cmp > 0) {
+ base = (char *)mid + size;
+ --nmemb;
+ }
+ }
+ return NULL;
+#else
+ return bsearch(key, base, nmemb, size, compar);
+#endif
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name Environment vars */
+/*@{*/
+
+/**
+ * Wrapper for getenv().
+ */
+char *
+_mesa_getenv( const char *var )
+{
+#if defined(_XBOX) || defined(_WIN32_WCE)
+ return NULL;
+#else
+ return getenv(var);
+#endif
+}
+
+/*@}*/
+
+
+/**********************************************************************/
+/** \name String */
+/*@{*/
+
+/**
+ * Implemented using malloc() and strcpy.
+ * Note that NULL is handled accordingly.
+ */
+char *
+_mesa_strdup( const char *s )
+{
+ if (s) {
+ size_t l = strlen(s);
+ char *s2 = (char *) malloc(l + 1);
+ if (s2)
+ strcpy(s2, s);
+ return s2;
+ }
+ else {
+ return NULL;
+ }
+}
+
+/** Wrapper around strtof() */
+float
+_mesa_strtof( const char *s, char **end )
+{
+#if defined(_GNU_SOURCE) && !defined(__CYGWIN__) && !defined(__FreeBSD__)
+ static locale_t loc = NULL;
+ if (!loc) {
+ loc = newlocale(LC_CTYPE_MASK, "C", NULL);
+ }
+ return strtof_l(s, end, loc);
+#elif defined(_ISOC99_SOURCE) || (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600)
+ return strtof(s, end);
+#else
+ return (float)strtod(s, end);
+#endif
+}
+
+/** Compute simple checksum/hash for a string */
+unsigned int
+_mesa_str_checksum(const char *str)
+{
+ /* This could probably be much better */
+ unsigned int sum, i;
+ const char *c;
+ sum = i = 1;
+ for (c = str; *c; c++, i++)
+ sum += *c * (i % 100);
+ return sum + i;
+}
+
+
+/*@}*/
+
+
+/** Wrapper around vsnprintf() */
+int
+_mesa_snprintf( char *str, size_t size, const char *fmt, ... )
+{
+ int r;
+ va_list args;
+ va_start( args, fmt );
+ r = vsnprintf( str, size, fmt, args );
+ va_end( args );
+ return r;
+}
+
+
+/**********************************************************************/
+/** \name Diagnostics */
+/*@{*/
+
+static void
+output_if_debug(const char *prefixString, const char *outputString,
+ GLboolean newline)
+{
+ static int debug = -1;
+
+ /* Check the MESA_DEBUG environment variable if it hasn't
+ * been checked yet. We only have to check it once...
+ */
+ if (debug == -1) {
+ char *env = _mesa_getenv("MESA_DEBUG");
+
+ /* In a debug build, we print warning messages *unless*
+ * MESA_DEBUG is 0. In a non-debug build, we don't
+ * print warning messages *unless* MESA_DEBUG is
+ * set *to any value*.
+ */
+#ifdef DEBUG
+ debug = (env != NULL && atoi(env) == 0) ? 0 : 1;
+#else
+ debug = (env != NULL) ? 1 : 0;
+#endif
+ }
+
+ /* Now only print the string if we're required to do so. */
+ if (debug) {
+ fprintf(stderr, "%s: %s", prefixString, outputString);
+ if (newline)
+ fprintf(stderr, "\n");
+
+#if defined(_WIN32) && !defined(_WIN32_WCE)
+ /* stderr from windows applications without console is not usually
+ * visible, so communicate with the debugger instead */
+ {
+ char buf[4096];
+ _mesa_snprintf(buf, sizeof(buf), "%s: %s%s", prefixString, outputString, newline ? "\n" : "");
+ OutputDebugStringA(buf);
+ }
+#endif
+ }
+}
+
+
+/**
+ * Return string version of GL error code.
+ */
+static const char *
+error_string( GLenum error )
+{
+ switch (error) {
+ case GL_NO_ERROR:
+ return "GL_NO_ERROR";
+ case GL_INVALID_VALUE:
+ return "GL_INVALID_VALUE";
+ case GL_INVALID_ENUM:
+ return "GL_INVALID_ENUM";
+ case GL_INVALID_OPERATION:
+ return "GL_INVALID_OPERATION";
+ case GL_STACK_OVERFLOW:
+ return "GL_STACK_OVERFLOW";
+ case GL_STACK_UNDERFLOW:
+ return "GL_STACK_UNDERFLOW";
+ case GL_OUT_OF_MEMORY:
+ return "GL_OUT_OF_MEMORY";
+ case GL_TABLE_TOO_LARGE:
+ return "GL_TABLE_TOO_LARGE";
+ case GL_INVALID_FRAMEBUFFER_OPERATION_EXT:
+ return "GL_INVALID_FRAMEBUFFER_OPERATION";
+ default:
+ return "unknown";
+ }
+}
+
+
+/**
+ * When a new type of error is recorded, print a message describing
+ * previous errors which were accumulated.
+ */
+static void
+flush_delayed_errors( struct gl_context *ctx )
+{
+ char s[MAXSTRING];
+
+ if (ctx->ErrorDebugCount) {
+ _mesa_snprintf(s, MAXSTRING, "%d similar %s errors",
+ ctx->ErrorDebugCount,
+ error_string(ctx->ErrorValue));
+
+ output_if_debug("Mesa", s, GL_TRUE);
+
+ ctx->ErrorDebugCount = 0;
+ }
+}
+
+
+/**
+ * Report a warning (a recoverable error condition) to stderr if
+ * either DEBUG is defined or the MESA_DEBUG env var is set.
+ *
+ * \param ctx GL context.
+ * \param fmtString printf()-like format string.
+ */
+void
+_mesa_warning( struct gl_context *ctx, const char *fmtString, ... )
+{
+ char str[MAXSTRING];
+ va_list args;
+ va_start( args, fmtString );
+ (void) vsnprintf( str, MAXSTRING, fmtString, args );
+ va_end( args );
+
+ if (ctx)
+ flush_delayed_errors( ctx );
+
+ output_if_debug("Mesa warning", str, GL_TRUE);
+}
+
+
+/**
+ * Report an internal implementation problem.
+ * Prints the message to stderr via fprintf().
+ *
+ * \param ctx GL context.
+ * \param fmtString problem description string.
+ */
+void
+_mesa_problem( const struct gl_context *ctx, const char *fmtString, ... )
+{
+ va_list args;
+ char str[MAXSTRING];
+ (void) ctx;
+
+ va_start( args, fmtString );
+ vsnprintf( str, MAXSTRING, fmtString, args );
+ va_end( args );
+
+ fprintf(stderr, "Mesa %s implementation error: %s\n", MESA_VERSION_STRING, str);
+ fprintf(stderr, "Please report at bugs.freedesktop.org\n");
+}
+
+
+/**
+ * Record an OpenGL state error. These usually occur when the user
+ * passes invalid parameters to a GL function.
+ *
+ * If debugging is enabled (either at compile-time via the DEBUG macro, or
+ * run-time via the MESA_DEBUG environment variable), report the error with
+ * _mesa_debug().
+ *
+ * \param ctx the GL context.
+ * \param error the error value.
+ * \param fmtString printf() style format string, followed by optional args
+ */
+void
+_mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... )
+{
+ static GLint debug = -1;
+
+ /* Check debug environment variable only once:
+ */
+ if (debug == -1) {
+ const char *debugEnv = _mesa_getenv("MESA_DEBUG");
+
+#ifdef DEBUG
+ if (debugEnv && strstr(debugEnv, "silent"))
+ debug = GL_FALSE;
+ else
+ debug = GL_TRUE;
+#else
+ if (debugEnv)
+ debug = GL_TRUE;
+ else
+ debug = GL_FALSE;
+#endif
+ }
+
+ if (debug) {
+ if (ctx->ErrorValue == error &&
+ ctx->ErrorDebugFmtString == fmtString) {
+ ctx->ErrorDebugCount++;
+ }
+ else {
+ char s[MAXSTRING], s2[MAXSTRING];
+ va_list args;
+
+ flush_delayed_errors( ctx );
+
+ va_start(args, fmtString);
+ vsnprintf(s, MAXSTRING, fmtString, args);
+ va_end(args);
+
+ _mesa_snprintf(s2, MAXSTRING, "%s in %s", error_string(error), s);
+ output_if_debug("Mesa: User error", s2, GL_TRUE);
+
+ ctx->ErrorDebugFmtString = fmtString;
+ ctx->ErrorDebugCount = 0;
+ }
+ }
+
+ _mesa_record_error(ctx, error);
+}
+
+
+/**
+ * Report debug information. Print error message to stderr via fprintf().
+ * No-op if DEBUG mode not enabled.
+ *
+ * \param ctx GL context.
+ * \param fmtString printf()-style format string, followed by optional args.
+ */
+void
+_mesa_debug( const struct gl_context *ctx, const char *fmtString, ... )
+{
+#ifdef DEBUG
+ char s[MAXSTRING];
+ va_list args;
+ va_start(args, fmtString);
+ vsnprintf(s, MAXSTRING, fmtString, args);
+ va_end(args);
+ output_if_debug("Mesa", s, GL_FALSE);
+#endif /* DEBUG */
+ (void) ctx;
+ (void) fmtString;
+}
+
+/*@}*/
diff --git a/mesalib/src/mesa/main/imports.h b/mesalib/src/mesa/main/imports.h
index ce7baabe2..315c4119d 100644
--- a/mesalib/src/mesa/main/imports.h
+++ b/mesalib/src/mesa/main/imports.h
@@ -1,621 +1,621 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.5
- *
- * Copyright (C) 1999-2008 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 imports.h
- * Standard C library function wrappers.
- *
- * This file provides wrappers for all the standard C library functions
- * like malloc(), free(), printf(), getenv(), etc.
- */
-
-
-#ifndef IMPORTS_H
-#define IMPORTS_H
-
-
-#include "compiler.h"
-#include "glheader.h"
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/**********************************************************************/
-/** Memory macros */
-/*@{*/
-
-/** Allocate \p BYTES bytes */
-#define MALLOC(BYTES) malloc(BYTES)
-/** Allocate and zero \p BYTES bytes */
-#define CALLOC(BYTES) calloc(1, BYTES)
-/** Allocate a structure of type \p T */
-#define MALLOC_STRUCT(T) (struct T *) malloc(sizeof(struct T))
-/** Allocate and zero a structure of type \p T */
-#define CALLOC_STRUCT(T) (struct T *) calloc(1, sizeof(struct T))
-/** Free memory */
-#define FREE(PTR) free(PTR)
-
-/*@}*/
-
-
-/*
- * For GL_ARB_vertex_buffer_object we need to treat vertex array pointers
- * as offsets into buffer stores. Since the vertex array pointer and
- * buffer store pointer are both pointers and we need to add them, we use
- * this macro.
- * Both pointers/offsets are expressed in bytes.
- */
-#define ADD_POINTERS(A, B) ( (GLubyte *) (A) + (uintptr_t) (B) )
-
-
-/**
- * Sometimes we treat GLfloats as GLints. On x86 systems, moving a float
- * as a int (thereby using integer registers instead of FP registers) is
- * a performance win. Typically, this can be done with ordinary casts.
- * But with gcc's -fstrict-aliasing flag (which defaults to on in gcc 3.0)
- * these casts generate warnings.
- * The following union typedef is used to solve that.
- */
-typedef union { GLfloat f; GLint i; } fi_type;
-
-
-
-/**********************************************************************
- * Math macros
- */
-
-#define MAX_GLUSHORT 0xffff
-#define MAX_GLUINT 0xffffffff
-
-/* Degrees to radians conversion: */
-#define DEG2RAD (M_PI/180.0)
-
-
-/***
- *** SQRTF: single-precision square root
- ***/
-#if 0 /* _mesa_sqrtf() not accurate enough - temporarily disabled */
-# define SQRTF(X) _mesa_sqrtf(X)
-#else
-# define SQRTF(X) (float) sqrt((float) (X))
-#endif
-
-
-/***
- *** INV_SQRTF: single-precision inverse square root
- ***/
-#if 0
-#define INV_SQRTF(X) _mesa_inv_sqrt(X)
-#else
-#define INV_SQRTF(X) (1.0F / SQRTF(X)) /* this is faster on a P4 */
-#endif
-
-
-/**
- * \name Work-arounds for platforms that lack C99 math functions
- */
-/*@{*/
-#if (!defined(_XOPEN_SOURCE) || (_XOPEN_SOURCE < 600)) && !defined(_ISOC99_SOURCE) \
- && (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)) \
- && (!defined(_MSC_VER) || (_MSC_VER < 1400))
-#define acosf(f) ((float) acos(f))
-#define asinf(f) ((float) asin(f))
-#define atan2f(x,y) ((float) atan2(x,y))
-#define atanf(f) ((float) atan(f))
-#define cielf(f) ((float) ciel(f))
-#define cosf(f) ((float) cos(f))
-#define coshf(f) ((float) cosh(f))
-#define expf(f) ((float) exp(f))
-#define exp2f(f) ((float) exp2(f))
-#define floorf(f) ((float) floor(f))
-#define logf(f) ((float) log(f))
-#define log2f(f) ((float) log2(f))
-#define powf(x,y) ((float) pow(x,y))
-#define sinf(f) ((float) sin(f))
-#define sinhf(f) ((float) sinh(f))
-#define sqrtf(f) ((float) sqrt(f))
-#define tanf(f) ((float) tan(f))
-#define tanhf(f) ((float) tanh(f))
-#define acoshf(f) ((float) acosh(f))
-#define asinhf(f) ((float) asinh(f))
-#define atanhf(f) ((float) atanh(f))
-#endif
-
-#if defined(_MSC_VER)
-static INLINE float truncf(float x) { return x < 0.0f ? ceilf(x) : floorf(x); }
-static INLINE float exp2f(float x) { return powf(2.0f, x); }
-static INLINE float log2f(float x) { return logf(x) * 1.442695041f; }
-static INLINE float asinhf(float x) { return logf(x + sqrtf(x * x + 1.0f)); }
-static INLINE float acoshf(float x) { return logf(x + sqrtf(x * x - 1.0f)); }
-static INLINE float atanhf(float x) { return (logf(1.0f + x) - logf(1.0f - x)) / 2.0f; }
-static INLINE int isblank(int ch) { return ch == ' ' || ch == '\t'; }
-#define strtoll(p, e, b) _strtoi64(p, e, b)
-#endif
-/*@}*/
-
-/***
- *** LOG2: Log base 2 of float
- ***/
-#ifdef USE_IEEE
-#if 0
-/* This is pretty fast, but not accurate enough (only 2 fractional bits).
- * Based on code from http://www.stereopsis.com/log2.html
- */
-static INLINE GLfloat LOG2(GLfloat x)
-{
- const GLfloat y = x * x * x * x;
- const GLuint ix = *((GLuint *) &y);
- const GLuint exp = (ix >> 23) & 0xFF;
- const GLint log2 = ((GLint) exp) - 127;
- return (GLfloat) log2 * (1.0 / 4.0); /* 4, because of x^4 above */
-}
-#endif
-/* Pretty fast, and accurate.
- * Based on code from http://www.flipcode.com/totd/
- */
-static INLINE GLfloat LOG2(GLfloat val)
-{
- fi_type num;
- GLint log_2;
- num.f = val;
- log_2 = ((num.i >> 23) & 255) - 128;
- num.i &= ~(255 << 23);
- num.i += 127 << 23;
- num.f = ((-1.0f/3) * num.f + 2) * num.f - 2.0f/3;
- return num.f + log_2;
-}
-#else
-/*
- * NOTE: log_base_2(x) = log(x) / log(2)
- * NOTE: 1.442695 = 1/log(2).
- */
-#define LOG2(x) ((GLfloat) (log(x) * 1.442695F))
-#endif
-
-
-/***
- *** IS_INF_OR_NAN: test if float is infinite or NaN
- ***/
-#ifdef USE_IEEE
-static INLINE int IS_INF_OR_NAN( float x )
-{
- fi_type tmp;
- tmp.f = x;
- return !(int)((unsigned int)((tmp.i & 0x7fffffff)-0x7f800000) >> 31);
-}
-#elif defined(isfinite)
-#define IS_INF_OR_NAN(x) (!isfinite(x))
-#elif defined(finite)
-#define IS_INF_OR_NAN(x) (!finite(x))
-#elif defined(__VMS)
-#define IS_INF_OR_NAN(x) (!finite(x))
-#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
-#define IS_INF_OR_NAN(x) (!isfinite(x))
-#else
-#define IS_INF_OR_NAN(x) (!finite(x))
-#endif
-
-
-/***
- *** IS_NEGATIVE: test if float is negative
- ***/
-#if defined(USE_IEEE)
-static INLINE int GET_FLOAT_BITS( float x )
-{
- fi_type fi;
- fi.f = x;
- return fi.i;
-}
-#define IS_NEGATIVE(x) (GET_FLOAT_BITS(x) < 0)
-#else
-#define IS_NEGATIVE(x) (x < 0.0F)
-#endif
-
-
-/***
- *** DIFFERENT_SIGNS: test if two floats have opposite signs
- ***/
-#if defined(USE_IEEE)
-#define DIFFERENT_SIGNS(x,y) ((GET_FLOAT_BITS(x) ^ GET_FLOAT_BITS(y)) & (1<<31))
-#else
-/* Could just use (x*y<0) except for the flatshading requirements.
- * Maybe there's a better way?
- */
-#define DIFFERENT_SIGNS(x,y) ((x) * (y) <= 0.0F && (x) - (y) != 0.0F)
-#endif
-
-
-/***
- *** CEILF: ceiling of float
- *** FLOORF: floor of float
- *** FABSF: absolute value of float
- *** LOGF: the natural logarithm (base e) of the value
- *** EXPF: raise e to the value
- *** LDEXPF: multiply value by an integral power of two
- *** FREXPF: extract mantissa and exponent from value
- ***/
-#if defined(__gnu_linux__)
-/* C99 functions */
-#define CEILF(x) ceilf(x)
-#define FLOORF(x) floorf(x)
-#define FABSF(x) fabsf(x)
-#define LOGF(x) logf(x)
-#define EXPF(x) expf(x)
-#define LDEXPF(x,y) ldexpf(x,y)
-#define FREXPF(x,y) frexpf(x,y)
-#else
-#define CEILF(x) ((GLfloat) ceil(x))
-#define FLOORF(x) ((GLfloat) floor(x))
-#define FABSF(x) ((GLfloat) fabs(x))
-#define LOGF(x) ((GLfloat) log(x))
-#define EXPF(x) ((GLfloat) exp(x))
-#define LDEXPF(x,y) ((GLfloat) ldexp(x,y))
-#define FREXPF(x,y) ((GLfloat) frexp(x,y))
-#endif
-
-
-/***
- *** IROUND: return (as an integer) float rounded to nearest integer
- ***/
-#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
-static INLINE int iround(float f)
-{
- int r;
- __asm__ ("fistpl %0" : "=m" (r) : "t" (f) : "st");
- return r;
-}
-#define IROUND(x) iround(x)
-#elif defined(USE_X86_ASM) && defined(_MSC_VER)
-static INLINE int iround(float f)
-{
- int r;
- _asm {
- fld f
- fistp r
- }
- return r;
-}
-#define IROUND(x) iround(x)
-#elif defined(__WATCOMC__) && defined(__386__)
-long iround(float f);
-#pragma aux iround = \
- "push eax" \
- "fistp dword ptr [esp]" \
- "pop eax" \
- parm [8087] \
- value [eax] \
- modify exact [eax];
-#define IROUND(x) iround(x)
-#else
-#define IROUND(f) ((int) (((f) >= 0.0F) ? ((f) + 0.5F) : ((f) - 0.5F)))
-#endif
-
-#define IROUND64(f) ((GLint64) (((f) >= 0.0F) ? ((f) + 0.5F) : ((f) - 0.5F)))
-
-/***
- *** IROUND_POS: return (as an integer) positive float rounded to nearest int
- ***/
-#ifdef DEBUG
-#define IROUND_POS(f) (assert((f) >= 0.0F), IROUND(f))
-#else
-#define IROUND_POS(f) (IROUND(f))
-#endif
-
-
-/***
- *** IFLOOR: return (as an integer) floor of float
- ***/
-#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
-/*
- * IEEE floor for computers that round to nearest or even.
- * 'f' must be between -4194304 and 4194303.
- * This floor operation is done by "(iround(f + .5) + iround(f - .5)) >> 1",
- * but uses some IEEE specific tricks for better speed.
- * Contributed by Josh Vanderhoof
- */
-static INLINE int ifloor(float f)
-{
- int ai, bi;
- double af, bf;
- af = (3 << 22) + 0.5 + (double)f;
- bf = (3 << 22) + 0.5 - (double)f;
- /* GCC generates an extra fstp/fld without this. */
- __asm__ ("fstps %0" : "=m" (ai) : "t" (af) : "st");
- __asm__ ("fstps %0" : "=m" (bi) : "t" (bf) : "st");
- return (ai - bi) >> 1;
-}
-#define IFLOOR(x) ifloor(x)
-#elif defined(USE_IEEE)
-static INLINE int ifloor(float f)
-{
- int ai, bi;
- double af, bf;
- fi_type u;
-
- af = (3 << 22) + 0.5 + (double)f;
- bf = (3 << 22) + 0.5 - (double)f;
- u.f = (float) af; ai = u.i;
- u.f = (float) bf; bi = u.i;
- return (ai - bi) >> 1;
-}
-#define IFLOOR(x) ifloor(x)
-#else
-static INLINE int ifloor(float f)
-{
- int i = IROUND(f);
- return (i > f) ? i - 1 : i;
-}
-#define IFLOOR(x) ifloor(x)
-#endif
-
-
-/***
- *** ICEIL: return (as an integer) ceiling of float
- ***/
-#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
-/*
- * IEEE ceil for computers that round to nearest or even.
- * 'f' must be between -4194304 and 4194303.
- * This ceil operation is done by "(iround(f + .5) + iround(f - .5) + 1) >> 1",
- * but uses some IEEE specific tricks for better speed.
- * Contributed by Josh Vanderhoof
- */
-static INLINE int iceil(float f)
-{
- int ai, bi;
- double af, bf;
- af = (3 << 22) + 0.5 + (double)f;
- bf = (3 << 22) + 0.5 - (double)f;
- /* GCC generates an extra fstp/fld without this. */
- __asm__ ("fstps %0" : "=m" (ai) : "t" (af) : "st");
- __asm__ ("fstps %0" : "=m" (bi) : "t" (bf) : "st");
- return (ai - bi + 1) >> 1;
-}
-#define ICEIL(x) iceil(x)
-#elif defined(USE_IEEE)
-static INLINE int iceil(float f)
-{
- int ai, bi;
- double af, bf;
- fi_type u;
- af = (3 << 22) + 0.5 + (double)f;
- bf = (3 << 22) + 0.5 - (double)f;
- u.f = (float) af; ai = u.i;
- u.f = (float) bf; bi = u.i;
- return (ai - bi + 1) >> 1;
-}
-#define ICEIL(x) iceil(x)
-#else
-static INLINE int iceil(float f)
-{
- int i = IROUND(f);
- return (i < f) ? i + 1 : i;
-}
-#define ICEIL(x) iceil(x)
-#endif
-
-
-/**
- * Is x a power of two?
- */
-static INLINE int
-_mesa_is_pow_two(int x)
-{
- return !(x & (x - 1));
-}
-
-/**
- * Round given integer to next higer power of two
- * If X is zero result is undefined.
- *
- * Source for the fallback implementation is
- * Sean Eron Anderson's webpage "Bit Twiddling Hacks"
- * http://graphics.stanford.edu/~seander/bithacks.html
- *
- * When using builtin function have to do some work
- * for case when passed values 1 to prevent hiting
- * undefined result from __builtin_clz. Undefined
- * results would be different depending on optimization
- * level used for build.
- */
-static INLINE int32_t
-_mesa_next_pow_two_32(uint32_t x)
-{
-#if defined(__GNUC__) && \
- ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
- uint32_t y = (x != 1);
- return (1 + y) << ((__builtin_clz(x - y) ^ 31) );
-#else
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x++;
- return x;
-#endif
-}
-
-static INLINE int64_t
-_mesa_next_pow_two_64(uint64_t x)
-{
-#if defined(__GNUC__) && \
- ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
- uint64_t y = (x != 1);
- if (sizeof(x) == sizeof(long))
- return (1 + y) << ((__builtin_clzl(x - y) ^ 63));
- else
- return (1 + y) << ((__builtin_clzll(x - y) ^ 63));
-#else
- x--;
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- x |= x >> 32;
- x++;
- return x;
-#endif
-}
-
-
-/**
- * Return 1 if this is a little endian machine, 0 if big endian.
- */
-static INLINE GLboolean
-_mesa_little_endian(void)
-{
- const GLuint ui = 1; /* intentionally not static */
- return *((const GLubyte *) &ui);
-}
-
-
-
-/**********************************************************************
- * Functions
- */
-
-extern void *
-_mesa_align_malloc( size_t bytes, unsigned long alignment );
-
-extern void *
-_mesa_align_calloc( size_t bytes, unsigned long alignment );
-
-extern void
-_mesa_align_free( void *ptr );
-
-extern void *
-_mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
- unsigned long alignment);
-
-extern void *
-_mesa_exec_malloc( GLuint size );
-
-extern void
-_mesa_exec_free( void *addr );
-
-extern void *
-_mesa_realloc( void *oldBuffer, size_t oldSize, size_t newSize );
-
-extern void
-_mesa_memset16( unsigned short *dst, unsigned short val, size_t n );
-
-extern double
-_mesa_sqrtd(double x);
-
-extern float
-_mesa_sqrtf(float x);
-
-extern float
-_mesa_inv_sqrtf(float x);
-
-extern void
-_mesa_init_sqrt_table(void);
-
-#ifdef __GNUC__
-
-#ifdef __MINGW32__
-#define ffs __builtin_ffs
-#define ffsll __builtin_ffsll
-#endif
-
-#define _mesa_ffs(i) ffs(i)
-#define _mesa_ffsll(i) ffsll(i)
-
-#if ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
-#define _mesa_bitcount(i) __builtin_popcount(i)
-#else
-extern unsigned int
-_mesa_bitcount(unsigned int n);
-#endif
-
-#else
-extern int
-_mesa_ffs(int32_t i);
-
-extern int
-_mesa_ffsll(int64_t i);
-
-extern unsigned int
-_mesa_bitcount(unsigned int n);
-#endif
-
-extern GLhalfARB
-_mesa_float_to_half(float f);
-
-extern float
-_mesa_half_to_float(GLhalfARB h);
-
-
-extern void *
-_mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
- int (*compar)(const void *, const void *) );
-
-extern char *
-_mesa_getenv( const char *var );
-
-extern char *
-_mesa_strdup( const char *s );
-
-extern float
-_mesa_strtof( const char *s, char **end );
-
-extern unsigned int
-_mesa_str_checksum(const char *str);
-
-extern int
-_mesa_snprintf( char *str, size_t size, const char *fmt, ... ) PRINTFLIKE(3, 4);
-
-struct gl_context;
-
-extern void
-_mesa_warning( struct gl_context *gc, const char *fmtString, ... ) PRINTFLIKE(2, 3);
-
-extern void
-_mesa_problem( const struct gl_context *ctx, const char *fmtString, ... ) PRINTFLIKE(2, 3);
-
-extern void
-_mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... ) PRINTFLIKE(3, 4);
-
-extern void
-_mesa_debug( const struct gl_context *ctx, const char *fmtString, ... ) PRINTFLIKE(2, 3);
-
-
-#if defined(_MSC_VER) && !defined(snprintf)
-#define snprintf _snprintf
-#endif
-
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif /* IMPORTS_H */
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.5
+ *
+ * Copyright (C) 1999-2008 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 imports.h
+ * Standard C library function wrappers.
+ *
+ * This file provides wrappers for all the standard C library functions
+ * like malloc(), free(), printf(), getenv(), etc.
+ */
+
+
+#ifndef IMPORTS_H
+#define IMPORTS_H
+
+
+#include "compiler.h"
+#include "glheader.h"
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**********************************************************************/
+/** Memory macros */
+/*@{*/
+
+/** Allocate \p BYTES bytes */
+#define MALLOC(BYTES) malloc(BYTES)
+/** Allocate and zero \p BYTES bytes */
+#define CALLOC(BYTES) calloc(1, BYTES)
+/** Allocate a structure of type \p T */
+#define MALLOC_STRUCT(T) (struct T *) malloc(sizeof(struct T))
+/** Allocate and zero a structure of type \p T */
+#define CALLOC_STRUCT(T) (struct T *) calloc(1, sizeof(struct T))
+/** Free memory */
+#define FREE(PTR) free(PTR)
+
+/*@}*/
+
+
+/*
+ * For GL_ARB_vertex_buffer_object we need to treat vertex array pointers
+ * as offsets into buffer stores. Since the vertex array pointer and
+ * buffer store pointer are both pointers and we need to add them, we use
+ * this macro.
+ * Both pointers/offsets are expressed in bytes.
+ */
+#define ADD_POINTERS(A, B) ( (GLubyte *) (A) + (uintptr_t) (B) )
+
+
+/**
+ * Sometimes we treat GLfloats as GLints. On x86 systems, moving a float
+ * as a int (thereby using integer registers instead of FP registers) is
+ * a performance win. Typically, this can be done with ordinary casts.
+ * But with gcc's -fstrict-aliasing flag (which defaults to on in gcc 3.0)
+ * these casts generate warnings.
+ * The following union typedef is used to solve that.
+ */
+typedef union { GLfloat f; GLint i; } fi_type;
+
+
+
+/**********************************************************************
+ * Math macros
+ */
+
+#define MAX_GLUSHORT 0xffff
+#define MAX_GLUINT 0xffffffff
+
+/* Degrees to radians conversion: */
+#define DEG2RAD (M_PI/180.0)
+
+
+/***
+ *** SQRTF: single-precision square root
+ ***/
+#if 0 /* _mesa_sqrtf() not accurate enough - temporarily disabled */
+# define SQRTF(X) _mesa_sqrtf(X)
+#else
+# define SQRTF(X) (float) sqrt((float) (X))
+#endif
+
+
+/***
+ *** INV_SQRTF: single-precision inverse square root
+ ***/
+#if 0
+#define INV_SQRTF(X) _mesa_inv_sqrt(X)
+#else
+#define INV_SQRTF(X) (1.0F / SQRTF(X)) /* this is faster on a P4 */
+#endif
+
+
+/**
+ * \name Work-arounds for platforms that lack C99 math functions
+ */
+/*@{*/
+#if (!defined(_XOPEN_SOURCE) || (_XOPEN_SOURCE < 600)) && !defined(_ISOC99_SOURCE) \
+ && (!defined(__STDC_VERSION__) || (__STDC_VERSION__ < 199901L)) \
+ && (!defined(_MSC_VER) || (_MSC_VER < 1400))
+#define acosf(f) ((float) acos(f))
+#define asinf(f) ((float) asin(f))
+#define atan2f(x,y) ((float) atan2(x,y))
+#define atanf(f) ((float) atan(f))
+#define cielf(f) ((float) ciel(f))
+#define cosf(f) ((float) cos(f))
+#define coshf(f) ((float) cosh(f))
+#define expf(f) ((float) exp(f))
+#define exp2f(f) ((float) exp2(f))
+#define floorf(f) ((float) floor(f))
+#define logf(f) ((float) log(f))
+#define log2f(f) ((float) log2(f))
+#define powf(x,y) ((float) pow(x,y))
+#define sinf(f) ((float) sin(f))
+#define sinhf(f) ((float) sinh(f))
+#define sqrtf(f) ((float) sqrt(f))
+#define tanf(f) ((float) tan(f))
+#define tanhf(f) ((float) tanh(f))
+#define acoshf(f) ((float) acosh(f))
+#define asinhf(f) ((float) asinh(f))
+#define atanhf(f) ((float) atanh(f))
+#endif
+
+#if defined(_MSC_VER)
+static INLINE float truncf(float x) { return x < 0.0f ? ceilf(x) : floorf(x); }
+static INLINE float exp2f(float x) { return powf(2.0f, x); }
+static INLINE float log2f(float x) { return logf(x) * 1.442695041f; }
+static INLINE float asinhf(float x) { return logf(x + sqrtf(x * x + 1.0f)); }
+static INLINE float acoshf(float x) { return logf(x + sqrtf(x * x - 1.0f)); }
+static INLINE float atanhf(float x) { return (logf(1.0f + x) - logf(1.0f - x)) / 2.0f; }
+static INLINE int isblank(int ch) { return ch == ' ' || ch == '\t'; }
+#define strtoll(p, e, b) _strtoi64(p, e, b)
+#endif
+/*@}*/
+
+/***
+ *** LOG2: Log base 2 of float
+ ***/
+#ifdef USE_IEEE
+#if 0
+/* This is pretty fast, but not accurate enough (only 2 fractional bits).
+ * Based on code from http://www.stereopsis.com/log2.html
+ */
+static INLINE GLfloat LOG2(GLfloat x)
+{
+ const GLfloat y = x * x * x * x;
+ const GLuint ix = *((GLuint *) &y);
+ const GLuint exp = (ix >> 23) & 0xFF;
+ const GLint log2 = ((GLint) exp) - 127;
+ return (GLfloat) log2 * (1.0 / 4.0); /* 4, because of x^4 above */
+}
+#endif
+/* Pretty fast, and accurate.
+ * Based on code from http://www.flipcode.com/totd/
+ */
+static INLINE GLfloat LOG2(GLfloat val)
+{
+ fi_type num;
+ GLint log_2;
+ num.f = val;
+ log_2 = ((num.i >> 23) & 255) - 128;
+ num.i &= ~(255 << 23);
+ num.i += 127 << 23;
+ num.f = ((-1.0f/3) * num.f + 2) * num.f - 2.0f/3;
+ return num.f + log_2;
+}
+#else
+/*
+ * NOTE: log_base_2(x) = log(x) / log(2)
+ * NOTE: 1.442695 = 1/log(2).
+ */
+#define LOG2(x) ((GLfloat) (log(x) * 1.442695F))
+#endif
+
+
+/***
+ *** IS_INF_OR_NAN: test if float is infinite or NaN
+ ***/
+#ifdef USE_IEEE
+static INLINE int IS_INF_OR_NAN( float x )
+{
+ fi_type tmp;
+ tmp.f = x;
+ return !(int)((unsigned int)((tmp.i & 0x7fffffff)-0x7f800000) >> 31);
+}
+#elif defined(isfinite)
+#define IS_INF_OR_NAN(x) (!isfinite(x))
+#elif defined(finite)
+#define IS_INF_OR_NAN(x) (!finite(x))
+#elif defined(__VMS)
+#define IS_INF_OR_NAN(x) (!finite(x))
+#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#define IS_INF_OR_NAN(x) (!isfinite(x))
+#else
+#define IS_INF_OR_NAN(x) (!finite(x))
+#endif
+
+
+/***
+ *** IS_NEGATIVE: test if float is negative
+ ***/
+#if defined(USE_IEEE)
+static INLINE int GET_FLOAT_BITS( float x )
+{
+ fi_type fi;
+ fi.f = x;
+ return fi.i;
+}
+#define IS_NEGATIVE(x) (GET_FLOAT_BITS(x) < 0)
+#else
+#define IS_NEGATIVE(x) (x < 0.0F)
+#endif
+
+
+/***
+ *** DIFFERENT_SIGNS: test if two floats have opposite signs
+ ***/
+#if defined(USE_IEEE)
+#define DIFFERENT_SIGNS(x,y) ((GET_FLOAT_BITS(x) ^ GET_FLOAT_BITS(y)) & (1<<31))
+#else
+/* Could just use (x*y<0) except for the flatshading requirements.
+ * Maybe there's a better way?
+ */
+#define DIFFERENT_SIGNS(x,y) ((x) * (y) <= 0.0F && (x) - (y) != 0.0F)
+#endif
+
+
+/***
+ *** CEILF: ceiling of float
+ *** FLOORF: floor of float
+ *** FABSF: absolute value of float
+ *** LOGF: the natural logarithm (base e) of the value
+ *** EXPF: raise e to the value
+ *** LDEXPF: multiply value by an integral power of two
+ *** FREXPF: extract mantissa and exponent from value
+ ***/
+#if defined(__gnu_linux__)
+/* C99 functions */
+#define CEILF(x) ceilf(x)
+#define FLOORF(x) floorf(x)
+#define FABSF(x) fabsf(x)
+#define LOGF(x) logf(x)
+#define EXPF(x) expf(x)
+#define LDEXPF(x,y) ldexpf(x,y)
+#define FREXPF(x,y) frexpf(x,y)
+#else
+#define CEILF(x) ((GLfloat) ceil(x))
+#define FLOORF(x) ((GLfloat) floor(x))
+#define FABSF(x) ((GLfloat) fabs(x))
+#define LOGF(x) ((GLfloat) log(x))
+#define EXPF(x) ((GLfloat) exp(x))
+#define LDEXPF(x,y) ((GLfloat) ldexp(x,y))
+#define FREXPF(x,y) ((GLfloat) frexp(x,y))
+#endif
+
+
+/***
+ *** IROUND: return (as an integer) float rounded to nearest integer
+ ***/
+#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
+static INLINE int iround(float f)
+{
+ int r;
+ __asm__ ("fistpl %0" : "=m" (r) : "t" (f) : "st");
+ return r;
+}
+#define IROUND(x) iround(x)
+#elif defined(USE_X86_ASM) && defined(_MSC_VER)
+static INLINE int iround(float f)
+{
+ int r;
+ _asm {
+ fld f
+ fistp r
+ }
+ return r;
+}
+#define IROUND(x) iround(x)
+#elif defined(__WATCOMC__) && defined(__386__)
+long iround(float f);
+#pragma aux iround = \
+ "push eax" \
+ "fistp dword ptr [esp]" \
+ "pop eax" \
+ parm [8087] \
+ value [eax] \
+ modify exact [eax];
+#define IROUND(x) iround(x)
+#else
+#define IROUND(f) ((int) (((f) >= 0.0F) ? ((f) + 0.5F) : ((f) - 0.5F)))
+#endif
+
+#define IROUND64(f) ((GLint64) (((f) >= 0.0F) ? ((f) + 0.5F) : ((f) - 0.5F)))
+
+/***
+ *** IROUND_POS: return (as an integer) positive float rounded to nearest int
+ ***/
+#ifdef DEBUG
+#define IROUND_POS(f) (assert((f) >= 0.0F), IROUND(f))
+#else
+#define IROUND_POS(f) (IROUND(f))
+#endif
+
+
+/***
+ *** IFLOOR: return (as an integer) floor of float
+ ***/
+#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
+/*
+ * IEEE floor for computers that round to nearest or even.
+ * 'f' must be between -4194304 and 4194303.
+ * This floor operation is done by "(iround(f + .5) + iround(f - .5)) >> 1",
+ * but uses some IEEE specific tricks for better speed.
+ * Contributed by Josh Vanderhoof
+ */
+static INLINE int ifloor(float f)
+{
+ int ai, bi;
+ double af, bf;
+ af = (3 << 22) + 0.5 + (double)f;
+ bf = (3 << 22) + 0.5 - (double)f;
+ /* GCC generates an extra fstp/fld without this. */
+ __asm__ ("fstps %0" : "=m" (ai) : "t" (af) : "st");
+ __asm__ ("fstps %0" : "=m" (bi) : "t" (bf) : "st");
+ return (ai - bi) >> 1;
+}
+#define IFLOOR(x) ifloor(x)
+#elif defined(USE_IEEE)
+static INLINE int ifloor(float f)
+{
+ int ai, bi;
+ double af, bf;
+ fi_type u;
+
+ af = (3 << 22) + 0.5 + (double)f;
+ bf = (3 << 22) + 0.5 - (double)f;
+ u.f = (float) af; ai = u.i;
+ u.f = (float) bf; bi = u.i;
+ return (ai - bi) >> 1;
+}
+#define IFLOOR(x) ifloor(x)
+#else
+static INLINE int ifloor(float f)
+{
+ int i = IROUND(f);
+ return (i > f) ? i - 1 : i;
+}
+#define IFLOOR(x) ifloor(x)
+#endif
+
+
+/***
+ *** ICEIL: return (as an integer) ceiling of float
+ ***/
+#if defined(USE_X86_ASM) && defined(__GNUC__) && defined(__i386__)
+/*
+ * IEEE ceil for computers that round to nearest or even.
+ * 'f' must be between -4194304 and 4194303.
+ * This ceil operation is done by "(iround(f + .5) + iround(f - .5) + 1) >> 1",
+ * but uses some IEEE specific tricks for better speed.
+ * Contributed by Josh Vanderhoof
+ */
+static INLINE int iceil(float f)
+{
+ int ai, bi;
+ double af, bf;
+ af = (3 << 22) + 0.5 + (double)f;
+ bf = (3 << 22) + 0.5 - (double)f;
+ /* GCC generates an extra fstp/fld without this. */
+ __asm__ ("fstps %0" : "=m" (ai) : "t" (af) : "st");
+ __asm__ ("fstps %0" : "=m" (bi) : "t" (bf) : "st");
+ return (ai - bi + 1) >> 1;
+}
+#define ICEIL(x) iceil(x)
+#elif defined(USE_IEEE)
+static INLINE int iceil(float f)
+{
+ int ai, bi;
+ double af, bf;
+ fi_type u;
+ af = (3 << 22) + 0.5 + (double)f;
+ bf = (3 << 22) + 0.5 - (double)f;
+ u.f = (float) af; ai = u.i;
+ u.f = (float) bf; bi = u.i;
+ return (ai - bi + 1) >> 1;
+}
+#define ICEIL(x) iceil(x)
+#else
+static INLINE int iceil(float f)
+{
+ int i = IROUND(f);
+ return (i < f) ? i + 1 : i;
+}
+#define ICEIL(x) iceil(x)
+#endif
+
+
+/**
+ * Is x a power of two?
+ */
+static INLINE int
+_mesa_is_pow_two(int x)
+{
+ return !(x & (x - 1));
+}
+
+/**
+ * Round given integer to next higer power of two
+ * If X is zero result is undefined.
+ *
+ * Source for the fallback implementation is
+ * Sean Eron Anderson's webpage "Bit Twiddling Hacks"
+ * http://graphics.stanford.edu/~seander/bithacks.html
+ *
+ * When using builtin function have to do some work
+ * for case when passed values 1 to prevent hiting
+ * undefined result from __builtin_clz. Undefined
+ * results would be different depending on optimization
+ * level used for build.
+ */
+static INLINE int32_t
+_mesa_next_pow_two_32(uint32_t x)
+{
+#if defined(__GNUC__) && \
+ ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
+ uint32_t y = (x != 1);
+ return (1 + y) << ((__builtin_clz(x - y) ^ 31) );
+#else
+ x--;
+ x |= x >> 1;
+ x |= x >> 2;
+ x |= x >> 4;
+ x |= x >> 8;
+ x |= x >> 16;
+ x++;
+ return x;
+#endif
+}
+
+static INLINE int64_t
+_mesa_next_pow_two_64(uint64_t x)
+{
+#if defined(__GNUC__) && \
+ ((__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
+ uint64_t y = (x != 1);
+ if (sizeof(x) == sizeof(long))
+ return (1 + y) << ((__builtin_clzl(x - y) ^ 63));
+ else
+ return (1 + y) << ((__builtin_clzll(x - y) ^ 63));
+#else
+ x--;
+ x |= x >> 1;
+ x |= x >> 2;
+ x |= x >> 4;
+ x |= x >> 8;
+ x |= x >> 16;
+ x |= x >> 32;
+ x++;
+ return x;
+#endif
+}
+
+
+/**
+ * Return 1 if this is a little endian machine, 0 if big endian.
+ */
+static INLINE GLboolean
+_mesa_little_endian(void)
+{
+ const GLuint ui = 1; /* intentionally not static */
+ return *((const GLubyte *) &ui);
+}
+
+
+
+/**********************************************************************
+ * Functions
+ */
+
+extern void *
+_mesa_align_malloc( size_t bytes, unsigned long alignment );
+
+extern void *
+_mesa_align_calloc( size_t bytes, unsigned long alignment );
+
+extern void
+_mesa_align_free( void *ptr );
+
+extern void *
+_mesa_align_realloc(void *oldBuffer, size_t oldSize, size_t newSize,
+ unsigned long alignment);
+
+extern void *
+_mesa_exec_malloc( GLuint size );
+
+extern void
+_mesa_exec_free( void *addr );
+
+extern void *
+_mesa_realloc( void *oldBuffer, size_t oldSize, size_t newSize );
+
+extern void
+_mesa_memset16( unsigned short *dst, unsigned short val, size_t n );
+
+extern double
+_mesa_sqrtd(double x);
+
+extern float
+_mesa_sqrtf(float x);
+
+extern float
+_mesa_inv_sqrtf(float x);
+
+extern void
+_mesa_init_sqrt_table(void);
+
+#ifdef __GNUC__
+
+#ifdef __MINGW32__
+#define ffs __builtin_ffs
+#define ffsll __builtin_ffsll
+#endif
+
+#define _mesa_ffs(i) ffs(i)
+#define _mesa_ffsll(i) ffsll(i)
+
+#if ((_GNUC__ == 3 && __GNUC_MINOR__ >= 4) || __GNUC__ >= 4)
+#define _mesa_bitcount(i) __builtin_popcount(i)
+#else
+extern unsigned int
+_mesa_bitcount(unsigned int n);
+#endif
+
+#else
+extern int
+_mesa_ffs(int32_t i);
+
+extern int
+_mesa_ffsll(int64_t i);
+
+extern unsigned int
+_mesa_bitcount(unsigned int n);
+#endif
+
+extern GLhalfARB
+_mesa_float_to_half(float f);
+
+extern float
+_mesa_half_to_float(GLhalfARB h);
+
+
+extern void *
+_mesa_bsearch( const void *key, const void *base, size_t nmemb, size_t size,
+ int (*compar)(const void *, const void *) );
+
+extern char *
+_mesa_getenv( const char *var );
+
+extern char *
+_mesa_strdup( const char *s );
+
+extern float
+_mesa_strtof( const char *s, char **end );
+
+extern unsigned int
+_mesa_str_checksum(const char *str);
+
+extern int
+_mesa_snprintf( char *str, size_t size, const char *fmt, ... ) PRINTFLIKE(3, 4);
+
+struct gl_context;
+
+extern void
+_mesa_warning( struct gl_context *gc, const char *fmtString, ... ) PRINTFLIKE(2, 3);
+
+extern void
+_mesa_problem( const struct gl_context *ctx, const char *fmtString, ... ) PRINTFLIKE(2, 3);
+
+extern void
+_mesa_error( struct gl_context *ctx, GLenum error, const char *fmtString, ... ) PRINTFLIKE(3, 4);
+
+extern void
+_mesa_debug( const struct gl_context *ctx, const char *fmtString, ... ) PRINTFLIKE(2, 3);
+
+
+#if defined(_MSC_VER) && !defined(snprintf)
+#define snprintf _snprintf
+#endif
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* IMPORTS_H */
diff --git a/mesalib/src/mesa/main/lines.c b/mesalib/src/mesa/main/lines.c
index 79bf5679d..1df409f45 100644
--- a/mesalib/src/mesa/main/lines.c
+++ b/mesalib/src/mesa/main/lines.c
@@ -1,117 +1,117 @@
-/*
- * Mesa 3-D graphics library
- * Version: 6.5.3
- *
- * Copyright (C) 1999-2006 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.
- */
-
-
-#include "glheader.h"
-#include "context.h"
-#include "lines.h"
-#include "macros.h"
-#include "mtypes.h"
-
-
-/**
- * Set the line width.
- *
- * \param width line width in pixels.
- *
- * \sa glLineWidth().
- */
-void GLAPIENTRY
-_mesa_LineWidth( GLfloat width )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glLineWidth %f\n", width);
-
- if (width<=0.0) {
- _mesa_error( ctx, GL_INVALID_VALUE, "glLineWidth" );
- return;
- }
-
- if (ctx->Line.Width == width)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_LINE);
- ctx->Line.Width = width;
-
- if (ctx->Driver.LineWidth)
- ctx->Driver.LineWidth(ctx, width);
-}
-
-
-/**
- * Set the line stipple pattern.
- *
- * \param factor pattern scale factor.
- * \param pattern bit pattern.
- *
- * \sa glLineStipple().
- *
- * Updates gl_line_attrib::StippleFactor and gl_line_attrib::StipplePattern. On
- * change flushes the vertices and notifies the driver via
- * the dd_function_table::LineStipple callback.
- */
-void GLAPIENTRY
-_mesa_LineStipple( GLint factor, GLushort pattern )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glLineStipple %d %u\n", factor, pattern);
-
- factor = CLAMP( factor, 1, 256 );
-
- if (ctx->Line.StippleFactor == factor &&
- ctx->Line.StipplePattern == pattern)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_LINE);
- ctx->Line.StippleFactor = factor;
- ctx->Line.StipplePattern = pattern;
-
- if (ctx->Driver.LineStipple)
- ctx->Driver.LineStipple( ctx, factor, pattern );
-}
-
-
-/**
- * Initialize the context line state.
- *
- * \param ctx GL context.
- *
- * Initializes __struct gl_contextRec::Line and line related constants in
- * __struct gl_contextRec::Const.
- */
-void GLAPIENTRY
-_mesa_init_line( struct gl_context * ctx )
-{
- ctx->Line.SmoothFlag = GL_FALSE;
- ctx->Line.StippleFlag = GL_FALSE;
- ctx->Line.Width = 1.0;
- ctx->Line.StipplePattern = 0xffff;
- ctx->Line.StippleFactor = 1;
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 6.5.3
+ *
+ * Copyright (C) 1999-2006 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.
+ */
+
+
+#include "glheader.h"
+#include "context.h"
+#include "lines.h"
+#include "macros.h"
+#include "mtypes.h"
+
+
+/**
+ * Set the line width.
+ *
+ * \param width line width in pixels.
+ *
+ * \sa glLineWidth().
+ */
+void GLAPIENTRY
+_mesa_LineWidth( GLfloat width )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glLineWidth %f\n", width);
+
+ if (width<=0.0) {
+ _mesa_error( ctx, GL_INVALID_VALUE, "glLineWidth" );
+ return;
+ }
+
+ if (ctx->Line.Width == width)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_LINE);
+ ctx->Line.Width = width;
+
+ if (ctx->Driver.LineWidth)
+ ctx->Driver.LineWidth(ctx, width);
+}
+
+
+/**
+ * Set the line stipple pattern.
+ *
+ * \param factor pattern scale factor.
+ * \param pattern bit pattern.
+ *
+ * \sa glLineStipple().
+ *
+ * Updates gl_line_attrib::StippleFactor and gl_line_attrib::StipplePattern. On
+ * change flushes the vertices and notifies the driver via
+ * the dd_function_table::LineStipple callback.
+ */
+void GLAPIENTRY
+_mesa_LineStipple( GLint factor, GLushort pattern )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glLineStipple %d %u\n", factor, pattern);
+
+ factor = CLAMP( factor, 1, 256 );
+
+ if (ctx->Line.StippleFactor == factor &&
+ ctx->Line.StipplePattern == pattern)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_LINE);
+ ctx->Line.StippleFactor = factor;
+ ctx->Line.StipplePattern = pattern;
+
+ if (ctx->Driver.LineStipple)
+ ctx->Driver.LineStipple( ctx, factor, pattern );
+}
+
+
+/**
+ * Initialize the context line state.
+ *
+ * \param ctx GL context.
+ *
+ * Initializes __struct gl_contextRec::Line and line related constants in
+ * __struct gl_contextRec::Const.
+ */
+void GLAPIENTRY
+_mesa_init_line( struct gl_context * ctx )
+{
+ ctx->Line.SmoothFlag = GL_FALSE;
+ ctx->Line.StippleFlag = GL_FALSE;
+ ctx->Line.Width = 1.0;
+ ctx->Line.StipplePattern = 0xffff;
+ ctx->Line.StippleFactor = 1;
+}
diff --git a/mesalib/src/mesa/main/queryobj.c b/mesalib/src/mesa/main/queryobj.c
index fa35c6ce5..dc9f18a65 100644
--- a/mesalib/src/mesa/main/queryobj.c
+++ b/mesalib/src/mesa/main/queryobj.c
@@ -1,623 +1,623 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.1
- *
- * Copyright (C) 1999-2007 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.
- */
-
-
-#include "glheader.h"
-#include "context.h"
-#include "enums.h"
-#include "hash.h"
-#include "imports.h"
-#include "queryobj.h"
-#include "mfeatures.h"
-#include "mtypes.h"
-#include "main/dispatch.h"
-
-
-#if FEATURE_queryobj
-
-
-/**
- * Allocate a new query object. This is a fallback routine called via
- * ctx->Driver.NewQueryObject().
- * \param ctx - rendering context
- * \param id - the new object's ID
- * \return pointer to new query_object object or NULL if out of memory.
- */
-static struct gl_query_object *
-_mesa_new_query_object(struct gl_context *ctx, GLuint id)
-{
- struct gl_query_object *q = MALLOC_STRUCT(gl_query_object);
- (void) ctx;
- if (q) {
- q->Id = id;
- q->Result = 0;
- q->Active = GL_FALSE;
- q->Ready = GL_TRUE; /* correct, see spec */
- }
- return q;
-}
-
-
-/**
- * Begin a query. Software driver fallback.
- * Called via ctx->Driver.BeginQuery().
- */
-static void
-_mesa_begin_query(struct gl_context *ctx, struct gl_query_object *q)
-{
- /* no-op */
-}
-
-
-/**
- * End a query. Software driver fallback.
- * Called via ctx->Driver.EndQuery().
- */
-static void
-_mesa_end_query(struct gl_context *ctx, struct gl_query_object *q)
-{
- q->Ready = GL_TRUE;
-}
-
-
-/**
- * Wait for query to complete. Software driver fallback.
- * Called via ctx->Driver.WaitQuery().
- */
-static void
-_mesa_wait_query(struct gl_context *ctx, struct gl_query_object *q)
-{
- /* For software drivers, _mesa_end_query() should have completed the query.
- * For real hardware, implement a proper WaitQuery() driver function,
- * which may require issuing a flush.
- */
- assert(q->Ready);
-}
-
-
-/**
- * Check if a query results are ready. Software driver fallback.
- * Called via ctx->Driver.CheckQuery().
- */
-static void
-_mesa_check_query(struct gl_context *ctx, struct gl_query_object *q)
-{
- /* No-op for sw rendering.
- * HW drivers may need to flush at this time.
- */
-}
-
-
-/**
- * Delete a query object. Called via ctx->Driver.DeleteQuery().
- * Not removed from hash table here.
- */
-static void
-_mesa_delete_query(struct gl_context *ctx, struct gl_query_object *q)
-{
- free(q);
-}
-
-
-void
-_mesa_init_query_object_functions(struct dd_function_table *driver)
-{
- driver->NewQueryObject = _mesa_new_query_object;
- driver->DeleteQuery = _mesa_delete_query;
- driver->BeginQuery = _mesa_begin_query;
- driver->EndQuery = _mesa_end_query;
- driver->WaitQuery = _mesa_wait_query;
- driver->CheckQuery = _mesa_check_query;
-}
-
-
-/**
- * Return pointer to the query object binding point for the given target.
- * \return NULL if invalid target, else the address of binding point
- */
-static struct gl_query_object **
-get_query_binding_point(struct gl_context *ctx, GLenum target)
-{
- switch (target) {
- case GL_SAMPLES_PASSED_ARB:
- if (ctx->Extensions.ARB_occlusion_query)
- return &ctx->Query.CurrentOcclusionObject;
- else
- return NULL;
- case GL_ANY_SAMPLES_PASSED:
- if (ctx->Extensions.ARB_occlusion_query2)
- return &ctx->Query.CurrentOcclusionObject;
- else
- return NULL;
- case GL_TIME_ELAPSED_EXT:
- if (ctx->Extensions.EXT_timer_query)
- return &ctx->Query.CurrentTimerObject;
- else
- return NULL;
-#if FEATURE_EXT_transform_feedback
- case GL_PRIMITIVES_GENERATED:
- if (ctx->Extensions.EXT_transform_feedback)
- return &ctx->Query.PrimitivesGenerated;
- else
- return NULL;
- case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
- if (ctx->Extensions.EXT_transform_feedback)
- return &ctx->Query.PrimitivesWritten;
- else
- return NULL;
-#endif
- default:
- return NULL;
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GenQueriesARB(GLsizei n, GLuint *ids)
-{
- GLuint first;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGenQueries(%d)\n", n);
-
- if (n < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGenQueriesARB(n < 0)");
- return;
- }
-
- /* No query objects can be active at this time! */
- if (ctx->Query.CurrentOcclusionObject ||
- ctx->Query.CurrentTimerObject) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glGenQueriesARB");
- return;
- }
-
- first = _mesa_HashFindFreeKeyBlock(ctx->Query.QueryObjects, n);
- if (first) {
- GLsizei i;
- for (i = 0; i < n; i++) {
- struct gl_query_object *q
- = ctx->Driver.NewQueryObject(ctx, first + i);
- if (!q) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glGenQueriesARB");
- return;
- }
- ids[i] = first + i;
- _mesa_HashInsert(ctx->Query.QueryObjects, first + i, q);
- }
- }
-}
-
-
-void GLAPIENTRY
-_mesa_DeleteQueriesARB(GLsizei n, const GLuint *ids)
-{
- GLint i;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glDeleeteQueries(%d)\n", n);
-
- if (n < 0) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteQueriesARB(n < 0)");
- return;
- }
-
- /* No query objects can be active at this time! */
- if (ctx->Query.CurrentOcclusionObject ||
- ctx->Query.CurrentTimerObject) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glDeleteQueriesARB");
- return;
- }
-
- for (i = 0; i < n; i++) {
- if (ids[i] > 0) {
- struct gl_query_object *q = _mesa_lookup_query_object(ctx, ids[i]);
- if (q) {
- ASSERT(!q->Active); /* should be caught earlier */
- _mesa_HashRemove(ctx->Query.QueryObjects, ids[i]);
- ctx->Driver.DeleteQuery(ctx, q);
- }
- }
- }
-}
-
-
-GLboolean GLAPIENTRY
-_mesa_IsQueryARB(GLuint id)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glIsQuery(%u)\n", id);
-
- if (id && _mesa_lookup_query_object(ctx, id))
- return GL_TRUE;
- else
- return GL_FALSE;
-}
-
-
-static void GLAPIENTRY
-_mesa_BeginQueryARB(GLenum target, GLuint id)
-{
- struct gl_query_object *q, **bindpt;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glBeginQuery(%s, %u)\n",
- _mesa_lookup_enum_by_nr(target), id);
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
-
- bindpt = get_query_binding_point(ctx, target);
- if (!bindpt) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glBeginQueryARB(target)");
- return;
- }
-
- if (id == 0) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glBeginQueryARB(id==0)");
- return;
- }
-
- q = _mesa_lookup_query_object(ctx, id);
- if (!q) {
- /* create new object */
- q = ctx->Driver.NewQueryObject(ctx, id);
- if (!q) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBeginQueryARB");
- return;
- }
- _mesa_HashInsert(ctx->Query.QueryObjects, id, q);
- }
- else {
- /* pre-existing object */
- if (q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glBeginQueryARB(query already active)");
- return;
- }
- }
-
- q->Target = target;
- q->Active = GL_TRUE;
- q->Result = 0;
- q->Ready = GL_FALSE;
-
- /* XXX should probably refcount query objects */
- *bindpt = q;
-
- ctx->Driver.BeginQuery(ctx, q);
-}
-
-
-static void GLAPIENTRY
-_mesa_EndQueryARB(GLenum target)
-{
- struct gl_query_object *q, **bindpt;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glEndQuery(%s)\n", _mesa_lookup_enum_by_nr(target));
-
- FLUSH_VERTICES(ctx, _NEW_DEPTH);
-
- bindpt = get_query_binding_point(ctx, target);
- if (!bindpt) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glEndQueryARB(target)");
- return;
- }
-
- /* XXX should probably refcount query objects */
- q = *bindpt;
- *bindpt = NULL;
-
- if (!q || !q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glEndQueryARB(no matching glBeginQueryARB)");
- return;
- }
-
- q->Active = GL_FALSE;
- ctx->Driver.EndQuery(ctx, q);
-}
-
-
-void GLAPIENTRY
-_mesa_GetQueryivARB(GLenum target, GLenum pname, GLint *params)
-{
- struct gl_query_object *q, **bindpt;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGetQueryiv(%s, %s)\n",
- _mesa_lookup_enum_by_nr(target),
- _mesa_lookup_enum_by_nr(pname));
-
- bindpt = get_query_binding_point(ctx, target);
- if (!bindpt) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryARB(target)");
- return;
- }
-
- q = *bindpt;
-
- switch (pname) {
- case GL_QUERY_COUNTER_BITS_ARB:
- *params = 8 * sizeof(q->Result);
- break;
- case GL_CURRENT_QUERY_ARB:
- *params = q ? q->Id : 0;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryivARB(pname)");
- return;
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GetQueryObjectivARB(GLuint id, GLenum pname, GLint *params)
-{
- struct gl_query_object *q = NULL;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGetQueryObjectiv(%u, %s)\n", id,
- _mesa_lookup_enum_by_nr(pname));
-
- if (id)
- q = _mesa_lookup_query_object(ctx, id);
-
- if (!q || q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glGetQueryObjectivARB(id=%d is invalid or active)", id);
- return;
- }
-
- switch (pname) {
- case GL_QUERY_RESULT_ARB:
- if (!q->Ready)
- ctx->Driver.WaitQuery(ctx, q);
- /* if result is too large for returned type, clamp to max value */
- if (q->Target == GL_ANY_SAMPLES_PASSED) {
- if (q->Result)
- *params = GL_TRUE;
- else
- *params = GL_FALSE;
- } else {
- if (q->Result > 0x7fffffff) {
- *params = 0x7fffffff;
- }
- else {
- *params = (GLint)q->Result;
- }
- }
- break;
- case GL_QUERY_RESULT_AVAILABLE_ARB:
- if (!q->Ready)
- ctx->Driver.CheckQuery( ctx, q );
- *params = q->Ready;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectivARB(pname)");
- return;
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GetQueryObjectuivARB(GLuint id, GLenum pname, GLuint *params)
-{
- struct gl_query_object *q = NULL;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGetQueryObjectuiv(%u, %s)\n", id,
- _mesa_lookup_enum_by_nr(pname));
-
- if (id)
- q = _mesa_lookup_query_object(ctx, id);
-
- if (!q || q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glGetQueryObjectuivARB(id=%d is invalid or active)", id);
- return;
- }
-
- switch (pname) {
- case GL_QUERY_RESULT_ARB:
- if (!q->Ready)
- ctx->Driver.WaitQuery(ctx, q);
- /* if result is too large for returned type, clamp to max value */
- if (q->Target == GL_ANY_SAMPLES_PASSED) {
- if (q->Result)
- *params = GL_TRUE;
- else
- *params = GL_FALSE;
- } else {
- if (q->Result > 0xffffffff) {
- *params = 0xffffffff;
- }
- else {
- *params = (GLuint)q->Result;
- }
- }
- break;
- case GL_QUERY_RESULT_AVAILABLE_ARB:
- if (!q->Ready)
- ctx->Driver.CheckQuery( ctx, q );
- *params = q->Ready;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectuivARB(pname)");
- return;
- }
-}
-
-
-/**
- * New with GL_EXT_timer_query
- */
-static void GLAPIENTRY
-_mesa_GetQueryObjecti64vEXT(GLuint id, GLenum pname, GLint64EXT *params)
-{
- struct gl_query_object *q = NULL;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGetQueryObjecti64v(%u, %s)\n", id,
- _mesa_lookup_enum_by_nr(pname));
-
- if (id)
- q = _mesa_lookup_query_object(ctx, id);
-
- if (!q || q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glGetQueryObjectui64vARB(id=%d is invalid or active)", id);
- return;
- }
-
- switch (pname) {
- case GL_QUERY_RESULT_ARB:
- if (!q->Ready)
- ctx->Driver.WaitQuery(ctx, q);
- *params = q->Result;
- break;
- case GL_QUERY_RESULT_AVAILABLE_ARB:
- if (!q->Ready)
- ctx->Driver.CheckQuery( ctx, q );
- *params = q->Ready;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjecti64vARB(pname)");
- return;
- }
-}
-
-
-/**
- * New with GL_EXT_timer_query
- */
-static void GLAPIENTRY
-_mesa_GetQueryObjectui64vEXT(GLuint id, GLenum pname, GLuint64EXT *params)
-{
- struct gl_query_object *q = NULL;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glGetQueryObjectui64v(%u, %s)\n", id,
- _mesa_lookup_enum_by_nr(pname));
-
- if (id)
- q = _mesa_lookup_query_object(ctx, id);
-
- if (!q || q->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glGetQueryObjectuui64vARB(id=%d is invalid or active)", id);
- return;
- }
-
- switch (pname) {
- case GL_QUERY_RESULT_ARB:
- if (!q->Ready)
- ctx->Driver.WaitQuery(ctx, q);
- *params = q->Result;
- break;
- case GL_QUERY_RESULT_AVAILABLE_ARB:
- if (!q->Ready)
- ctx->Driver.CheckQuery( ctx, q );
- *params = q->Ready;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectui64vARB(pname)");
- return;
- }
-}
-
-
-void
-_mesa_init_queryobj_dispatch(struct _glapi_table *disp)
-{
- SET_GenQueriesARB(disp, _mesa_GenQueriesARB);
- SET_DeleteQueriesARB(disp, _mesa_DeleteQueriesARB);
- SET_IsQueryARB(disp, _mesa_IsQueryARB);
- SET_BeginQueryARB(disp, _mesa_BeginQueryARB);
- SET_EndQueryARB(disp, _mesa_EndQueryARB);
- SET_GetQueryivARB(disp, _mesa_GetQueryivARB);
- SET_GetQueryObjectivARB(disp, _mesa_GetQueryObjectivARB);
- SET_GetQueryObjectuivARB(disp, _mesa_GetQueryObjectuivARB);
-
- SET_GetQueryObjecti64vEXT(disp, _mesa_GetQueryObjecti64vEXT);
- SET_GetQueryObjectui64vEXT(disp, _mesa_GetQueryObjectui64vEXT);
-}
-
-
-#endif /* FEATURE_queryobj */
-
-
-/**
- * Allocate/init the context state related to query objects.
- */
-void
-_mesa_init_queryobj(struct gl_context *ctx)
-{
- ctx->Query.QueryObjects = _mesa_NewHashTable();
- ctx->Query.CurrentOcclusionObject = NULL;
-}
-
-
-/**
- * Callback for deleting a query object. Called by _mesa_HashDeleteAll().
- */
-static void
-delete_queryobj_cb(GLuint id, void *data, void *userData)
-{
- struct gl_query_object *q= (struct gl_query_object *) data;
- struct gl_context *ctx = (struct gl_context *)userData;
- ctx->Driver.DeleteQuery(ctx, q);
-}
-
-
-/**
- * Free the context state related to query objects.
- */
-void
-_mesa_free_queryobj_data(struct gl_context *ctx)
-{
- _mesa_HashDeleteAll(ctx->Query.QueryObjects, delete_queryobj_cb, ctx);
- _mesa_DeleteHashTable(ctx->Query.QueryObjects);
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.1
+ *
+ * Copyright (C) 1999-2007 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.
+ */
+
+
+#include "glheader.h"
+#include "context.h"
+#include "enums.h"
+#include "hash.h"
+#include "imports.h"
+#include "queryobj.h"
+#include "mfeatures.h"
+#include "mtypes.h"
+#include "main/dispatch.h"
+
+
+#if FEATURE_queryobj
+
+
+/**
+ * Allocate a new query object. This is a fallback routine called via
+ * ctx->Driver.NewQueryObject().
+ * \param ctx - rendering context
+ * \param id - the new object's ID
+ * \return pointer to new query_object object or NULL if out of memory.
+ */
+struct gl_query_object *
+_mesa_new_query_object(struct gl_context *ctx, GLuint id)
+{
+ struct gl_query_object *q = MALLOC_STRUCT(gl_query_object);
+ (void) ctx;
+ if (q) {
+ q->Id = id;
+ q->Result = 0;
+ q->Active = GL_FALSE;
+ q->Ready = GL_TRUE; /* correct, see spec */
+ }
+ return q;
+}
+
+
+/**
+ * Begin a query. Software driver fallback.
+ * Called via ctx->Driver.BeginQuery().
+ */
+void
+_mesa_begin_query(struct gl_context *ctx, struct gl_query_object *q)
+{
+ /* no-op */
+}
+
+
+/**
+ * End a query. Software driver fallback.
+ * Called via ctx->Driver.EndQuery().
+ */
+void
+_mesa_end_query(struct gl_context *ctx, struct gl_query_object *q)
+{
+ q->Ready = GL_TRUE;
+}
+
+
+/**
+ * Wait for query to complete. Software driver fallback.
+ * Called via ctx->Driver.WaitQuery().
+ */
+void
+_mesa_wait_query(struct gl_context *ctx, struct gl_query_object *q)
+{
+ /* For software drivers, _mesa_end_query() should have completed the query.
+ * For real hardware, implement a proper WaitQuery() driver function,
+ * which may require issuing a flush.
+ */
+ assert(q->Ready);
+}
+
+
+/**
+ * Check if a query results are ready. Software driver fallback.
+ * Called via ctx->Driver.CheckQuery().
+ */
+static void
+_mesa_check_query(struct gl_context *ctx, struct gl_query_object *q)
+{
+ /* No-op for sw rendering.
+ * HW drivers may need to flush at this time.
+ */
+}
+
+
+/**
+ * Delete a query object. Called via ctx->Driver.DeleteQuery().
+ * Not removed from hash table here.
+ */
+void
+_mesa_delete_query(struct gl_context *ctx, struct gl_query_object *q)
+{
+ free(q);
+}
+
+
+void
+_mesa_init_query_object_functions(struct dd_function_table *driver)
+{
+ driver->NewQueryObject = _mesa_new_query_object;
+ driver->DeleteQuery = _mesa_delete_query;
+ driver->BeginQuery = _mesa_begin_query;
+ driver->EndQuery = _mesa_end_query;
+ driver->WaitQuery = _mesa_wait_query;
+ driver->CheckQuery = _mesa_check_query;
+}
+
+
+/**
+ * Return pointer to the query object binding point for the given target.
+ * \return NULL if invalid target, else the address of binding point
+ */
+static struct gl_query_object **
+get_query_binding_point(struct gl_context *ctx, GLenum target)
+{
+ switch (target) {
+ case GL_SAMPLES_PASSED_ARB:
+ if (ctx->Extensions.ARB_occlusion_query)
+ return &ctx->Query.CurrentOcclusionObject;
+ else
+ return NULL;
+ case GL_ANY_SAMPLES_PASSED:
+ if (ctx->Extensions.ARB_occlusion_query2)
+ return &ctx->Query.CurrentOcclusionObject;
+ else
+ return NULL;
+ case GL_TIME_ELAPSED_EXT:
+ if (ctx->Extensions.EXT_timer_query)
+ return &ctx->Query.CurrentTimerObject;
+ else
+ return NULL;
+#if FEATURE_EXT_transform_feedback
+ case GL_PRIMITIVES_GENERATED:
+ if (ctx->Extensions.EXT_transform_feedback)
+ return &ctx->Query.PrimitivesGenerated;
+ else
+ return NULL;
+ case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
+ if (ctx->Extensions.EXT_transform_feedback)
+ return &ctx->Query.PrimitivesWritten;
+ else
+ return NULL;
+#endif
+ default:
+ return NULL;
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GenQueriesARB(GLsizei n, GLuint *ids)
+{
+ GLuint first;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGenQueries(%d)\n", n);
+
+ if (n < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGenQueriesARB(n < 0)");
+ return;
+ }
+
+ /* No query objects can be active at this time! */
+ if (ctx->Query.CurrentOcclusionObject ||
+ ctx->Query.CurrentTimerObject) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glGenQueriesARB");
+ return;
+ }
+
+ first = _mesa_HashFindFreeKeyBlock(ctx->Query.QueryObjects, n);
+ if (first) {
+ GLsizei i;
+ for (i = 0; i < n; i++) {
+ struct gl_query_object *q
+ = ctx->Driver.NewQueryObject(ctx, first + i);
+ if (!q) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glGenQueriesARB");
+ return;
+ }
+ ids[i] = first + i;
+ _mesa_HashInsert(ctx->Query.QueryObjects, first + i, q);
+ }
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_DeleteQueriesARB(GLsizei n, const GLuint *ids)
+{
+ GLint i;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glDeleeteQueries(%d)\n", n);
+
+ if (n < 0) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glDeleteQueriesARB(n < 0)");
+ return;
+ }
+
+ /* No query objects can be active at this time! */
+ if (ctx->Query.CurrentOcclusionObject ||
+ ctx->Query.CurrentTimerObject) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glDeleteQueriesARB");
+ return;
+ }
+
+ for (i = 0; i < n; i++) {
+ if (ids[i] > 0) {
+ struct gl_query_object *q = _mesa_lookup_query_object(ctx, ids[i]);
+ if (q) {
+ ASSERT(!q->Active); /* should be caught earlier */
+ _mesa_HashRemove(ctx->Query.QueryObjects, ids[i]);
+ ctx->Driver.DeleteQuery(ctx, q);
+ }
+ }
+ }
+}
+
+
+GLboolean GLAPIENTRY
+_mesa_IsQueryARB(GLuint id)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END_WITH_RETVAL(ctx, GL_FALSE);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glIsQuery(%u)\n", id);
+
+ if (id && _mesa_lookup_query_object(ctx, id))
+ return GL_TRUE;
+ else
+ return GL_FALSE;
+}
+
+
+static void GLAPIENTRY
+_mesa_BeginQueryARB(GLenum target, GLuint id)
+{
+ struct gl_query_object *q, **bindpt;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glBeginQuery(%s, %u)\n",
+ _mesa_lookup_enum_by_nr(target), id);
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+
+ bindpt = get_query_binding_point(ctx, target);
+ if (!bindpt) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glBeginQueryARB(target)");
+ return;
+ }
+
+ if (id == 0) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glBeginQueryARB(id==0)");
+ return;
+ }
+
+ q = _mesa_lookup_query_object(ctx, id);
+ if (!q) {
+ /* create new object */
+ q = ctx->Driver.NewQueryObject(ctx, id);
+ if (!q) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBeginQueryARB");
+ return;
+ }
+ _mesa_HashInsert(ctx->Query.QueryObjects, id, q);
+ }
+ else {
+ /* pre-existing object */
+ if (q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glBeginQueryARB(query already active)");
+ return;
+ }
+ }
+
+ q->Target = target;
+ q->Active = GL_TRUE;
+ q->Result = 0;
+ q->Ready = GL_FALSE;
+
+ /* XXX should probably refcount query objects */
+ *bindpt = q;
+
+ ctx->Driver.BeginQuery(ctx, q);
+}
+
+
+static void GLAPIENTRY
+_mesa_EndQueryARB(GLenum target)
+{
+ struct gl_query_object *q, **bindpt;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glEndQuery(%s)\n", _mesa_lookup_enum_by_nr(target));
+
+ FLUSH_VERTICES(ctx, _NEW_DEPTH);
+
+ bindpt = get_query_binding_point(ctx, target);
+ if (!bindpt) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glEndQueryARB(target)");
+ return;
+ }
+
+ /* XXX should probably refcount query objects */
+ q = *bindpt;
+ *bindpt = NULL;
+
+ if (!q || !q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glEndQueryARB(no matching glBeginQueryARB)");
+ return;
+ }
+
+ q->Active = GL_FALSE;
+ ctx->Driver.EndQuery(ctx, q);
+}
+
+
+void GLAPIENTRY
+_mesa_GetQueryivARB(GLenum target, GLenum pname, GLint *params)
+{
+ struct gl_query_object *q, **bindpt;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGetQueryiv(%s, %s)\n",
+ _mesa_lookup_enum_by_nr(target),
+ _mesa_lookup_enum_by_nr(pname));
+
+ bindpt = get_query_binding_point(ctx, target);
+ if (!bindpt) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryARB(target)");
+ return;
+ }
+
+ q = *bindpt;
+
+ switch (pname) {
+ case GL_QUERY_COUNTER_BITS_ARB:
+ *params = 8 * sizeof(q->Result);
+ break;
+ case GL_CURRENT_QUERY_ARB:
+ *params = q ? q->Id : 0;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryivARB(pname)");
+ return;
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GetQueryObjectivARB(GLuint id, GLenum pname, GLint *params)
+{
+ struct gl_query_object *q = NULL;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGetQueryObjectiv(%u, %s)\n", id,
+ _mesa_lookup_enum_by_nr(pname));
+
+ if (id)
+ q = _mesa_lookup_query_object(ctx, id);
+
+ if (!q || q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glGetQueryObjectivARB(id=%d is invalid or active)", id);
+ return;
+ }
+
+ switch (pname) {
+ case GL_QUERY_RESULT_ARB:
+ if (!q->Ready)
+ ctx->Driver.WaitQuery(ctx, q);
+ /* if result is too large for returned type, clamp to max value */
+ if (q->Target == GL_ANY_SAMPLES_PASSED) {
+ if (q->Result)
+ *params = GL_TRUE;
+ else
+ *params = GL_FALSE;
+ } else {
+ if (q->Result > 0x7fffffff) {
+ *params = 0x7fffffff;
+ }
+ else {
+ *params = (GLint)q->Result;
+ }
+ }
+ break;
+ case GL_QUERY_RESULT_AVAILABLE_ARB:
+ if (!q->Ready)
+ ctx->Driver.CheckQuery( ctx, q );
+ *params = q->Ready;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectivARB(pname)");
+ return;
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GetQueryObjectuivARB(GLuint id, GLenum pname, GLuint *params)
+{
+ struct gl_query_object *q = NULL;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGetQueryObjectuiv(%u, %s)\n", id,
+ _mesa_lookup_enum_by_nr(pname));
+
+ if (id)
+ q = _mesa_lookup_query_object(ctx, id);
+
+ if (!q || q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glGetQueryObjectuivARB(id=%d is invalid or active)", id);
+ return;
+ }
+
+ switch (pname) {
+ case GL_QUERY_RESULT_ARB:
+ if (!q->Ready)
+ ctx->Driver.WaitQuery(ctx, q);
+ /* if result is too large for returned type, clamp to max value */
+ if (q->Target == GL_ANY_SAMPLES_PASSED) {
+ if (q->Result)
+ *params = GL_TRUE;
+ else
+ *params = GL_FALSE;
+ } else {
+ if (q->Result > 0xffffffff) {
+ *params = 0xffffffff;
+ }
+ else {
+ *params = (GLuint)q->Result;
+ }
+ }
+ break;
+ case GL_QUERY_RESULT_AVAILABLE_ARB:
+ if (!q->Ready)
+ ctx->Driver.CheckQuery( ctx, q );
+ *params = q->Ready;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectuivARB(pname)");
+ return;
+ }
+}
+
+
+/**
+ * New with GL_EXT_timer_query
+ */
+static void GLAPIENTRY
+_mesa_GetQueryObjecti64vEXT(GLuint id, GLenum pname, GLint64EXT *params)
+{
+ struct gl_query_object *q = NULL;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGetQueryObjecti64v(%u, %s)\n", id,
+ _mesa_lookup_enum_by_nr(pname));
+
+ if (id)
+ q = _mesa_lookup_query_object(ctx, id);
+
+ if (!q || q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glGetQueryObjectui64vARB(id=%d is invalid or active)", id);
+ return;
+ }
+
+ switch (pname) {
+ case GL_QUERY_RESULT_ARB:
+ if (!q->Ready)
+ ctx->Driver.WaitQuery(ctx, q);
+ *params = q->Result;
+ break;
+ case GL_QUERY_RESULT_AVAILABLE_ARB:
+ if (!q->Ready)
+ ctx->Driver.CheckQuery( ctx, q );
+ *params = q->Ready;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjecti64vARB(pname)");
+ return;
+ }
+}
+
+
+/**
+ * New with GL_EXT_timer_query
+ */
+static void GLAPIENTRY
+_mesa_GetQueryObjectui64vEXT(GLuint id, GLenum pname, GLuint64EXT *params)
+{
+ struct gl_query_object *q = NULL;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glGetQueryObjectui64v(%u, %s)\n", id,
+ _mesa_lookup_enum_by_nr(pname));
+
+ if (id)
+ q = _mesa_lookup_query_object(ctx, id);
+
+ if (!q || q->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glGetQueryObjectuui64vARB(id=%d is invalid or active)", id);
+ return;
+ }
+
+ switch (pname) {
+ case GL_QUERY_RESULT_ARB:
+ if (!q->Ready)
+ ctx->Driver.WaitQuery(ctx, q);
+ *params = q->Result;
+ break;
+ case GL_QUERY_RESULT_AVAILABLE_ARB:
+ if (!q->Ready)
+ ctx->Driver.CheckQuery( ctx, q );
+ *params = q->Ready;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetQueryObjectui64vARB(pname)");
+ return;
+ }
+}
+
+
+void
+_mesa_init_queryobj_dispatch(struct _glapi_table *disp)
+{
+ SET_GenQueriesARB(disp, _mesa_GenQueriesARB);
+ SET_DeleteQueriesARB(disp, _mesa_DeleteQueriesARB);
+ SET_IsQueryARB(disp, _mesa_IsQueryARB);
+ SET_BeginQueryARB(disp, _mesa_BeginQueryARB);
+ SET_EndQueryARB(disp, _mesa_EndQueryARB);
+ SET_GetQueryivARB(disp, _mesa_GetQueryivARB);
+ SET_GetQueryObjectivARB(disp, _mesa_GetQueryObjectivARB);
+ SET_GetQueryObjectuivARB(disp, _mesa_GetQueryObjectuivARB);
+
+ SET_GetQueryObjecti64vEXT(disp, _mesa_GetQueryObjecti64vEXT);
+ SET_GetQueryObjectui64vEXT(disp, _mesa_GetQueryObjectui64vEXT);
+}
+
+
+#endif /* FEATURE_queryobj */
+
+
+/**
+ * Allocate/init the context state related to query objects.
+ */
+void
+_mesa_init_queryobj(struct gl_context *ctx)
+{
+ ctx->Query.QueryObjects = _mesa_NewHashTable();
+ ctx->Query.CurrentOcclusionObject = NULL;
+}
+
+
+/**
+ * Callback for deleting a query object. Called by _mesa_HashDeleteAll().
+ */
+static void
+delete_queryobj_cb(GLuint id, void *data, void *userData)
+{
+ struct gl_query_object *q= (struct gl_query_object *) data;
+ struct gl_context *ctx = (struct gl_context *)userData;
+ ctx->Driver.DeleteQuery(ctx, q);
+}
+
+
+/**
+ * Free the context state related to query objects.
+ */
+void
+_mesa_free_queryobj_data(struct gl_context *ctx)
+{
+ _mesa_HashDeleteAll(ctx->Query.QueryObjects, delete_queryobj_cb, ctx);
+ _mesa_DeleteHashTable(ctx->Query.QueryObjects);
+}
diff --git a/mesalib/src/mesa/main/shaderapi.c b/mesalib/src/mesa/main/shaderapi.c
index 11b0f884f..252cda845 100644
--- a/mesalib/src/mesa/main/shaderapi.c
+++ b/mesalib/src/mesa/main/shaderapi.c
@@ -1,1942 +1,1942 @@
-/*
- * Mesa 3-D graphics library
- *
- * Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
- * Copyright (C) 2009-2010 VMware, Inc. 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 shaderapi.c
- * \author Brian Paul
- *
- * Implementation of GLSL-related API functions.
- * The glUniform* functions are in uniforms.c
- *
- *
- * XXX things to do:
- * 1. Check that the right error code is generated for all _mesa_error() calls.
- * 2. Insert FLUSH_VERTICES calls in various places
- */
-
-
-#include "main/glheader.h"
-#include "main/context.h"
-#include "main/dispatch.h"
-#include "main/enums.h"
-#include "main/hash.h"
-#include "main/mfeatures.h"
-#include "main/mtypes.h"
-#include "main/shaderapi.h"
-#include "main/shaderobj.h"
-#include "program/program.h"
-#include "program/prog_parameter.h"
-#include "program/prog_uniform.h"
-#include "ralloc.h"
-#include <stdbool.h>
-#include "../glsl/glsl_parser_extras.h"
-
-/** Define this to enable shader substitution (see below) */
-#define SHADER_SUBST 0
-
-
-/**
- * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
- */
-static GLbitfield
-get_shader_flags(void)
-{
- GLbitfield flags = 0x0;
- const char *env = _mesa_getenv("MESA_GLSL");
-
- if (env) {
- if (strstr(env, "dump"))
- flags |= GLSL_DUMP;
- if (strstr(env, "log"))
- flags |= GLSL_LOG;
- if (strstr(env, "nopvert"))
- flags |= GLSL_NOP_VERT;
- if (strstr(env, "nopfrag"))
- flags |= GLSL_NOP_FRAG;
- if (strstr(env, "nopt"))
- flags |= GLSL_NO_OPT;
- else if (strstr(env, "opt"))
- flags |= GLSL_OPT;
- if (strstr(env, "uniform"))
- flags |= GLSL_UNIFORMS;
- if (strstr(env, "useprog"))
- flags |= GLSL_USE_PROG;
- }
-
- return flags;
-}
-
-
-/**
- * Initialize context's shader state.
- */
-void
-_mesa_init_shader_state(struct gl_context *ctx)
-{
- /* Device drivers may override these to control what kind of instructions
- * are generated by the GLSL compiler.
- */
- struct gl_shader_compiler_options options;
- gl_shader_type sh;
-
- memset(&options, 0, sizeof(options));
- options.MaxUnrollIterations = 32;
-
- /* Default pragma settings */
- options.DefaultPragmas.Optimize = GL_TRUE;
-
- for (sh = 0; sh < MESA_SHADER_TYPES; ++sh)
- memcpy(&ctx->ShaderCompilerOptions[sh], &options, sizeof(options));
-
- ctx->Shader.Flags = get_shader_flags();
-}
-
-
-/**
- * Free the per-context shader-related state.
- */
-void
-_mesa_free_shader_state(struct gl_context *ctx)
-{
- _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentVertexProgram, NULL);
- _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentGeometryProgram,
- NULL);
- _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentFragmentProgram,
- NULL);
- _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
-}
-
-
-/**
- * Return the size of the given GLSL datatype, in floats (components).
- */
-GLint
-_mesa_sizeof_glsl_type(GLenum type)
-{
- switch (type) {
- case GL_FLOAT:
- case GL_INT:
- case GL_BOOL:
- case GL_SAMPLER_1D:
- case GL_SAMPLER_2D:
- case GL_SAMPLER_3D:
- case GL_SAMPLER_CUBE:
- case GL_SAMPLER_1D_SHADOW:
- case GL_SAMPLER_2D_SHADOW:
- case GL_SAMPLER_2D_RECT_ARB:
- case GL_SAMPLER_2D_RECT_SHADOW_ARB:
- case GL_SAMPLER_1D_ARRAY_EXT:
- case GL_SAMPLER_2D_ARRAY_EXT:
- case GL_SAMPLER_1D_ARRAY_SHADOW_EXT:
- case GL_SAMPLER_2D_ARRAY_SHADOW_EXT:
- case GL_SAMPLER_CUBE_SHADOW_EXT:
- return 1;
- case GL_FLOAT_VEC2:
- case GL_INT_VEC2:
- case GL_UNSIGNED_INT_VEC2:
- case GL_BOOL_VEC2:
- return 2;
- case GL_FLOAT_VEC3:
- case GL_INT_VEC3:
- case GL_UNSIGNED_INT_VEC3:
- case GL_BOOL_VEC3:
- return 3;
- case GL_FLOAT_VEC4:
- case GL_INT_VEC4:
- case GL_UNSIGNED_INT_VEC4:
- case GL_BOOL_VEC4:
- return 4;
- case GL_FLOAT_MAT2:
- case GL_FLOAT_MAT2x3:
- case GL_FLOAT_MAT2x4:
- return 8; /* two float[4] vectors */
- case GL_FLOAT_MAT3:
- case GL_FLOAT_MAT3x2:
- case GL_FLOAT_MAT3x4:
- return 12; /* three float[4] vectors */
- case GL_FLOAT_MAT4:
- case GL_FLOAT_MAT4x2:
- case GL_FLOAT_MAT4x3:
- return 16; /* four float[4] vectors */
- default:
- _mesa_problem(NULL, "Invalid type in _mesa_sizeof_glsl_type()");
- return 1;
- }
-}
-
-
-/**
- * Copy string from <src> to <dst>, up to maxLength characters, returning
- * length of <dst> in <length>.
- * \param src the strings source
- * \param maxLength max chars to copy
- * \param length returns number of chars copied
- * \param dst the string destination
- */
-void
-_mesa_copy_string(GLchar *dst, GLsizei maxLength,
- GLsizei *length, const GLchar *src)
-{
- GLsizei len;
- for (len = 0; len < maxLength - 1 && src && src[len]; len++)
- dst[len] = src[len];
- if (maxLength > 0)
- dst[len] = 0;
- if (length)
- *length = len;
-}
-
-
-
-/**
- * Confirm that the a shader type is valid and supported by the implementation
- *
- * \param ctx Current GL context
- * \param type Shader target
- *
- */
-static bool
-validate_shader_target(const struct gl_context *ctx, GLenum type)
-{
- switch (type) {
-#if FEATURE_ARB_fragment_shader
- case GL_FRAGMENT_SHADER:
- return ctx->Extensions.ARB_fragment_shader;
-#endif
-#if FEATURE_ARB_vertex_shader
- case GL_VERTEX_SHADER:
- return ctx->Extensions.ARB_vertex_shader;
-#endif
-#if FEATURE_ARB_geometry_shader4
- case GL_GEOMETRY_SHADER_ARB:
- return ctx->Extensions.ARB_geometry_shader4;
-#endif
- default:
- return false;
- }
-}
-
-
-/**
- * Find the length of the longest transform feedback varying name
- * which was specified with glTransformFeedbackVaryings().
- */
-static GLint
-longest_feedback_varying_name(const struct gl_shader_program *shProg)
-{
- GLuint i;
- GLint max = 0;
- for (i = 0; i < shProg->TransformFeedback.NumVarying; i++) {
- GLint len = strlen(shProg->TransformFeedback.VaryingNames[i]);
- if (len > max)
- max = len;
- }
- return max;
-}
-
-
-
-static GLboolean
-is_program(struct gl_context *ctx, GLuint name)
-{
- struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
- return shProg ? GL_TRUE : GL_FALSE;
-}
-
-
-static GLboolean
-is_shader(struct gl_context *ctx, GLuint name)
-{
- struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
- return shader ? GL_TRUE : GL_FALSE;
-}
-
-
-/**
- * Attach shader to a shader program.
- */
-static void
-attach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
-{
- struct gl_shader_program *shProg;
- struct gl_shader *sh;
- GLuint i, n;
-
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glAttachShader");
- if (!shProg)
- return;
-
- sh = _mesa_lookup_shader_err(ctx, shader, "glAttachShader");
- if (!sh) {
- return;
- }
-
- n = shProg->NumShaders;
- for (i = 0; i < n; i++) {
- if (shProg->Shaders[i] == sh) {
- /* The shader is already attched to this program. The
- * GL_ARB_shader_objects spec says:
- *
- * "The error INVALID_OPERATION is generated by AttachObjectARB
- * if <obj> is already attached to <containerObj>."
- */
- _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
- return;
- }
- }
-
- /* grow list */
- shProg->Shaders = (struct gl_shader **)
- _mesa_realloc(shProg->Shaders,
- n * sizeof(struct gl_shader *),
- (n + 1) * sizeof(struct gl_shader *));
- if (!shProg->Shaders) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
- return;
- }
-
- /* append */
- shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
- _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
- shProg->NumShaders++;
-}
-
-
-static GLint
-get_attrib_location(struct gl_context *ctx, GLuint program, const GLchar *name)
-{
- struct gl_shader_program *shProg
- = _mesa_lookup_shader_program_err(ctx, program, "glGetAttribLocation");
-
- if (!shProg) {
- return -1;
- }
-
- if (!shProg->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glGetAttribLocation(program not linked)");
- return -1;
- }
-
- if (!name)
- return -1;
-
- if (shProg->VertexProgram) {
- const struct gl_program_parameter_list *attribs =
- shProg->VertexProgram->Base.Attributes;
- if (attribs) {
- GLint i = _mesa_lookup_parameter_index(attribs, -1, name);
- if (i >= 0) {
- return attribs->Parameters[i].StateIndexes[0];
- }
- }
- }
- return -1;
-}
-
-
-static void
-bind_attrib_location(struct gl_context *ctx, GLuint program, GLuint index,
- const GLchar *name)
-{
- struct gl_shader_program *shProg;
- const GLint size = -1; /* unknown size */
- GLint i, oldIndex;
- GLenum datatype = GL_FLOAT_VEC4;
-
- shProg = _mesa_lookup_shader_program_err(ctx, program,
- "glBindAttribLocation");
- if (!shProg) {
- return;
- }
-
- if (!name)
- return;
-
- if (strncmp(name, "gl_", 3) == 0) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glBindAttribLocation(illegal name)");
- return;
- }
-
- if (index >= ctx->Const.VertexProgram.MaxAttribs) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glBindAttribLocation(index)");
- return;
- }
-
- if (shProg->LinkStatus) {
- /* get current index/location for the attribute */
- oldIndex = get_attrib_location(ctx, program, name);
- }
- else {
- oldIndex = -1;
- }
-
- /* this will replace the current value if it's already in the list */
- i = _mesa_add_attribute(shProg->Attributes, name, size, datatype, index);
- if (i < 0) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindAttribLocation");
- return;
- }
-
- /*
- * Note that this attribute binding won't go into effect until
- * glLinkProgram is called again.
- */
-}
-
-
-static void
-bind_frag_data_location(struct gl_context *ctx, GLuint program,
- GLuint colorNumber, const GLchar *name)
-{
- _mesa_problem(ctx, "bind_frag_data_location() not implemented yet");
-}
-
-
-static GLuint
-create_shader(struct gl_context *ctx, GLenum type)
-{
- struct gl_shader *sh;
- GLuint name;
-
- if (!validate_shader_target(ctx, type)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "CreateShader(type)");
- return 0;
- }
-
- name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
- sh = ctx->Driver.NewShader(ctx, name, type);
- _mesa_HashInsert(ctx->Shared->ShaderObjects, name, sh);
-
- return name;
-}
-
-
-static GLuint
-create_shader_program(struct gl_context *ctx)
-{
- GLuint name;
- struct gl_shader_program *shProg;
-
- name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
-
- shProg = ctx->Driver.NewShaderProgram(ctx, name);
-
- _mesa_HashInsert(ctx->Shared->ShaderObjects, name, shProg);
-
- assert(shProg->RefCount == 1);
-
- return name;
-}
-
-
-/**
- * Named w/ "2" to indicate OpenGL 2.x vs GL_ARB_fragment_programs's
- * DeleteProgramARB.
- */
-static void
-delete_shader_program(struct gl_context *ctx, GLuint name)
-{
- /*
- * NOTE: deleting shaders/programs works a bit differently than
- * texture objects (and buffer objects, etc). Shader/program
- * handles/IDs exist in the hash table until the object is really
- * deleted (refcount==0). With texture objects, the handle/ID is
- * removed from the hash table in glDeleteTextures() while the tex
- * object itself might linger until its refcount goes to zero.
- */
- struct gl_shader_program *shProg;
-
- shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
- if (!shProg)
- return;
-
- shProg->DeletePending = GL_TRUE;
-
- /* effectively, decr shProg's refcount */
- _mesa_reference_shader_program(ctx, &shProg, NULL);
-}
-
-
-static void
-delete_shader(struct gl_context *ctx, GLuint shader)
-{
- struct gl_shader *sh;
-
- sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
- if (!sh)
- return;
-
- sh->DeletePending = GL_TRUE;
-
- /* effectively, decr sh's refcount */
- _mesa_reference_shader(ctx, &sh, NULL);
-}
-
-
-static void
-detach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
-{
- struct gl_shader_program *shProg;
- GLuint n;
- GLuint i, j;
-
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
- if (!shProg)
- return;
-
- n = shProg->NumShaders;
-
- for (i = 0; i < n; i++) {
- if (shProg->Shaders[i]->Name == shader) {
- /* found it */
- struct gl_shader **newList;
-
- /* release */
- _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
-
- /* alloc new, smaller array */
- newList = (struct gl_shader **)
- malloc((n - 1) * sizeof(struct gl_shader *));
- if (!newList) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
- return;
- }
- for (j = 0; j < i; j++) {
- newList[j] = shProg->Shaders[j];
- }
- while (++i < n)
- newList[j++] = shProg->Shaders[i];
- free(shProg->Shaders);
-
- shProg->Shaders = newList;
- shProg->NumShaders = n - 1;
-
-#ifdef DEBUG
- /* sanity check */
- {
- for (j = 0; j < shProg->NumShaders; j++) {
- assert(shProg->Shaders[j]->Type == GL_VERTEX_SHADER ||
- shProg->Shaders[j]->Type == GL_FRAGMENT_SHADER);
- assert(shProg->Shaders[j]->RefCount > 0);
- }
- }
-#endif
-
- return;
- }
- }
-
- /* not found */
- {
- GLenum err;
- if (is_shader(ctx, shader))
- err = GL_INVALID_OPERATION;
- else if (is_program(ctx, shader))
- err = GL_INVALID_OPERATION;
- else
- err = GL_INVALID_VALUE;
- _mesa_error(ctx, err, "glDetachProgram(shader)");
- return;
- }
-}
-
-
-static void
-get_active_attrib(struct gl_context *ctx, GLuint program, GLuint index,
- GLsizei maxLength, GLsizei *length, GLint *size,
- GLenum *type, GLchar *nameOut)
-{
- const struct gl_program_parameter_list *attribs = NULL;
- struct gl_shader_program *shProg;
-
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveAttrib");
- if (!shProg)
- return;
-
- if (shProg->VertexProgram)
- attribs = shProg->VertexProgram->Base.Attributes;
-
- if (!attribs || index >= attribs->NumParameters) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveAttrib(index)");
- return;
- }
-
- _mesa_copy_string(nameOut, maxLength, length,
- attribs->Parameters[index].Name);
-
- if (size)
- *size = attribs->Parameters[index].Size
- / _mesa_sizeof_glsl_type(attribs->Parameters[index].DataType);
-
- if (type)
- *type = attribs->Parameters[index].DataType;
-}
-
-
-/**
- * Return list of shaders attached to shader program.
- */
-static void
-get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
- GLsizei *count, GLuint *obj)
-{
- struct gl_shader_program *shProg =
- _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
- if (shProg) {
- GLuint i;
- for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
- obj[i] = shProg->Shaders[i]->Name;
- }
- if (count)
- *count = i;
- }
-}
-
-
-static GLint
-get_frag_data_location(struct gl_context *ctx, GLuint program,
- const GLchar *name)
-{
- _mesa_problem(ctx, "get_frag_data_location() not implemented yet");
- return -1;
-}
-
-
-
-/**
- * glGetHandleARB() - return ID/name of currently bound shader program.
- */
-static GLuint
-get_handle(struct gl_context *ctx, GLenum pname)
-{
- if (pname == GL_PROGRAM_OBJECT_ARB) {
- if (ctx->Shader.ActiveProgram)
- return ctx->Shader.ActiveProgram->Name;
- else
- return 0;
- }
- else {
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
- return 0;
- }
-}
-
-
-/**
- * glGetProgramiv() - get shader program state.
- * Note that this is for GLSL shader programs, not ARB vertex/fragment
- * programs (see glGetProgramivARB).
- */
-static void
-get_programiv(struct gl_context *ctx, GLuint program, GLenum pname, GLint *params)
-{
- const struct gl_program_parameter_list *attribs;
- struct gl_shader_program *shProg
- = _mesa_lookup_shader_program(ctx, program);
-
- if (!shProg) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramiv(program)");
- return;
- }
-
- if (shProg->VertexProgram)
- attribs = shProg->VertexProgram->Base.Attributes;
- else
- attribs = NULL;
-
- switch (pname) {
- case GL_DELETE_STATUS:
- *params = shProg->DeletePending;
- break;
- case GL_LINK_STATUS:
- *params = shProg->LinkStatus;
- break;
- case GL_VALIDATE_STATUS:
- *params = shProg->Validated;
- break;
- case GL_INFO_LOG_LENGTH:
- *params = shProg->InfoLog ? strlen(shProg->InfoLog) + 1 : 0;
- break;
- case GL_ATTACHED_SHADERS:
- *params = shProg->NumShaders;
- break;
- case GL_ACTIVE_ATTRIBUTES:
- *params = attribs ? attribs->NumParameters : 0;
- break;
- case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
- *params = _mesa_longest_parameter_name(attribs, PROGRAM_INPUT) + 1;
- break;
- case GL_ACTIVE_UNIFORMS:
- *params = shProg->Uniforms ? shProg->Uniforms->NumUniforms : 0;
- break;
- case GL_ACTIVE_UNIFORM_MAX_LENGTH:
- *params = _mesa_longest_uniform_name(shProg->Uniforms);
- if (*params > 0)
- (*params)++; /* add one for terminating zero */
- break;
- case GL_PROGRAM_BINARY_LENGTH_OES:
- *params = 0;
- break;
-#if FEATURE_EXT_transform_feedback
- case GL_TRANSFORM_FEEDBACK_VARYINGS:
- *params = shProg->TransformFeedback.NumVarying;
- break;
- case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH:
- *params = longest_feedback_varying_name(shProg) + 1;
- break;
- case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
- *params = shProg->TransformFeedback.BufferMode;
- break;
-#endif
-#if FEATURE_ARB_geometry_shader4
- case GL_GEOMETRY_VERTICES_OUT_ARB:
- *params = shProg->Geom.VerticesOut;
- break;
- case GL_GEOMETRY_INPUT_TYPE_ARB:
- *params = shProg->Geom.InputType;
- break;
- case GL_GEOMETRY_OUTPUT_TYPE_ARB:
- *params = shProg->Geom.OutputType;
- break;
-#endif
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname)");
- return;
- }
-}
-
-
-/**
- * glGetShaderiv() - get GLSL shader state
- */
-static void
-get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
-{
- struct gl_shader *shader =
- _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
-
- if (!shader) {
- return;
- }
-
- switch (pname) {
- case GL_SHADER_TYPE:
- *params = shader->Type;
- break;
- case GL_DELETE_STATUS:
- *params = shader->DeletePending;
- break;
- case GL_COMPILE_STATUS:
- *params = shader->CompileStatus;
- break;
- case GL_INFO_LOG_LENGTH:
- *params = shader->InfoLog ? strlen(shader->InfoLog) + 1 : 0;
- break;
- case GL_SHADER_SOURCE_LENGTH:
- *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
- return;
- }
-}
-
-
-static void
-get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
- GLsizei *length, GLchar *infoLog)
-{
- struct gl_shader_program *shProg
- = _mesa_lookup_shader_program(ctx, program);
- if (!shProg) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(program)");
- return;
- }
- _mesa_copy_string(infoLog, bufSize, length, shProg->InfoLog);
-}
-
-
-static void
-get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
- GLsizei *length, GLchar *infoLog)
-{
- struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
- if (!sh) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(shader)");
- return;
- }
- _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
-}
-
-
-/**
- * Return shader source code.
- */
-static void
-get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
- GLsizei *length, GLchar *sourceOut)
-{
- struct gl_shader *sh;
- sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
- if (!sh) {
- return;
- }
- _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
-}
-
-
-/**
- * Set/replace shader source code.
- */
-static void
-shader_source(struct gl_context *ctx, GLuint shader, const GLchar *source)
-{
- struct gl_shader *sh;
-
- sh = _mesa_lookup_shader_err(ctx, shader, "glShaderSource");
- if (!sh)
- return;
-
- /* free old shader source string and install new one */
- if (sh->Source) {
- free((void *) sh->Source);
- }
- sh->Source = source;
- sh->CompileStatus = GL_FALSE;
-#ifdef DEBUG
- sh->SourceChecksum = _mesa_str_checksum(sh->Source);
-#endif
-}
-
-
-/**
- * Compile a shader.
- */
-static void
-compile_shader(struct gl_context *ctx, GLuint shaderObj)
-{
- struct gl_shader *sh;
- struct gl_shader_compiler_options *options;
-
- sh = _mesa_lookup_shader_err(ctx, shaderObj, "glCompileShader");
- if (!sh)
- return;
-
- options = &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(sh->Type)];
-
- /* set default pragma state for shader */
- sh->Pragmas = options->DefaultPragmas;
-
- /* this call will set the sh->CompileStatus field to indicate if
- * compilation was successful.
- */
- _mesa_glsl_compile_shader(ctx, sh);
-}
-
-
-/**
- * Link a program's shaders.
- */
-static void
-link_program(struct gl_context *ctx, GLuint program)
-{
- struct gl_shader_program *shProg;
- struct gl_transform_feedback_object *obj =
- ctx->TransformFeedback.CurrentObject;
-
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glLinkProgram");
- if (!shProg)
- return;
-
- if (obj->Active
- && (shProg == ctx->Shader.CurrentVertexProgram
- || shProg == ctx->Shader.CurrentGeometryProgram
- || shProg == ctx->Shader.CurrentFragmentProgram)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glLinkProgram(transform feedback active");
- return;
- }
-
- FLUSH_VERTICES(ctx, _NEW_PROGRAM);
-
- _mesa_glsl_link_shader(ctx, shProg);
-
- /* debug code */
- if (0) {
- GLuint i;
-
- printf("Link %u shaders in program %u: %s\n",
- shProg->NumShaders, shProg->Name,
- shProg->LinkStatus ? "Success" : "Failed");
-
- for (i = 0; i < shProg->NumShaders; i++) {
- printf(" shader %u, type 0x%x\n",
- shProg->Shaders[i]->Name,
- shProg->Shaders[i]->Type);
- }
- }
-}
-
-
-/**
- * Print basic shader info (for debug).
- */
-static void
-print_shader_info(const struct gl_shader_program *shProg)
-{
- GLuint i;
-
- printf("Mesa: glUseProgram(%u)\n", shProg->Name);
- for (i = 0; i < shProg->NumShaders; i++) {
- const char *s;
- switch (shProg->Shaders[i]->Type) {
- case GL_VERTEX_SHADER:
- s = "vertex";
- break;
- case GL_FRAGMENT_SHADER:
- s = "fragment";
- break;
- case GL_GEOMETRY_SHADER:
- s = "geometry";
- break;
- default:
- s = "";
- }
- printf(" %s shader %u, checksum %u\n", s,
- shProg->Shaders[i]->Name,
- shProg->Shaders[i]->SourceChecksum);
- }
- if (shProg->VertexProgram)
- printf(" vert prog %u\n", shProg->VertexProgram->Base.Id);
- if (shProg->FragmentProgram)
- printf(" frag prog %u\n", shProg->FragmentProgram->Base.Id);
-}
-
-
-/**
- * Use the named shader program for subsequent glUniform calls
- */
-void
-_mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
- const char *caller)
-{
- if ((shProg != NULL) && !shProg->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "%s(program %u not linked)", caller, shProg->Name);
- return;
- }
-
- if (ctx->Shader.ActiveProgram != shProg) {
- _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
- }
-}
-
-/**
- */
-static bool
-use_shader_program(struct gl_context *ctx, GLenum type,
- struct gl_shader_program *shProg)
-{
- struct gl_shader_program **target;
-
- switch (type) {
-#if FEATURE_ARB_vertex_shader
- case GL_VERTEX_SHADER:
- target = &ctx->Shader.CurrentVertexProgram;
- if ((shProg == NULL)
- || (shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL)) {
- shProg = NULL;
- }
- break;
-#endif
-#if FEATURE_ARB_geometry_shader4
- case GL_GEOMETRY_SHADER_ARB:
- target = &ctx->Shader.CurrentGeometryProgram;
- if ((shProg == NULL)
- || (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] == NULL)) {
- shProg = NULL;
- }
- break;
-#endif
-#if FEATURE_ARB_fragment_shader
- case GL_FRAGMENT_SHADER:
- target = &ctx->Shader.CurrentFragmentProgram;
- if ((shProg == NULL)
- || (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL)) {
- shProg = NULL;
- }
- break;
-#endif
- default:
- return false;
- }
-
- if (*target != shProg) {
- FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS);
- _mesa_reference_shader_program(ctx, target, shProg);
- return true;
- }
-
- return false;
-}
-
-/**
- * Use the named shader program for subsequent rendering.
- */
-void
-_mesa_use_program(struct gl_context *ctx, struct gl_shader_program *shProg)
-{
- use_shader_program(ctx, GL_VERTEX_SHADER, shProg);
- use_shader_program(ctx, GL_GEOMETRY_SHADER_ARB, shProg);
- use_shader_program(ctx, GL_FRAGMENT_SHADER, shProg);
- _mesa_active_program(ctx, shProg, "glUseProgram");
-
- if (ctx->Driver.UseProgram)
- ctx->Driver.UseProgram(ctx, shProg);
-}
-
-
-/**
- * Validate a program's samplers.
- * Specifically, check that there aren't two samplers of different types
- * pointing to the same texture unit.
- * \return GL_TRUE if valid, GL_FALSE if invalid
- */
-static GLboolean
-validate_samplers(const struct gl_program *prog, char *errMsg)
-{
- static const char *targetName[] = {
- "TEXTURE_2D_ARRAY",
- "TEXTURE_1D_ARRAY",
- "TEXTURE_CUBE",
- "TEXTURE_3D",
- "TEXTURE_RECT",
- "TEXTURE_2D",
- "TEXTURE_1D",
- };
- GLint targetUsed[MAX_TEXTURE_IMAGE_UNITS];
- GLbitfield samplersUsed = prog->SamplersUsed;
- GLuint i;
-
- assert(Elements(targetName) == NUM_TEXTURE_TARGETS);
-
- if (samplersUsed == 0x0)
- return GL_TRUE;
-
- for (i = 0; i < Elements(targetUsed); i++)
- targetUsed[i] = -1;
-
- /* walk over bits which are set in 'samplers' */
- while (samplersUsed) {
- GLuint unit;
- gl_texture_index target;
- GLint sampler = _mesa_ffs(samplersUsed) - 1;
- assert(sampler >= 0);
- assert(sampler < MAX_TEXTURE_IMAGE_UNITS);
- unit = prog->SamplerUnits[sampler];
- target = prog->SamplerTargets[sampler];
- if (targetUsed[unit] != -1 && targetUsed[unit] != (int) target) {
- _mesa_snprintf(errMsg, 100,
- "Texture unit %d is accessed both as %s and %s",
- unit, targetName[targetUsed[unit]], targetName[target]);
- return GL_FALSE;
- }
- targetUsed[unit] = target;
- samplersUsed ^= (1 << sampler);
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Do validation of the given shader program.
- * \param errMsg returns error message if validation fails.
- * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
- */
-static GLboolean
-validate_shader_program(const struct gl_shader_program *shProg,
- char *errMsg)
-{
- const struct gl_vertex_program *vp = shProg->VertexProgram;
- const struct gl_fragment_program *fp = shProg->FragmentProgram;
-
- if (!shProg->LinkStatus) {
- return GL_FALSE;
- }
-
- /* From the GL spec, a program is invalid if any of these are true:
-
- any two active samplers in the current program object are of
- different types, but refer to the same texture image unit,
-
- any active sampler in the current program object refers to a texture
- image unit where fixed-function fragment processing accesses a
- texture target that does not match the sampler type, or
-
- the sum of the number of active samplers in the program and the
- number of texture image units enabled for fixed-function fragment
- processing exceeds the combined limit on the total number of texture
- image units allowed.
- */
-
-
- /*
- * Check: any two active samplers in the current program object are of
- * different types, but refer to the same texture image unit,
- */
- if (vp && !validate_samplers(&vp->Base, errMsg)) {
- return GL_FALSE;
- }
- if (fp && !validate_samplers(&fp->Base, errMsg)) {
- return GL_FALSE;
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Called via glValidateProgram()
- */
-static void
-validate_program(struct gl_context *ctx, GLuint program)
-{
- struct gl_shader_program *shProg;
- char errMsg[100];
-
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
- if (!shProg) {
- return;
- }
-
- shProg->Validated = validate_shader_program(shProg, errMsg);
- if (!shProg->Validated) {
- /* update info log */
- if (shProg->InfoLog) {
- ralloc_free(shProg->InfoLog);
- }
- shProg->InfoLog = ralloc_strdup(shProg, errMsg);
- }
-}
-
-
-
-void GLAPIENTRY
-_mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
-{
- GET_CURRENT_CONTEXT(ctx);
- attach_shader(ctx, program, shader);
-}
-
-
-void GLAPIENTRY
-_mesa_AttachShader(GLuint program, GLuint shader)
-{
- GET_CURRENT_CONTEXT(ctx);
- attach_shader(ctx, program, shader);
-}
-
-
-void GLAPIENTRY
-_mesa_BindAttribLocationARB(GLhandleARB program, GLuint index,
- const GLcharARB *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- bind_attrib_location(ctx, program, index, name);
-}
-
-
-/* GL_EXT_gpu_shader4, GL3 */
-void GLAPIENTRY
-_mesa_BindFragDataLocation(GLuint program, GLuint colorNumber,
- const GLchar *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- bind_frag_data_location(ctx, program, colorNumber, name);
-}
-
-
-void GLAPIENTRY
-_mesa_CompileShaderARB(GLhandleARB shaderObj)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
- compile_shader(ctx, shaderObj);
-}
-
-
-GLuint GLAPIENTRY
-_mesa_CreateShader(GLenum type)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glCreateShader %s\n", _mesa_lookup_enum_by_nr(type));
- return create_shader(ctx, type);
-}
-
-
-GLhandleARB GLAPIENTRY
-_mesa_CreateShaderObjectARB(GLenum type)
-{
- GET_CURRENT_CONTEXT(ctx);
- return create_shader(ctx, type);
-}
-
-
-GLuint GLAPIENTRY
-_mesa_CreateProgram(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glCreateProgram\n");
- return create_shader_program(ctx);
-}
-
-
-GLhandleARB GLAPIENTRY
-_mesa_CreateProgramObjectARB(void)
-{
- GET_CURRENT_CONTEXT(ctx);
- return create_shader_program(ctx);
-}
-
-
-void GLAPIENTRY
-_mesa_DeleteObjectARB(GLhandleARB obj)
-{
- if (MESA_VERBOSE & VERBOSE_API) {
- GET_CURRENT_CONTEXT(ctx);
- _mesa_debug(ctx, "glDeleteObjectARB(%u)\n", obj);
- }
-
- if (obj) {
- GET_CURRENT_CONTEXT(ctx);
- if (is_program(ctx, obj)) {
- delete_shader_program(ctx, obj);
- }
- else if (is_shader(ctx, obj)) {
- delete_shader(ctx, obj);
- }
- else {
- /* error? */
- }
- }
-}
-
-
-void GLAPIENTRY
-_mesa_DeleteProgram(GLuint name)
-{
- if (name) {
- GET_CURRENT_CONTEXT(ctx);
- delete_shader_program(ctx, name);
- }
-}
-
-
-void GLAPIENTRY
-_mesa_DeleteShader(GLuint name)
-{
- if (name) {
- GET_CURRENT_CONTEXT(ctx);
- delete_shader(ctx, name);
- }
-}
-
-
-void GLAPIENTRY
-_mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
-{
- GET_CURRENT_CONTEXT(ctx);
- detach_shader(ctx, program, shader);
-}
-
-
-void GLAPIENTRY
-_mesa_DetachShader(GLuint program, GLuint shader)
-{
- GET_CURRENT_CONTEXT(ctx);
- detach_shader(ctx, program, shader);
-}
-
-
-void GLAPIENTRY
-_mesa_GetActiveAttribARB(GLhandleARB program, GLuint index,
- GLsizei maxLength, GLsizei * length, GLint * size,
- GLenum * type, GLcharARB * name)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_active_attrib(ctx, program, index, maxLength, length, size, type, name);
-}
-
-
-void GLAPIENTRY
-_mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
- GLsizei * count, GLhandleARB * obj)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_attached_shaders(ctx, container, maxCount, count, obj);
-}
-
-
-void GLAPIENTRY
-_mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
- GLsizei *count, GLuint *obj)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_attached_shaders(ctx, program, maxCount, count, obj);
-}
-
-
-GLint GLAPIENTRY
-_mesa_GetAttribLocationARB(GLhandleARB program, const GLcharARB * name)
-{
- GET_CURRENT_CONTEXT(ctx);
- return get_attrib_location(ctx, program, name);
-}
-
-
-/* GL_EXT_gpu_shader4, GL3 */
-GLint GLAPIENTRY
-_mesa_GetFragDataLocation(GLuint program, const GLchar *name)
-{
- GET_CURRENT_CONTEXT(ctx);
- return get_frag_data_location(ctx, program, name);
-}
-
-
-
-void GLAPIENTRY
-_mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
- GLcharARB * infoLog)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (is_program(ctx, object)) {
- get_program_info_log(ctx, object, maxLength, length, infoLog);
- }
- else if (is_shader(ctx, object)) {
- get_shader_info_log(ctx, object, maxLength, length, infoLog);
- }
- else {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- /* Implement in terms of GetProgramiv, GetShaderiv */
- if (is_program(ctx, object)) {
- if (pname == GL_OBJECT_TYPE_ARB) {
- *params = GL_PROGRAM_OBJECT_ARB;
- }
- else {
- get_programiv(ctx, object, pname, params);
- }
- }
- else if (is_shader(ctx, object)) {
- if (pname == GL_OBJECT_TYPE_ARB) {
- *params = GL_SHADER_OBJECT_ARB;
- }
- else {
- get_shaderiv(ctx, object, pname, params);
- }
- }
- else {
- _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
- }
-}
-
-
-void GLAPIENTRY
-_mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
- GLfloat *params)
-{
- GLint iparams[1]; /* XXX is one element enough? */
- _mesa_GetObjectParameterivARB(object, pname, iparams);
- params[0] = (GLfloat) iparams[0];
-}
-
-
-void GLAPIENTRY
-_mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_programiv(ctx, program, pname, params);
-}
-
-
-void GLAPIENTRY
-_mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_shaderiv(ctx, shader, pname, params);
-}
-
-
-void GLAPIENTRY
-_mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
- GLsizei *length, GLchar *infoLog)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_program_info_log(ctx, program, bufSize, length, infoLog);
-}
-
-
-void GLAPIENTRY
-_mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
- GLsizei *length, GLchar *infoLog)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_shader_info_log(ctx, shader, bufSize, length, infoLog);
-}
-
-
-void GLAPIENTRY
-_mesa_GetShaderSourceARB(GLhandleARB shader, GLsizei maxLength,
- GLsizei *length, GLcharARB *sourceOut)
-{
- GET_CURRENT_CONTEXT(ctx);
- get_shader_source(ctx, shader, maxLength, length, sourceOut);
-}
-
-
-GLhandleARB GLAPIENTRY
-_mesa_GetHandleARB(GLenum pname)
-{
- GET_CURRENT_CONTEXT(ctx);
- return get_handle(ctx, pname);
-}
-
-
-GLboolean GLAPIENTRY
-_mesa_IsProgram(GLuint name)
-{
- GET_CURRENT_CONTEXT(ctx);
- return is_program(ctx, name);
-}
-
-
-GLboolean GLAPIENTRY
-_mesa_IsShader(GLuint name)
-{
- GET_CURRENT_CONTEXT(ctx);
- return is_shader(ctx, name);
-}
-
-
-void GLAPIENTRY
-_mesa_LinkProgramARB(GLhandleARB programObj)
-{
- GET_CURRENT_CONTEXT(ctx);
- link_program(ctx, programObj);
-}
-
-
-
-/**
- * Read shader source code from a file.
- * Useful for debugging to override an app's shader.
- */
-static GLcharARB *
-read_shader(const char *fname)
-{
- const int max = 50*1000;
- FILE *f = fopen(fname, "r");
- GLcharARB *buffer, *shader;
- int len;
-
- if (!f) {
- return NULL;
- }
-
- buffer = (char *) malloc(max);
- len = fread(buffer, 1, max, f);
- buffer[len] = 0;
-
- fclose(f);
-
- shader = _mesa_strdup(buffer);
- free(buffer);
-
- return shader;
-}
-
-
-/**
- * Called via glShaderSource() and glShaderSourceARB() API functions.
- * Basically, concatenate the source code strings into one long string
- * and pass it to _mesa_shader_source().
- */
-void GLAPIENTRY
-_mesa_ShaderSourceARB(GLhandleARB shaderObj, GLsizei count,
- const GLcharARB ** string, const GLint * length)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint *offsets;
- GLsizei i, totalLength;
- GLcharARB *source;
- GLuint checksum;
-
- if (!shaderObj || string == NULL) {
- _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
- return;
- }
-
- /*
- * This array holds offsets of where the appropriate string ends, thus the
- * last element will be set to the total length of the source code.
- */
- offsets = (GLint *) malloc(count * sizeof(GLint));
- if (offsets == NULL) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
- return;
- }
-
- for (i = 0; i < count; i++) {
- if (string[i] == NULL) {
- free((GLvoid *) offsets);
- _mesa_error(ctx, GL_INVALID_OPERATION, "glShaderSourceARB(null string)");
- return;
- }
- if (length == NULL || length[i] < 0)
- offsets[i] = strlen(string[i]);
- else
- offsets[i] = length[i];
- /* accumulate string lengths */
- if (i > 0)
- offsets[i] += offsets[i - 1];
- }
-
- /* Total length of source string is sum off all strings plus two.
- * One extra byte for terminating zero, another extra byte to silence
- * valgrind warnings in the parser/grammer code.
- */
- totalLength = offsets[count - 1] + 2;
- source = (GLcharARB *) malloc(totalLength * sizeof(GLcharARB));
- if (source == NULL) {
- free((GLvoid *) offsets);
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
- return;
- }
-
- for (i = 0; i < count; i++) {
- GLint start = (i > 0) ? offsets[i - 1] : 0;
- memcpy(source + start, string[i],
- (offsets[i] - start) * sizeof(GLcharARB));
- }
- source[totalLength - 1] = '\0';
- source[totalLength - 2] = '\0';
-
- if (SHADER_SUBST) {
- /* Compute the shader's source code checksum then try to open a file
- * named newshader_<CHECKSUM>. If it exists, use it in place of the
- * original shader source code. For debugging.
- */
- char filename[100];
- GLcharARB *newSource;
-
- checksum = _mesa_str_checksum(source);
-
- _mesa_snprintf(filename, sizeof(filename), "newshader_%d", checksum);
-
- newSource = read_shader(filename);
- if (newSource) {
- fprintf(stderr, "Mesa: Replacing shader %u chksum=%d with %s\n",
- shaderObj, checksum, filename);
- free(source);
- source = newSource;
- }
- }
-
- shader_source(ctx, shaderObj, source);
-
- if (SHADER_SUBST) {
- struct gl_shader *sh = _mesa_lookup_shader(ctx, shaderObj);
- if (sh)
- sh->SourceChecksum = checksum; /* save original checksum */
- }
-
- free(offsets);
-}
-
-
-void GLAPIENTRY
-_mesa_UseProgramObjectARB(GLhandleARB program)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_shader_program *shProg;
- struct gl_transform_feedback_object *obj =
- ctx->TransformFeedback.CurrentObject;
-
- if (obj->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glUseProgram(transform feedback active)");
- return;
- }
-
- if (program) {
- shProg = _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
- if (!shProg) {
- return;
- }
- if (!shProg->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glUseProgram(program %u not linked)", program);
- return;
- }
-
- /* debug code */
- if (ctx->Shader.Flags & GLSL_USE_PROG) {
- print_shader_info(shProg);
- }
- }
- else {
- shProg = NULL;
- }
-
- _mesa_use_program(ctx, shProg);
-}
-
-
-void GLAPIENTRY
-_mesa_ValidateProgramARB(GLhandleARB program)
-{
- GET_CURRENT_CONTEXT(ctx);
- validate_program(ctx, program);
-}
-
-#ifdef FEATURE_ES2
-
-void GLAPIENTRY
-_mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
- GLint* range, GLint* precision)
-{
- const struct gl_program_constants *limits;
- const struct gl_precision *p;
- GET_CURRENT_CONTEXT(ctx);
-
- switch (shadertype) {
- case GL_VERTEX_SHADER:
- limits = &ctx->Const.VertexProgram;
- break;
- case GL_FRAGMENT_SHADER:
- limits = &ctx->Const.FragmentProgram;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetShaderPrecisionFormat(shadertype)");
- return;
- }
-
- switch (precisiontype) {
- case GL_LOW_FLOAT:
- p = &limits->LowFloat;
- break;
- case GL_MEDIUM_FLOAT:
- p = &limits->MediumFloat;
- break;
- case GL_HIGH_FLOAT:
- p = &limits->HighFloat;
- break;
- case GL_LOW_INT:
- p = &limits->LowInt;
- break;
- case GL_MEDIUM_INT:
- p = &limits->MediumInt;
- break;
- case GL_HIGH_INT:
- p = &limits->HighInt;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glGetShaderPrecisionFormat(precisiontype)");
- return;
- }
-
- range[0] = p->RangeMin;
- range[1] = p->RangeMax;
- precision[0] = p->Precision;
-}
-
-
-void GLAPIENTRY
-_mesa_ReleaseShaderCompiler(void)
-{
- _mesa_destroy_shader_compiler_caches();
-}
-
-
-void GLAPIENTRY
-_mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
- const void* binary, GLint length)
-{
- GET_CURRENT_CONTEXT(ctx);
- (void) n;
- (void) shaders;
- (void) binaryformat;
- (void) binary;
- (void) length;
- _mesa_error(ctx, GL_INVALID_OPERATION, __FUNCTION__);
-}
-
-#endif /* FEATURE_ES2 */
-
-
-#if FEATURE_ARB_geometry_shader4
-
-void GLAPIENTRY
-_mesa_ProgramParameteriARB(GLuint program, GLenum pname,
- GLint value)
-{
- struct gl_shader_program *shProg;
- GET_CURRENT_CONTEXT(ctx);
-
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- shProg = _mesa_lookup_shader_program_err(ctx, program,
- "glProgramParameteri");
- if (!shProg)
- return;
-
- switch (pname) {
- case GL_GEOMETRY_VERTICES_OUT_ARB:
- if (value < 1 ||
- (unsigned) value > ctx->Const.GeometryProgram.MaxGeometryOutputVertices) {
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glProgramParameteri(GL_GEOMETRY_VERTICES_OUT_ARB=%d",
- value);
- return;
- }
- shProg->Geom.VerticesOut = value;
- break;
- case GL_GEOMETRY_INPUT_TYPE_ARB:
- switch (value) {
- case GL_POINTS:
- case GL_LINES:
- case GL_LINES_ADJACENCY_ARB:
- case GL_TRIANGLES:
- case GL_TRIANGLES_ADJACENCY_ARB:
- shProg->Geom.InputType = value;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glProgramParameteri(geometry input type = %s",
- _mesa_lookup_enum_by_nr(value));
- return;
- }
- break;
- case GL_GEOMETRY_OUTPUT_TYPE_ARB:
- switch (value) {
- case GL_POINTS:
- case GL_LINE_STRIP:
- case GL_TRIANGLE_STRIP:
- shProg->Geom.OutputType = value;
- break;
- default:
- _mesa_error(ctx, GL_INVALID_VALUE,
- "glProgramParameteri(geometry output type = %s",
- _mesa_lookup_enum_by_nr(value));
- return;
- }
- break;
- default:
- _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteriARB(pname=%s)",
- _mesa_lookup_enum_by_nr(pname));
- break;
- }
-}
-
-#endif
-
-void
-_mesa_use_shader_program(struct gl_context *ctx, GLenum type,
- struct gl_shader_program *shProg)
-{
- use_shader_program(ctx, type, shProg);
-
- if (ctx->Driver.UseProgram)
- ctx->Driver.UseProgram(ctx, shProg);
-}
-
-void GLAPIENTRY
-_mesa_UseShaderProgramEXT(GLenum type, GLuint program)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_shader_program *shProg = NULL;
-
- if (!validate_shader_target(ctx, type)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glUseShaderProgramEXT(type)");
- return;
- }
-
- if (ctx->TransformFeedback.CurrentObject->Active) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glUseShaderProgramEXT(transform feedback is active)");
- return;
- }
-
- if (program) {
- shProg = _mesa_lookup_shader_program_err(ctx, program,
- "glUseShaderProgramEXT");
- if (shProg == NULL)
- return;
-
- if (!shProg->LinkStatus) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glUseShaderProgramEXT(program not linked)");
- return;
- }
- }
-
- _mesa_use_shader_program(ctx, type, shProg);
-}
-
-void GLAPIENTRY
-_mesa_ActiveProgramEXT(GLuint program)
-{
- GET_CURRENT_CONTEXT(ctx);
- struct gl_shader_program *shProg = (program != 0)
- ? _mesa_lookup_shader_program_err(ctx, program, "glActiveProgramEXT")
- : NULL;
-
- _mesa_active_program(ctx, shProg, "glActiveProgramEXT");
- return;
-}
-
-GLuint GLAPIENTRY
-_mesa_CreateShaderProgramEXT(GLenum type, const GLchar *string)
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLuint shader = create_shader(ctx, type);
- GLuint program = 0;
-
- if (shader) {
- shader_source(ctx, shader, _mesa_strdup(string));
- compile_shader(ctx, shader);
-
- program = create_shader_program(ctx);
- if (program) {
- struct gl_shader_program *shProg;
- struct gl_shader *sh;
- GLint compiled = GL_FALSE;
-
- shProg = _mesa_lookup_shader_program(ctx, program);
- sh = _mesa_lookup_shader(ctx, shader);
-
- get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
- if (compiled) {
- attach_shader(ctx, program, shader);
- link_program(ctx, program);
- detach_shader(ctx, program, shader);
-
-#if 0
- /* Possibly... */
- if (active-user-defined-varyings-in-linked-program) {
- append-error-to-info-log;
- shProg->LinkStatus = GL_FALSE;
- }
-#endif
- }
-
- ralloc_strcat(&shProg->InfoLog, sh->InfoLog);
- }
-
- delete_shader(ctx, shader);
- }
-
- return program;
-}
-
-/**
- * Plug in shader-related functions into API dispatch table.
- */
-void
-_mesa_init_shader_dispatch(struct _glapi_table *exec)
-{
-#if FEATURE_GL
- /* GL_ARB_vertex/fragment_shader */
- SET_DeleteObjectARB(exec, _mesa_DeleteObjectARB);
- SET_GetHandleARB(exec, _mesa_GetHandleARB);
- SET_DetachObjectARB(exec, _mesa_DetachObjectARB);
- SET_CreateShaderObjectARB(exec, _mesa_CreateShaderObjectARB);
- SET_ShaderSourceARB(exec, _mesa_ShaderSourceARB);
- SET_CompileShaderARB(exec, _mesa_CompileShaderARB);
- SET_CreateProgramObjectARB(exec, _mesa_CreateProgramObjectARB);
- SET_AttachObjectARB(exec, _mesa_AttachObjectARB);
- SET_LinkProgramARB(exec, _mesa_LinkProgramARB);
- SET_UseProgramObjectARB(exec, _mesa_UseProgramObjectARB);
- SET_ValidateProgramARB(exec, _mesa_ValidateProgramARB);
- SET_GetObjectParameterfvARB(exec, _mesa_GetObjectParameterfvARB);
- SET_GetObjectParameterivARB(exec, _mesa_GetObjectParameterivARB);
- SET_GetInfoLogARB(exec, _mesa_GetInfoLogARB);
- SET_GetAttachedObjectsARB(exec, _mesa_GetAttachedObjectsARB);
- SET_GetShaderSourceARB(exec, _mesa_GetShaderSourceARB);
-
- /* OpenGL 2.0 */
- SET_AttachShader(exec, _mesa_AttachShader);
- SET_CreateProgram(exec, _mesa_CreateProgram);
- SET_CreateShader(exec, _mesa_CreateShader);
- SET_DeleteProgram(exec, _mesa_DeleteProgram);
- SET_DeleteShader(exec, _mesa_DeleteShader);
- SET_DetachShader(exec, _mesa_DetachShader);
- SET_GetAttachedShaders(exec, _mesa_GetAttachedShaders);
- SET_GetProgramiv(exec, _mesa_GetProgramiv);
- SET_GetProgramInfoLog(exec, _mesa_GetProgramInfoLog);
- SET_GetShaderiv(exec, _mesa_GetShaderiv);
- SET_GetShaderInfoLog(exec, _mesa_GetShaderInfoLog);
- SET_IsProgram(exec, _mesa_IsProgram);
- SET_IsShader(exec, _mesa_IsShader);
-
-#if FEATURE_ARB_vertex_shader
- SET_BindAttribLocationARB(exec, _mesa_BindAttribLocationARB);
- SET_GetActiveAttribARB(exec, _mesa_GetActiveAttribARB);
- SET_GetAttribLocationARB(exec, _mesa_GetAttribLocationARB);
-#endif
-
-#if FEATURE_ARB_geometry_shader4
- SET_ProgramParameteriARB(exec, _mesa_ProgramParameteriARB);
-#endif
-
- SET_UseShaderProgramEXT(exec, _mesa_UseShaderProgramEXT);
- SET_ActiveProgramEXT(exec, _mesa_ActiveProgramEXT);
- SET_CreateShaderProgramEXT(exec, _mesa_CreateShaderProgramEXT);
-
- /* GL_EXT_gpu_shader4 / GL 3.0 */
- SET_BindFragDataLocationEXT(exec, _mesa_BindFragDataLocation);
- SET_GetFragDataLocationEXT(exec, _mesa_GetFragDataLocation);
-
- /* GL_ARB_ES2_compatibility */
- SET_ReleaseShaderCompiler(exec, _mesa_ReleaseShaderCompiler);
- SET_GetShaderPrecisionFormat(exec, _mesa_GetShaderPrecisionFormat);
-
-#endif /* FEATURE_GL */
-}
-
+/*
+ * Mesa 3-D graphics library
+ *
+ * Copyright (C) 2004-2008 Brian Paul All Rights Reserved.
+ * Copyright (C) 2009-2010 VMware, Inc. 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 shaderapi.c
+ * \author Brian Paul
+ *
+ * Implementation of GLSL-related API functions.
+ * The glUniform* functions are in uniforms.c
+ *
+ *
+ * XXX things to do:
+ * 1. Check that the right error code is generated for all _mesa_error() calls.
+ * 2. Insert FLUSH_VERTICES calls in various places
+ */
+
+
+#include "main/glheader.h"
+#include "main/context.h"
+#include "main/dispatch.h"
+#include "main/enums.h"
+#include "main/hash.h"
+#include "main/mfeatures.h"
+#include "main/mtypes.h"
+#include "main/shaderapi.h"
+#include "main/shaderobj.h"
+#include "program/program.h"
+#include "program/prog_parameter.h"
+#include "program/prog_uniform.h"
+#include "ralloc.h"
+#include <stdbool.h>
+#include "../glsl/glsl_parser_extras.h"
+
+/** Define this to enable shader substitution (see below) */
+#define SHADER_SUBST 0
+
+
+/**
+ * Return mask of GLSL_x flags by examining the MESA_GLSL env var.
+ */
+static GLbitfield
+get_shader_flags(void)
+{
+ GLbitfield flags = 0x0;
+ const char *env = _mesa_getenv("MESA_GLSL");
+
+ if (env) {
+ if (strstr(env, "dump"))
+ flags |= GLSL_DUMP;
+ if (strstr(env, "log"))
+ flags |= GLSL_LOG;
+ if (strstr(env, "nopvert"))
+ flags |= GLSL_NOP_VERT;
+ if (strstr(env, "nopfrag"))
+ flags |= GLSL_NOP_FRAG;
+ if (strstr(env, "nopt"))
+ flags |= GLSL_NO_OPT;
+ else if (strstr(env, "opt"))
+ flags |= GLSL_OPT;
+ if (strstr(env, "uniform"))
+ flags |= GLSL_UNIFORMS;
+ if (strstr(env, "useprog"))
+ flags |= GLSL_USE_PROG;
+ }
+
+ return flags;
+}
+
+
+/**
+ * Initialize context's shader state.
+ */
+void
+_mesa_init_shader_state(struct gl_context *ctx)
+{
+ /* Device drivers may override these to control what kind of instructions
+ * are generated by the GLSL compiler.
+ */
+ struct gl_shader_compiler_options options;
+ gl_shader_type sh;
+
+ memset(&options, 0, sizeof(options));
+ options.MaxUnrollIterations = 32;
+
+ /* Default pragma settings */
+ options.DefaultPragmas.Optimize = GL_TRUE;
+
+ for (sh = 0; sh < MESA_SHADER_TYPES; ++sh)
+ memcpy(&ctx->ShaderCompilerOptions[sh], &options, sizeof(options));
+
+ ctx->Shader.Flags = get_shader_flags();
+}
+
+
+/**
+ * Free the per-context shader-related state.
+ */
+void
+_mesa_free_shader_state(struct gl_context *ctx)
+{
+ _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentVertexProgram, NULL);
+ _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentGeometryProgram,
+ NULL);
+ _mesa_reference_shader_program(ctx, &ctx->Shader.CurrentFragmentProgram,
+ NULL);
+ _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, NULL);
+}
+
+
+/**
+ * Return the size of the given GLSL datatype, in floats (components).
+ */
+GLint
+_mesa_sizeof_glsl_type(GLenum type)
+{
+ switch (type) {
+ case GL_FLOAT:
+ case GL_INT:
+ case GL_BOOL:
+ case GL_SAMPLER_1D:
+ case GL_SAMPLER_2D:
+ case GL_SAMPLER_3D:
+ case GL_SAMPLER_CUBE:
+ case GL_SAMPLER_1D_SHADOW:
+ case GL_SAMPLER_2D_SHADOW:
+ case GL_SAMPLER_2D_RECT_ARB:
+ case GL_SAMPLER_2D_RECT_SHADOW_ARB:
+ case GL_SAMPLER_1D_ARRAY_EXT:
+ case GL_SAMPLER_2D_ARRAY_EXT:
+ case GL_SAMPLER_1D_ARRAY_SHADOW_EXT:
+ case GL_SAMPLER_2D_ARRAY_SHADOW_EXT:
+ case GL_SAMPLER_CUBE_SHADOW_EXT:
+ return 1;
+ case GL_FLOAT_VEC2:
+ case GL_INT_VEC2:
+ case GL_UNSIGNED_INT_VEC2:
+ case GL_BOOL_VEC2:
+ return 2;
+ case GL_FLOAT_VEC3:
+ case GL_INT_VEC3:
+ case GL_UNSIGNED_INT_VEC3:
+ case GL_BOOL_VEC3:
+ return 3;
+ case GL_FLOAT_VEC4:
+ case GL_INT_VEC4:
+ case GL_UNSIGNED_INT_VEC4:
+ case GL_BOOL_VEC4:
+ return 4;
+ case GL_FLOAT_MAT2:
+ case GL_FLOAT_MAT2x3:
+ case GL_FLOAT_MAT2x4:
+ return 8; /* two float[4] vectors */
+ case GL_FLOAT_MAT3:
+ case GL_FLOAT_MAT3x2:
+ case GL_FLOAT_MAT3x4:
+ return 12; /* three float[4] vectors */
+ case GL_FLOAT_MAT4:
+ case GL_FLOAT_MAT4x2:
+ case GL_FLOAT_MAT4x3:
+ return 16; /* four float[4] vectors */
+ default:
+ _mesa_problem(NULL, "Invalid type in _mesa_sizeof_glsl_type()");
+ return 1;
+ }
+}
+
+
+/**
+ * Copy string from <src> to <dst>, up to maxLength characters, returning
+ * length of <dst> in <length>.
+ * \param src the strings source
+ * \param maxLength max chars to copy
+ * \param length returns number of chars copied
+ * \param dst the string destination
+ */
+void
+_mesa_copy_string(GLchar *dst, GLsizei maxLength,
+ GLsizei *length, const GLchar *src)
+{
+ GLsizei len;
+ for (len = 0; len < maxLength - 1 && src && src[len]; len++)
+ dst[len] = src[len];
+ if (maxLength > 0)
+ dst[len] = 0;
+ if (length)
+ *length = len;
+}
+
+
+
+/**
+ * Confirm that the a shader type is valid and supported by the implementation
+ *
+ * \param ctx Current GL context
+ * \param type Shader target
+ *
+ */
+static bool
+validate_shader_target(const struct gl_context *ctx, GLenum type)
+{
+ switch (type) {
+#if FEATURE_ARB_fragment_shader
+ case GL_FRAGMENT_SHADER:
+ return ctx->Extensions.ARB_fragment_shader;
+#endif
+#if FEATURE_ARB_vertex_shader
+ case GL_VERTEX_SHADER:
+ return ctx->Extensions.ARB_vertex_shader;
+#endif
+#if FEATURE_ARB_geometry_shader4
+ case GL_GEOMETRY_SHADER_ARB:
+ return ctx->Extensions.ARB_geometry_shader4;
+#endif
+ default:
+ return false;
+ }
+}
+
+
+/**
+ * Find the length of the longest transform feedback varying name
+ * which was specified with glTransformFeedbackVaryings().
+ */
+static GLint
+longest_feedback_varying_name(const struct gl_shader_program *shProg)
+{
+ GLuint i;
+ GLint max = 0;
+ for (i = 0; i < shProg->TransformFeedback.NumVarying; i++) {
+ GLint len = strlen(shProg->TransformFeedback.VaryingNames[i]);
+ if (len > max)
+ max = len;
+ }
+ return max;
+}
+
+
+
+static GLboolean
+is_program(struct gl_context *ctx, GLuint name)
+{
+ struct gl_shader_program *shProg = _mesa_lookup_shader_program(ctx, name);
+ return shProg ? GL_TRUE : GL_FALSE;
+}
+
+
+static GLboolean
+is_shader(struct gl_context *ctx, GLuint name)
+{
+ struct gl_shader *shader = _mesa_lookup_shader(ctx, name);
+ return shader ? GL_TRUE : GL_FALSE;
+}
+
+
+/**
+ * Attach shader to a shader program.
+ */
+static void
+attach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
+{
+ struct gl_shader_program *shProg;
+ struct gl_shader *sh;
+ GLuint i, n;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glAttachShader");
+ if (!shProg)
+ return;
+
+ sh = _mesa_lookup_shader_err(ctx, shader, "glAttachShader");
+ if (!sh) {
+ return;
+ }
+
+ n = shProg->NumShaders;
+ for (i = 0; i < n; i++) {
+ if (shProg->Shaders[i] == sh) {
+ /* The shader is already attched to this program. The
+ * GL_ARB_shader_objects spec says:
+ *
+ * "The error INVALID_OPERATION is generated by AttachObjectARB
+ * if <obj> is already attached to <containerObj>."
+ */
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glAttachShader");
+ return;
+ }
+ }
+
+ /* grow list */
+ shProg->Shaders = (struct gl_shader **)
+ _mesa_realloc(shProg->Shaders,
+ n * sizeof(struct gl_shader *),
+ (n + 1) * sizeof(struct gl_shader *));
+ if (!shProg->Shaders) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAttachShader");
+ return;
+ }
+
+ /* append */
+ shProg->Shaders[n] = NULL; /* since realloc() didn't zero the new space */
+ _mesa_reference_shader(ctx, &shProg->Shaders[n], sh);
+ shProg->NumShaders++;
+}
+
+
+static GLint
+get_attrib_location(struct gl_context *ctx, GLuint program, const GLchar *name)
+{
+ struct gl_shader_program *shProg
+ = _mesa_lookup_shader_program_err(ctx, program, "glGetAttribLocation");
+
+ if (!shProg) {
+ return -1;
+ }
+
+ if (!shProg->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glGetAttribLocation(program not linked)");
+ return -1;
+ }
+
+ if (!name)
+ return -1;
+
+ if (shProg->VertexProgram) {
+ const struct gl_program_parameter_list *attribs =
+ shProg->VertexProgram->Base.Attributes;
+ if (attribs) {
+ GLint i = _mesa_lookup_parameter_index(attribs, -1, name);
+ if (i >= 0) {
+ return attribs->Parameters[i].StateIndexes[0];
+ }
+ }
+ }
+ return -1;
+}
+
+
+static void
+bind_attrib_location(struct gl_context *ctx, GLuint program, GLuint index,
+ const GLchar *name)
+{
+ struct gl_shader_program *shProg;
+ const GLint size = -1; /* unknown size */
+ GLint i, oldIndex;
+ GLenum datatype = GL_FLOAT_VEC4;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program,
+ "glBindAttribLocation");
+ if (!shProg) {
+ return;
+ }
+
+ if (!name)
+ return;
+
+ if (strncmp(name, "gl_", 3) == 0) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glBindAttribLocation(illegal name)");
+ return;
+ }
+
+ if (index >= ctx->Const.VertexProgram.MaxAttribs) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glBindAttribLocation(index)");
+ return;
+ }
+
+ if (shProg->LinkStatus) {
+ /* get current index/location for the attribute */
+ oldIndex = get_attrib_location(ctx, program, name);
+ }
+ else {
+ oldIndex = -1;
+ }
+
+ /* this will replace the current value if it's already in the list */
+ i = _mesa_add_attribute(shProg->Attributes, name, size, datatype, index);
+ if (i < 0) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glBindAttribLocation");
+ return;
+ }
+
+ /*
+ * Note that this attribute binding won't go into effect until
+ * glLinkProgram is called again.
+ */
+}
+
+
+static void
+bind_frag_data_location(struct gl_context *ctx, GLuint program,
+ GLuint colorNumber, const GLchar *name)
+{
+ _mesa_problem(ctx, "bind_frag_data_location() not implemented yet");
+}
+
+
+static GLuint
+create_shader(struct gl_context *ctx, GLenum type)
+{
+ struct gl_shader *sh;
+ GLuint name;
+
+ if (!validate_shader_target(ctx, type)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "CreateShader(type)");
+ return 0;
+ }
+
+ name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
+ sh = ctx->Driver.NewShader(ctx, name, type);
+ _mesa_HashInsert(ctx->Shared->ShaderObjects, name, sh);
+
+ return name;
+}
+
+
+static GLuint
+create_shader_program(struct gl_context *ctx)
+{
+ GLuint name;
+ struct gl_shader_program *shProg;
+
+ name = _mesa_HashFindFreeKeyBlock(ctx->Shared->ShaderObjects, 1);
+
+ shProg = ctx->Driver.NewShaderProgram(ctx, name);
+
+ _mesa_HashInsert(ctx->Shared->ShaderObjects, name, shProg);
+
+ assert(shProg->RefCount == 1);
+
+ return name;
+}
+
+
+/**
+ * Named w/ "2" to indicate OpenGL 2.x vs GL_ARB_fragment_programs's
+ * DeleteProgramARB.
+ */
+static void
+delete_shader_program(struct gl_context *ctx, GLuint name)
+{
+ /*
+ * NOTE: deleting shaders/programs works a bit differently than
+ * texture objects (and buffer objects, etc). Shader/program
+ * handles/IDs exist in the hash table until the object is really
+ * deleted (refcount==0). With texture objects, the handle/ID is
+ * removed from the hash table in glDeleteTextures() while the tex
+ * object itself might linger until its refcount goes to zero.
+ */
+ struct gl_shader_program *shProg;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, name, "glDeleteProgram");
+ if (!shProg)
+ return;
+
+ shProg->DeletePending = GL_TRUE;
+
+ /* effectively, decr shProg's refcount */
+ _mesa_reference_shader_program(ctx, &shProg, NULL);
+}
+
+
+static void
+delete_shader(struct gl_context *ctx, GLuint shader)
+{
+ struct gl_shader *sh;
+
+ sh = _mesa_lookup_shader_err(ctx, shader, "glDeleteShader");
+ if (!sh)
+ return;
+
+ sh->DeletePending = GL_TRUE;
+
+ /* effectively, decr sh's refcount */
+ _mesa_reference_shader(ctx, &sh, NULL);
+}
+
+
+static void
+detach_shader(struct gl_context *ctx, GLuint program, GLuint shader)
+{
+ struct gl_shader_program *shProg;
+ GLuint n;
+ GLuint i, j;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glDetachShader");
+ if (!shProg)
+ return;
+
+ n = shProg->NumShaders;
+
+ for (i = 0; i < n; i++) {
+ if (shProg->Shaders[i]->Name == shader) {
+ /* found it */
+ struct gl_shader **newList;
+
+ /* release */
+ _mesa_reference_shader(ctx, &shProg->Shaders[i], NULL);
+
+ /* alloc new, smaller array */
+ newList = (struct gl_shader **)
+ malloc((n - 1) * sizeof(struct gl_shader *));
+ if (!newList) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glDetachShader");
+ return;
+ }
+ for (j = 0; j < i; j++) {
+ newList[j] = shProg->Shaders[j];
+ }
+ while (++i < n)
+ newList[j++] = shProg->Shaders[i];
+ free(shProg->Shaders);
+
+ shProg->Shaders = newList;
+ shProg->NumShaders = n - 1;
+
+#ifdef DEBUG
+ /* sanity check */
+ {
+ for (j = 0; j < shProg->NumShaders; j++) {
+ assert(shProg->Shaders[j]->Type == GL_VERTEX_SHADER ||
+ shProg->Shaders[j]->Type == GL_FRAGMENT_SHADER);
+ assert(shProg->Shaders[j]->RefCount > 0);
+ }
+ }
+#endif
+
+ return;
+ }
+ }
+
+ /* not found */
+ {
+ GLenum err;
+ if (is_shader(ctx, shader))
+ err = GL_INVALID_OPERATION;
+ else if (is_program(ctx, shader))
+ err = GL_INVALID_OPERATION;
+ else
+ err = GL_INVALID_VALUE;
+ _mesa_error(ctx, err, "glDetachProgram(shader)");
+ return;
+ }
+}
+
+
+static void
+get_active_attrib(struct gl_context *ctx, GLuint program, GLuint index,
+ GLsizei maxLength, GLsizei *length, GLint *size,
+ GLenum *type, GLchar *nameOut)
+{
+ const struct gl_program_parameter_list *attribs = NULL;
+ struct gl_shader_program *shProg;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glGetActiveAttrib");
+ if (!shProg)
+ return;
+
+ if (shProg->VertexProgram)
+ attribs = shProg->VertexProgram->Base.Attributes;
+
+ if (!attribs || index >= attribs->NumParameters) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGetActiveAttrib(index)");
+ return;
+ }
+
+ _mesa_copy_string(nameOut, maxLength, length,
+ attribs->Parameters[index].Name);
+
+ if (size)
+ *size = attribs->Parameters[index].Size
+ / _mesa_sizeof_glsl_type(attribs->Parameters[index].DataType);
+
+ if (type)
+ *type = attribs->Parameters[index].DataType;
+}
+
+
+/**
+ * Return list of shaders attached to shader program.
+ */
+static void
+get_attached_shaders(struct gl_context *ctx, GLuint program, GLsizei maxCount,
+ GLsizei *count, GLuint *obj)
+{
+ struct gl_shader_program *shProg =
+ _mesa_lookup_shader_program_err(ctx, program, "glGetAttachedShaders");
+ if (shProg) {
+ GLuint i;
+ for (i = 0; i < (GLuint) maxCount && i < shProg->NumShaders; i++) {
+ obj[i] = shProg->Shaders[i]->Name;
+ }
+ if (count)
+ *count = i;
+ }
+}
+
+
+static GLint
+get_frag_data_location(struct gl_context *ctx, GLuint program,
+ const GLchar *name)
+{
+ _mesa_problem(ctx, "get_frag_data_location() not implemented yet");
+ return -1;
+}
+
+
+
+/**
+ * glGetHandleARB() - return ID/name of currently bound shader program.
+ */
+static GLuint
+get_handle(struct gl_context *ctx, GLenum pname)
+{
+ if (pname == GL_PROGRAM_OBJECT_ARB) {
+ if (ctx->Shader.ActiveProgram)
+ return ctx->Shader.ActiveProgram->Name;
+ else
+ return 0;
+ }
+ else {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetHandleARB");
+ return 0;
+ }
+}
+
+
+/**
+ * glGetProgramiv() - get shader program state.
+ * Note that this is for GLSL shader programs, not ARB vertex/fragment
+ * programs (see glGetProgramivARB).
+ */
+static void
+get_programiv(struct gl_context *ctx, GLuint program, GLenum pname, GLint *params)
+{
+ const struct gl_program_parameter_list *attribs;
+ struct gl_shader_program *shProg
+ = _mesa_lookup_shader_program(ctx, program);
+
+ if (!shProg) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramiv(program)");
+ return;
+ }
+
+ if (shProg->VertexProgram)
+ attribs = shProg->VertexProgram->Base.Attributes;
+ else
+ attribs = NULL;
+
+ switch (pname) {
+ case GL_DELETE_STATUS:
+ *params = shProg->DeletePending;
+ break;
+ case GL_LINK_STATUS:
+ *params = shProg->LinkStatus;
+ break;
+ case GL_VALIDATE_STATUS:
+ *params = shProg->Validated;
+ break;
+ case GL_INFO_LOG_LENGTH:
+ *params = shProg->InfoLog ? strlen(shProg->InfoLog) + 1 : 0;
+ break;
+ case GL_ATTACHED_SHADERS:
+ *params = shProg->NumShaders;
+ break;
+ case GL_ACTIVE_ATTRIBUTES:
+ *params = attribs ? attribs->NumParameters : 0;
+ break;
+ case GL_ACTIVE_ATTRIBUTE_MAX_LENGTH:
+ *params = _mesa_longest_parameter_name(attribs, PROGRAM_INPUT) + 1;
+ break;
+ case GL_ACTIVE_UNIFORMS:
+ *params = shProg->Uniforms ? shProg->Uniforms->NumUniforms : 0;
+ break;
+ case GL_ACTIVE_UNIFORM_MAX_LENGTH:
+ *params = _mesa_longest_uniform_name(shProg->Uniforms);
+ if (*params > 0)
+ (*params)++; /* add one for terminating zero */
+ break;
+ case GL_PROGRAM_BINARY_LENGTH_OES:
+ *params = 0;
+ break;
+#if FEATURE_EXT_transform_feedback
+ case GL_TRANSFORM_FEEDBACK_VARYINGS:
+ *params = shProg->TransformFeedback.NumVarying;
+ break;
+ case GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH:
+ *params = longest_feedback_varying_name(shProg) + 1;
+ break;
+ case GL_TRANSFORM_FEEDBACK_BUFFER_MODE:
+ *params = shProg->TransformFeedback.BufferMode;
+ break;
+#endif
+#if FEATURE_ARB_geometry_shader4
+ case GL_GEOMETRY_VERTICES_OUT_ARB:
+ *params = shProg->Geom.VerticesOut;
+ break;
+ case GL_GEOMETRY_INPUT_TYPE_ARB:
+ *params = shProg->Geom.InputType;
+ break;
+ case GL_GEOMETRY_OUTPUT_TYPE_ARB:
+ *params = shProg->Geom.OutputType;
+ break;
+#endif
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetProgramiv(pname)");
+ return;
+ }
+}
+
+
+/**
+ * glGetShaderiv() - get GLSL shader state
+ */
+static void
+get_shaderiv(struct gl_context *ctx, GLuint name, GLenum pname, GLint *params)
+{
+ struct gl_shader *shader =
+ _mesa_lookup_shader_err(ctx, name, "glGetShaderiv");
+
+ if (!shader) {
+ return;
+ }
+
+ switch (pname) {
+ case GL_SHADER_TYPE:
+ *params = shader->Type;
+ break;
+ case GL_DELETE_STATUS:
+ *params = shader->DeletePending;
+ break;
+ case GL_COMPILE_STATUS:
+ *params = shader->CompileStatus;
+ break;
+ case GL_INFO_LOG_LENGTH:
+ *params = shader->InfoLog ? strlen(shader->InfoLog) + 1 : 0;
+ break;
+ case GL_SHADER_SOURCE_LENGTH:
+ *params = shader->Source ? strlen((char *) shader->Source) + 1 : 0;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glGetShaderiv(pname)");
+ return;
+ }
+}
+
+
+static void
+get_program_info_log(struct gl_context *ctx, GLuint program, GLsizei bufSize,
+ GLsizei *length, GLchar *infoLog)
+{
+ struct gl_shader_program *shProg
+ = _mesa_lookup_shader_program(ctx, program);
+ if (!shProg) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGetProgramInfoLog(program)");
+ return;
+ }
+ _mesa_copy_string(infoLog, bufSize, length, shProg->InfoLog);
+}
+
+
+static void
+get_shader_info_log(struct gl_context *ctx, GLuint shader, GLsizei bufSize,
+ GLsizei *length, GLchar *infoLog)
+{
+ struct gl_shader *sh = _mesa_lookup_shader(ctx, shader);
+ if (!sh) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGetShaderInfoLog(shader)");
+ return;
+ }
+ _mesa_copy_string(infoLog, bufSize, length, sh->InfoLog);
+}
+
+
+/**
+ * Return shader source code.
+ */
+static void
+get_shader_source(struct gl_context *ctx, GLuint shader, GLsizei maxLength,
+ GLsizei *length, GLchar *sourceOut)
+{
+ struct gl_shader *sh;
+ sh = _mesa_lookup_shader_err(ctx, shader, "glGetShaderSource");
+ if (!sh) {
+ return;
+ }
+ _mesa_copy_string(sourceOut, maxLength, length, sh->Source);
+}
+
+
+/**
+ * Set/replace shader source code.
+ */
+static void
+shader_source(struct gl_context *ctx, GLuint shader, const GLchar *source)
+{
+ struct gl_shader *sh;
+
+ sh = _mesa_lookup_shader_err(ctx, shader, "glShaderSource");
+ if (!sh)
+ return;
+
+ /* free old shader source string and install new one */
+ if (sh->Source) {
+ free((void *) sh->Source);
+ }
+ sh->Source = source;
+ sh->CompileStatus = GL_FALSE;
+#ifdef DEBUG
+ sh->SourceChecksum = _mesa_str_checksum(sh->Source);
+#endif
+}
+
+
+/**
+ * Compile a shader.
+ */
+static void
+compile_shader(struct gl_context *ctx, GLuint shaderObj)
+{
+ struct gl_shader *sh;
+ struct gl_shader_compiler_options *options;
+
+ sh = _mesa_lookup_shader_err(ctx, shaderObj, "glCompileShader");
+ if (!sh)
+ return;
+
+ options = &ctx->ShaderCompilerOptions[_mesa_shader_type_to_index(sh->Type)];
+
+ /* set default pragma state for shader */
+ sh->Pragmas = options->DefaultPragmas;
+
+ /* this call will set the sh->CompileStatus field to indicate if
+ * compilation was successful.
+ */
+ _mesa_glsl_compile_shader(ctx, sh);
+}
+
+
+/**
+ * Link a program's shaders.
+ */
+static void
+link_program(struct gl_context *ctx, GLuint program)
+{
+ struct gl_shader_program *shProg;
+ struct gl_transform_feedback_object *obj =
+ ctx->TransformFeedback.CurrentObject;
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glLinkProgram");
+ if (!shProg)
+ return;
+
+ if (obj->Active
+ && (shProg == ctx->Shader.CurrentVertexProgram
+ || shProg == ctx->Shader.CurrentGeometryProgram
+ || shProg == ctx->Shader.CurrentFragmentProgram)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glLinkProgram(transform feedback active");
+ return;
+ }
+
+ FLUSH_VERTICES(ctx, _NEW_PROGRAM);
+
+ _mesa_glsl_link_shader(ctx, shProg);
+
+ /* debug code */
+ if (0) {
+ GLuint i;
+
+ printf("Link %u shaders in program %u: %s\n",
+ shProg->NumShaders, shProg->Name,
+ shProg->LinkStatus ? "Success" : "Failed");
+
+ for (i = 0; i < shProg->NumShaders; i++) {
+ printf(" shader %u, type 0x%x\n",
+ shProg->Shaders[i]->Name,
+ shProg->Shaders[i]->Type);
+ }
+ }
+}
+
+
+/**
+ * Print basic shader info (for debug).
+ */
+static void
+print_shader_info(const struct gl_shader_program *shProg)
+{
+ GLuint i;
+
+ printf("Mesa: glUseProgram(%u)\n", shProg->Name);
+ for (i = 0; i < shProg->NumShaders; i++) {
+ const char *s;
+ switch (shProg->Shaders[i]->Type) {
+ case GL_VERTEX_SHADER:
+ s = "vertex";
+ break;
+ case GL_FRAGMENT_SHADER:
+ s = "fragment";
+ break;
+ case GL_GEOMETRY_SHADER:
+ s = "geometry";
+ break;
+ default:
+ s = "";
+ }
+ printf(" %s shader %u, checksum %u\n", s,
+ shProg->Shaders[i]->Name,
+ shProg->Shaders[i]->SourceChecksum);
+ }
+ if (shProg->VertexProgram)
+ printf(" vert prog %u\n", shProg->VertexProgram->Base.Id);
+ if (shProg->FragmentProgram)
+ printf(" frag prog %u\n", shProg->FragmentProgram->Base.Id);
+}
+
+
+/**
+ * Use the named shader program for subsequent glUniform calls
+ */
+void
+_mesa_active_program(struct gl_context *ctx, struct gl_shader_program *shProg,
+ const char *caller)
+{
+ if ((shProg != NULL) && !shProg->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "%s(program %u not linked)", caller, shProg->Name);
+ return;
+ }
+
+ if (ctx->Shader.ActiveProgram != shProg) {
+ _mesa_reference_shader_program(ctx, &ctx->Shader.ActiveProgram, shProg);
+ }
+}
+
+/**
+ */
+static bool
+use_shader_program(struct gl_context *ctx, GLenum type,
+ struct gl_shader_program *shProg)
+{
+ struct gl_shader_program **target;
+
+ switch (type) {
+#if FEATURE_ARB_vertex_shader
+ case GL_VERTEX_SHADER:
+ target = &ctx->Shader.CurrentVertexProgram;
+ if ((shProg == NULL)
+ || (shProg->_LinkedShaders[MESA_SHADER_VERTEX] == NULL)) {
+ shProg = NULL;
+ }
+ break;
+#endif
+#if FEATURE_ARB_geometry_shader4
+ case GL_GEOMETRY_SHADER_ARB:
+ target = &ctx->Shader.CurrentGeometryProgram;
+ if ((shProg == NULL)
+ || (shProg->_LinkedShaders[MESA_SHADER_GEOMETRY] == NULL)) {
+ shProg = NULL;
+ }
+ break;
+#endif
+#if FEATURE_ARB_fragment_shader
+ case GL_FRAGMENT_SHADER:
+ target = &ctx->Shader.CurrentFragmentProgram;
+ if ((shProg == NULL)
+ || (shProg->_LinkedShaders[MESA_SHADER_FRAGMENT] == NULL)) {
+ shProg = NULL;
+ }
+ break;
+#endif
+ default:
+ return false;
+ }
+
+ if (*target != shProg) {
+ FLUSH_VERTICES(ctx, _NEW_PROGRAM | _NEW_PROGRAM_CONSTANTS);
+ _mesa_reference_shader_program(ctx, target, shProg);
+ return true;
+ }
+
+ return false;
+}
+
+/**
+ * Use the named shader program for subsequent rendering.
+ */
+void
+_mesa_use_program(struct gl_context *ctx, struct gl_shader_program *shProg)
+{
+ use_shader_program(ctx, GL_VERTEX_SHADER, shProg);
+ use_shader_program(ctx, GL_GEOMETRY_SHADER_ARB, shProg);
+ use_shader_program(ctx, GL_FRAGMENT_SHADER, shProg);
+ _mesa_active_program(ctx, shProg, "glUseProgram");
+
+ if (ctx->Driver.UseProgram)
+ ctx->Driver.UseProgram(ctx, shProg);
+}
+
+
+/**
+ * Validate a program's samplers.
+ * Specifically, check that there aren't two samplers of different types
+ * pointing to the same texture unit.
+ * \return GL_TRUE if valid, GL_FALSE if invalid
+ */
+static GLboolean
+validate_samplers(const struct gl_program *prog, char *errMsg)
+{
+ static const char *targetName[] = {
+ "TEXTURE_2D_ARRAY",
+ "TEXTURE_1D_ARRAY",
+ "TEXTURE_CUBE",
+ "TEXTURE_3D",
+ "TEXTURE_RECT",
+ "TEXTURE_2D",
+ "TEXTURE_1D",
+ };
+ GLint targetUsed[MAX_TEXTURE_IMAGE_UNITS];
+ GLbitfield samplersUsed = prog->SamplersUsed;
+ GLuint i;
+
+ assert(Elements(targetName) == NUM_TEXTURE_TARGETS);
+
+ if (samplersUsed == 0x0)
+ return GL_TRUE;
+
+ for (i = 0; i < Elements(targetUsed); i++)
+ targetUsed[i] = -1;
+
+ /* walk over bits which are set in 'samplers' */
+ while (samplersUsed) {
+ GLuint unit;
+ gl_texture_index target;
+ GLint sampler = _mesa_ffs(samplersUsed) - 1;
+ assert(sampler >= 0);
+ assert(sampler < MAX_TEXTURE_IMAGE_UNITS);
+ unit = prog->SamplerUnits[sampler];
+ target = prog->SamplerTargets[sampler];
+ if (targetUsed[unit] != -1 && targetUsed[unit] != (int) target) {
+ _mesa_snprintf(errMsg, 100,
+ "Texture unit %d is accessed both as %s and %s",
+ unit, targetName[targetUsed[unit]], targetName[target]);
+ return GL_FALSE;
+ }
+ targetUsed[unit] = target;
+ samplersUsed ^= (1 << sampler);
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Do validation of the given shader program.
+ * \param errMsg returns error message if validation fails.
+ * \return GL_TRUE if valid, GL_FALSE if invalid (and set errMsg)
+ */
+static GLboolean
+validate_shader_program(const struct gl_shader_program *shProg,
+ char *errMsg)
+{
+ const struct gl_vertex_program *vp = shProg->VertexProgram;
+ const struct gl_fragment_program *fp = shProg->FragmentProgram;
+
+ if (!shProg->LinkStatus) {
+ return GL_FALSE;
+ }
+
+ /* From the GL spec, a program is invalid if any of these are true:
+
+ any two active samplers in the current program object are of
+ different types, but refer to the same texture image unit,
+
+ any active sampler in the current program object refers to a texture
+ image unit where fixed-function fragment processing accesses a
+ texture target that does not match the sampler type, or
+
+ the sum of the number of active samplers in the program and the
+ number of texture image units enabled for fixed-function fragment
+ processing exceeds the combined limit on the total number of texture
+ image units allowed.
+ */
+
+
+ /*
+ * Check: any two active samplers in the current program object are of
+ * different types, but refer to the same texture image unit,
+ */
+ if (vp && !validate_samplers(&vp->Base, errMsg)) {
+ return GL_FALSE;
+ }
+ if (fp && !validate_samplers(&fp->Base, errMsg)) {
+ return GL_FALSE;
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Called via glValidateProgram()
+ */
+static void
+validate_program(struct gl_context *ctx, GLuint program)
+{
+ struct gl_shader_program *shProg;
+ char errMsg[100];
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glValidateProgram");
+ if (!shProg) {
+ return;
+ }
+
+ shProg->Validated = validate_shader_program(shProg, errMsg);
+ if (!shProg->Validated) {
+ /* update info log */
+ if (shProg->InfoLog) {
+ ralloc_free(shProg->InfoLog);
+ }
+ shProg->InfoLog = ralloc_strdup(shProg, errMsg);
+ }
+}
+
+
+
+void GLAPIENTRY
+_mesa_AttachObjectARB(GLhandleARB program, GLhandleARB shader)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ attach_shader(ctx, program, shader);
+}
+
+
+void GLAPIENTRY
+_mesa_AttachShader(GLuint program, GLuint shader)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ attach_shader(ctx, program, shader);
+}
+
+
+void GLAPIENTRY
+_mesa_BindAttribLocationARB(GLhandleARB program, GLuint index,
+ const GLcharARB *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ bind_attrib_location(ctx, program, index, name);
+}
+
+
+/* GL_EXT_gpu_shader4, GL3 */
+void GLAPIENTRY
+_mesa_BindFragDataLocation(GLuint program, GLuint colorNumber,
+ const GLchar *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ bind_frag_data_location(ctx, program, colorNumber, name);
+}
+
+
+void GLAPIENTRY
+_mesa_CompileShaderARB(GLhandleARB shaderObj)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glCompileShader %u\n", shaderObj);
+ compile_shader(ctx, shaderObj);
+}
+
+
+GLuint GLAPIENTRY
+_mesa_CreateShader(GLenum type)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glCreateShader %s\n", _mesa_lookup_enum_by_nr(type));
+ return create_shader(ctx, type);
+}
+
+
+GLhandleARB GLAPIENTRY
+_mesa_CreateShaderObjectARB(GLenum type)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return create_shader(ctx, type);
+}
+
+
+GLuint GLAPIENTRY
+_mesa_CreateProgram(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glCreateProgram\n");
+ return create_shader_program(ctx);
+}
+
+
+GLhandleARB GLAPIENTRY
+_mesa_CreateProgramObjectARB(void)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return create_shader_program(ctx);
+}
+
+
+void GLAPIENTRY
+_mesa_DeleteObjectARB(GLhandleARB obj)
+{
+ if (MESA_VERBOSE & VERBOSE_API) {
+ GET_CURRENT_CONTEXT(ctx);
+ _mesa_debug(ctx, "glDeleteObjectARB(%u)\n", obj);
+ }
+
+ if (obj) {
+ GET_CURRENT_CONTEXT(ctx);
+ if (is_program(ctx, obj)) {
+ delete_shader_program(ctx, obj);
+ }
+ else if (is_shader(ctx, obj)) {
+ delete_shader(ctx, obj);
+ }
+ else {
+ /* error? */
+ }
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_DeleteProgram(GLuint name)
+{
+ if (name) {
+ GET_CURRENT_CONTEXT(ctx);
+ delete_shader_program(ctx, name);
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_DeleteShader(GLuint name)
+{
+ if (name) {
+ GET_CURRENT_CONTEXT(ctx);
+ delete_shader(ctx, name);
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_DetachObjectARB(GLhandleARB program, GLhandleARB shader)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ detach_shader(ctx, program, shader);
+}
+
+
+void GLAPIENTRY
+_mesa_DetachShader(GLuint program, GLuint shader)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ detach_shader(ctx, program, shader);
+}
+
+
+void GLAPIENTRY
+_mesa_GetActiveAttribARB(GLhandleARB program, GLuint index,
+ GLsizei maxLength, GLsizei * length, GLint * size,
+ GLenum * type, GLcharARB * name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_active_attrib(ctx, program, index, maxLength, length, size, type, name);
+}
+
+
+void GLAPIENTRY
+_mesa_GetAttachedObjectsARB(GLhandleARB container, GLsizei maxCount,
+ GLsizei * count, GLhandleARB * obj)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_attached_shaders(ctx, container, maxCount, count, obj);
+}
+
+
+void GLAPIENTRY
+_mesa_GetAttachedShaders(GLuint program, GLsizei maxCount,
+ GLsizei *count, GLuint *obj)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_attached_shaders(ctx, program, maxCount, count, obj);
+}
+
+
+GLint GLAPIENTRY
+_mesa_GetAttribLocationARB(GLhandleARB program, const GLcharARB * name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return get_attrib_location(ctx, program, name);
+}
+
+
+/* GL_EXT_gpu_shader4, GL3 */
+GLint GLAPIENTRY
+_mesa_GetFragDataLocation(GLuint program, const GLchar *name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return get_frag_data_location(ctx, program, name);
+}
+
+
+
+void GLAPIENTRY
+_mesa_GetInfoLogARB(GLhandleARB object, GLsizei maxLength, GLsizei * length,
+ GLcharARB * infoLog)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (is_program(ctx, object)) {
+ get_program_info_log(ctx, object, maxLength, length, infoLog);
+ }
+ else if (is_shader(ctx, object)) {
+ get_shader_info_log(ctx, object, maxLength, length, infoLog);
+ }
+ else {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glGetInfoLogARB");
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GetObjectParameterivARB(GLhandleARB object, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ /* Implement in terms of GetProgramiv, GetShaderiv */
+ if (is_program(ctx, object)) {
+ if (pname == GL_OBJECT_TYPE_ARB) {
+ *params = GL_PROGRAM_OBJECT_ARB;
+ }
+ else {
+ get_programiv(ctx, object, pname, params);
+ }
+ }
+ else if (is_shader(ctx, object)) {
+ if (pname == GL_OBJECT_TYPE_ARB) {
+ *params = GL_SHADER_OBJECT_ARB;
+ }
+ else {
+ get_shaderiv(ctx, object, pname, params);
+ }
+ }
+ else {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glGetObjectParameterivARB");
+ }
+}
+
+
+void GLAPIENTRY
+_mesa_GetObjectParameterfvARB(GLhandleARB object, GLenum pname,
+ GLfloat *params)
+{
+ GLint iparams[1]; /* XXX is one element enough? */
+ _mesa_GetObjectParameterivARB(object, pname, iparams);
+ params[0] = (GLfloat) iparams[0];
+}
+
+
+void GLAPIENTRY
+_mesa_GetProgramiv(GLuint program, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_programiv(ctx, program, pname, params);
+}
+
+
+void GLAPIENTRY
+_mesa_GetShaderiv(GLuint shader, GLenum pname, GLint *params)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_shaderiv(ctx, shader, pname, params);
+}
+
+
+void GLAPIENTRY
+_mesa_GetProgramInfoLog(GLuint program, GLsizei bufSize,
+ GLsizei *length, GLchar *infoLog)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_program_info_log(ctx, program, bufSize, length, infoLog);
+}
+
+
+void GLAPIENTRY
+_mesa_GetShaderInfoLog(GLuint shader, GLsizei bufSize,
+ GLsizei *length, GLchar *infoLog)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_shader_info_log(ctx, shader, bufSize, length, infoLog);
+}
+
+
+void GLAPIENTRY
+_mesa_GetShaderSourceARB(GLhandleARB shader, GLsizei maxLength,
+ GLsizei *length, GLcharARB *sourceOut)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ get_shader_source(ctx, shader, maxLength, length, sourceOut);
+}
+
+
+GLhandleARB GLAPIENTRY
+_mesa_GetHandleARB(GLenum pname)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return get_handle(ctx, pname);
+}
+
+
+GLboolean GLAPIENTRY
+_mesa_IsProgram(GLuint name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return is_program(ctx, name);
+}
+
+
+GLboolean GLAPIENTRY
+_mesa_IsShader(GLuint name)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ return is_shader(ctx, name);
+}
+
+
+void GLAPIENTRY
+_mesa_LinkProgramARB(GLhandleARB programObj)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ link_program(ctx, programObj);
+}
+
+
+
+/**
+ * Read shader source code from a file.
+ * Useful for debugging to override an app's shader.
+ */
+static GLcharARB *
+read_shader(const char *fname)
+{
+ const int max = 50*1000;
+ FILE *f = fopen(fname, "r");
+ GLcharARB *buffer, *shader;
+ int len;
+
+ if (!f) {
+ return NULL;
+ }
+
+ buffer = (char *) malloc(max);
+ len = fread(buffer, 1, max, f);
+ buffer[len] = 0;
+
+ fclose(f);
+
+ shader = _mesa_strdup(buffer);
+ free(buffer);
+
+ return shader;
+}
+
+
+/**
+ * Called via glShaderSource() and glShaderSourceARB() API functions.
+ * Basically, concatenate the source code strings into one long string
+ * and pass it to _mesa_shader_source().
+ */
+void GLAPIENTRY
+_mesa_ShaderSourceARB(GLhandleARB shaderObj, GLsizei count,
+ const GLcharARB ** string, const GLint * length)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint *offsets;
+ GLsizei i, totalLength;
+ GLcharARB *source;
+ GLuint checksum;
+
+ if (!shaderObj || string == NULL) {
+ _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
+ return;
+ }
+
+ /*
+ * This array holds offsets of where the appropriate string ends, thus the
+ * last element will be set to the total length of the source code.
+ */
+ offsets = (GLint *) malloc(count * sizeof(GLint));
+ if (offsets == NULL) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
+ return;
+ }
+
+ for (i = 0; i < count; i++) {
+ if (string[i] == NULL) {
+ free((GLvoid *) offsets);
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glShaderSourceARB(null string)");
+ return;
+ }
+ if (length == NULL || length[i] < 0)
+ offsets[i] = strlen(string[i]);
+ else
+ offsets[i] = length[i];
+ /* accumulate string lengths */
+ if (i > 0)
+ offsets[i] += offsets[i - 1];
+ }
+
+ /* Total length of source string is sum off all strings plus two.
+ * One extra byte for terminating zero, another extra byte to silence
+ * valgrind warnings in the parser/grammer code.
+ */
+ totalLength = offsets[count - 1] + 2;
+ source = (GLcharARB *) malloc(totalLength * sizeof(GLcharARB));
+ if (source == NULL) {
+ free((GLvoid *) offsets);
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
+ return;
+ }
+
+ for (i = 0; i < count; i++) {
+ GLint start = (i > 0) ? offsets[i - 1] : 0;
+ memcpy(source + start, string[i],
+ (offsets[i] - start) * sizeof(GLcharARB));
+ }
+ source[totalLength - 1] = '\0';
+ source[totalLength - 2] = '\0';
+
+ if (SHADER_SUBST) {
+ /* Compute the shader's source code checksum then try to open a file
+ * named newshader_<CHECKSUM>. If it exists, use it in place of the
+ * original shader source code. For debugging.
+ */
+ char filename[100];
+ GLcharARB *newSource;
+
+ checksum = _mesa_str_checksum(source);
+
+ _mesa_snprintf(filename, sizeof(filename), "newshader_%d", checksum);
+
+ newSource = read_shader(filename);
+ if (newSource) {
+ fprintf(stderr, "Mesa: Replacing shader %u chksum=%d with %s\n",
+ shaderObj, checksum, filename);
+ free(source);
+ source = newSource;
+ }
+ }
+
+ shader_source(ctx, shaderObj, source);
+
+ if (SHADER_SUBST) {
+ struct gl_shader *sh = _mesa_lookup_shader(ctx, shaderObj);
+ if (sh)
+ sh->SourceChecksum = checksum; /* save original checksum */
+ }
+
+ free(offsets);
+}
+
+
+void GLAPIENTRY
+_mesa_UseProgramObjectARB(GLhandleARB program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_shader_program *shProg;
+ struct gl_transform_feedback_object *obj =
+ ctx->TransformFeedback.CurrentObject;
+
+ if (obj->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glUseProgram(transform feedback active)");
+ return;
+ }
+
+ if (program) {
+ shProg = _mesa_lookup_shader_program_err(ctx, program, "glUseProgram");
+ if (!shProg) {
+ return;
+ }
+ if (!shProg->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glUseProgram(program %u not linked)", program);
+ return;
+ }
+
+ /* debug code */
+ if (ctx->Shader.Flags & GLSL_USE_PROG) {
+ print_shader_info(shProg);
+ }
+ }
+ else {
+ shProg = NULL;
+ }
+
+ _mesa_use_program(ctx, shProg);
+}
+
+
+void GLAPIENTRY
+_mesa_ValidateProgramARB(GLhandleARB program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ validate_program(ctx, program);
+}
+
+#ifdef FEATURE_ES2
+
+void GLAPIENTRY
+_mesa_GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype,
+ GLint* range, GLint* precision)
+{
+ const struct gl_program_constants *limits;
+ const struct gl_precision *p;
+ GET_CURRENT_CONTEXT(ctx);
+
+ switch (shadertype) {
+ case GL_VERTEX_SHADER:
+ limits = &ctx->Const.VertexProgram;
+ break;
+ case GL_FRAGMENT_SHADER:
+ limits = &ctx->Const.FragmentProgram;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetShaderPrecisionFormat(shadertype)");
+ return;
+ }
+
+ switch (precisiontype) {
+ case GL_LOW_FLOAT:
+ p = &limits->LowFloat;
+ break;
+ case GL_MEDIUM_FLOAT:
+ p = &limits->MediumFloat;
+ break;
+ case GL_HIGH_FLOAT:
+ p = &limits->HighFloat;
+ break;
+ case GL_LOW_INT:
+ p = &limits->LowInt;
+ break;
+ case GL_MEDIUM_INT:
+ p = &limits->MediumInt;
+ break;
+ case GL_HIGH_INT:
+ p = &limits->HighInt;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glGetShaderPrecisionFormat(precisiontype)");
+ return;
+ }
+
+ range[0] = p->RangeMin;
+ range[1] = p->RangeMax;
+ precision[0] = p->Precision;
+}
+
+
+void GLAPIENTRY
+_mesa_ReleaseShaderCompiler(void)
+{
+ _mesa_destroy_shader_compiler_caches();
+}
+
+
+void GLAPIENTRY
+_mesa_ShaderBinary(GLint n, const GLuint* shaders, GLenum binaryformat,
+ const void* binary, GLint length)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ (void) n;
+ (void) shaders;
+ (void) binaryformat;
+ (void) binary;
+ (void) length;
+ _mesa_error(ctx, GL_INVALID_OPERATION, __FUNCTION__);
+}
+
+#endif /* FEATURE_ES2 */
+
+
+#if FEATURE_ARB_geometry_shader4
+
+void GLAPIENTRY
+_mesa_ProgramParameteriARB(GLuint program, GLenum pname,
+ GLint value)
+{
+ struct gl_shader_program *shProg;
+ GET_CURRENT_CONTEXT(ctx);
+
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ shProg = _mesa_lookup_shader_program_err(ctx, program,
+ "glProgramParameteri");
+ if (!shProg)
+ return;
+
+ switch (pname) {
+ case GL_GEOMETRY_VERTICES_OUT_ARB:
+ if (value < 1 ||
+ (unsigned) value > ctx->Const.GeometryProgram.MaxGeometryOutputVertices) {
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glProgramParameteri(GL_GEOMETRY_VERTICES_OUT_ARB=%d",
+ value);
+ return;
+ }
+ shProg->Geom.VerticesOut = value;
+ break;
+ case GL_GEOMETRY_INPUT_TYPE_ARB:
+ switch (value) {
+ case GL_POINTS:
+ case GL_LINES:
+ case GL_LINES_ADJACENCY_ARB:
+ case GL_TRIANGLES:
+ case GL_TRIANGLES_ADJACENCY_ARB:
+ shProg->Geom.InputType = value;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glProgramParameteri(geometry input type = %s",
+ _mesa_lookup_enum_by_nr(value));
+ return;
+ }
+ break;
+ case GL_GEOMETRY_OUTPUT_TYPE_ARB:
+ switch (value) {
+ case GL_POINTS:
+ case GL_LINE_STRIP:
+ case GL_TRIANGLE_STRIP:
+ shProg->Geom.OutputType = value;
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_VALUE,
+ "glProgramParameteri(geometry output type = %s",
+ _mesa_lookup_enum_by_nr(value));
+ return;
+ }
+ break;
+ default:
+ _mesa_error(ctx, GL_INVALID_ENUM, "glProgramParameteriARB(pname=%s)",
+ _mesa_lookup_enum_by_nr(pname));
+ break;
+ }
+}
+
+#endif
+
+void
+_mesa_use_shader_program(struct gl_context *ctx, GLenum type,
+ struct gl_shader_program *shProg)
+{
+ use_shader_program(ctx, type, shProg);
+
+ if (ctx->Driver.UseProgram)
+ ctx->Driver.UseProgram(ctx, shProg);
+}
+
+void GLAPIENTRY
+_mesa_UseShaderProgramEXT(GLenum type, GLuint program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_shader_program *shProg = NULL;
+
+ if (!validate_shader_target(ctx, type)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glUseShaderProgramEXT(type)");
+ return;
+ }
+
+ if (ctx->TransformFeedback.CurrentObject->Active) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glUseShaderProgramEXT(transform feedback is active)");
+ return;
+ }
+
+ if (program) {
+ shProg = _mesa_lookup_shader_program_err(ctx, program,
+ "glUseShaderProgramEXT");
+ if (shProg == NULL)
+ return;
+
+ if (!shProg->LinkStatus) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glUseShaderProgramEXT(program not linked)");
+ return;
+ }
+ }
+
+ _mesa_use_shader_program(ctx, type, shProg);
+}
+
+void GLAPIENTRY
+_mesa_ActiveProgramEXT(GLuint program)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ struct gl_shader_program *shProg = (program != 0)
+ ? _mesa_lookup_shader_program_err(ctx, program, "glActiveProgramEXT")
+ : NULL;
+
+ _mesa_active_program(ctx, shProg, "glActiveProgramEXT");
+ return;
+}
+
+GLuint GLAPIENTRY
+_mesa_CreateShaderProgramEXT(GLenum type, const GLchar *string)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLuint shader = create_shader(ctx, type);
+ GLuint program = 0;
+
+ if (shader) {
+ shader_source(ctx, shader, _mesa_strdup(string));
+ compile_shader(ctx, shader);
+
+ program = create_shader_program(ctx);
+ if (program) {
+ struct gl_shader_program *shProg;
+ struct gl_shader *sh;
+ GLint compiled = GL_FALSE;
+
+ shProg = _mesa_lookup_shader_program(ctx, program);
+ sh = _mesa_lookup_shader(ctx, shader);
+
+ get_shaderiv(ctx, shader, GL_COMPILE_STATUS, &compiled);
+ if (compiled) {
+ attach_shader(ctx, program, shader);
+ link_program(ctx, program);
+ detach_shader(ctx, program, shader);
+
+#if 0
+ /* Possibly... */
+ if (active-user-defined-varyings-in-linked-program) {
+ append-error-to-info-log;
+ shProg->LinkStatus = GL_FALSE;
+ }
+#endif
+ }
+
+ ralloc_strcat(&shProg->InfoLog, sh->InfoLog);
+ }
+
+ delete_shader(ctx, shader);
+ }
+
+ return program;
+}
+
+/**
+ * Plug in shader-related functions into API dispatch table.
+ */
+void
+_mesa_init_shader_dispatch(struct _glapi_table *exec)
+{
+#if FEATURE_GL
+ /* GL_ARB_vertex/fragment_shader */
+ SET_DeleteObjectARB(exec, _mesa_DeleteObjectARB);
+ SET_GetHandleARB(exec, _mesa_GetHandleARB);
+ SET_DetachObjectARB(exec, _mesa_DetachObjectARB);
+ SET_CreateShaderObjectARB(exec, _mesa_CreateShaderObjectARB);
+ SET_ShaderSourceARB(exec, _mesa_ShaderSourceARB);
+ SET_CompileShaderARB(exec, _mesa_CompileShaderARB);
+ SET_CreateProgramObjectARB(exec, _mesa_CreateProgramObjectARB);
+ SET_AttachObjectARB(exec, _mesa_AttachObjectARB);
+ SET_LinkProgramARB(exec, _mesa_LinkProgramARB);
+ SET_UseProgramObjectARB(exec, _mesa_UseProgramObjectARB);
+ SET_ValidateProgramARB(exec, _mesa_ValidateProgramARB);
+ SET_GetObjectParameterfvARB(exec, _mesa_GetObjectParameterfvARB);
+ SET_GetObjectParameterivARB(exec, _mesa_GetObjectParameterivARB);
+ SET_GetInfoLogARB(exec, _mesa_GetInfoLogARB);
+ SET_GetAttachedObjectsARB(exec, _mesa_GetAttachedObjectsARB);
+ SET_GetShaderSourceARB(exec, _mesa_GetShaderSourceARB);
+
+ /* OpenGL 2.0 */
+ SET_AttachShader(exec, _mesa_AttachShader);
+ SET_CreateProgram(exec, _mesa_CreateProgram);
+ SET_CreateShader(exec, _mesa_CreateShader);
+ SET_DeleteProgram(exec, _mesa_DeleteProgram);
+ SET_DeleteShader(exec, _mesa_DeleteShader);
+ SET_DetachShader(exec, _mesa_DetachShader);
+ SET_GetAttachedShaders(exec, _mesa_GetAttachedShaders);
+ SET_GetProgramiv(exec, _mesa_GetProgramiv);
+ SET_GetProgramInfoLog(exec, _mesa_GetProgramInfoLog);
+ SET_GetShaderiv(exec, _mesa_GetShaderiv);
+ SET_GetShaderInfoLog(exec, _mesa_GetShaderInfoLog);
+ SET_IsProgram(exec, _mesa_IsProgram);
+ SET_IsShader(exec, _mesa_IsShader);
+
+#if FEATURE_ARB_vertex_shader
+ SET_BindAttribLocationARB(exec, _mesa_BindAttribLocationARB);
+ SET_GetActiveAttribARB(exec, _mesa_GetActiveAttribARB);
+ SET_GetAttribLocationARB(exec, _mesa_GetAttribLocationARB);
+#endif
+
+#if FEATURE_ARB_geometry_shader4
+ SET_ProgramParameteriARB(exec, _mesa_ProgramParameteriARB);
+#endif
+
+ SET_UseShaderProgramEXT(exec, _mesa_UseShaderProgramEXT);
+ SET_ActiveProgramEXT(exec, _mesa_ActiveProgramEXT);
+ SET_CreateShaderProgramEXT(exec, _mesa_CreateShaderProgramEXT);
+
+ /* GL_EXT_gpu_shader4 / GL 3.0 */
+ SET_BindFragDataLocationEXT(exec, _mesa_BindFragDataLocation);
+ SET_GetFragDataLocationEXT(exec, _mesa_GetFragDataLocation);
+
+ /* GL_ARB_ES2_compatibility */
+ SET_ReleaseShaderCompiler(exec, _mesa_ReleaseShaderCompiler);
+ SET_GetShaderPrecisionFormat(exec, _mesa_GetShaderPrecisionFormat);
+
+#endif /* FEATURE_GL */
+}
+
diff --git a/mesalib/src/mesa/main/state.c b/mesalib/src/mesa/main/state.c
index 502c42929..f11578faf 100644
--- a/mesalib/src/mesa/main/state.c
+++ b/mesalib/src/mesa/main/state.c
@@ -1,734 +1,734 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.3
- *
- * Copyright (C) 1999-2008 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 state.c
- * State management.
- *
- * This file manages recalculation of derived values in struct gl_context.
- */
-
-
-#include "glheader.h"
-#include "mtypes.h"
-#include "context.h"
-#include "debug.h"
-#include "macros.h"
-#include "ffvertex_prog.h"
-#include "framebuffer.h"
-#include "light.h"
-#include "matrix.h"
-#include "pixel.h"
-#include "program/program.h"
-#include "program/prog_parameter.h"
-#include "state.h"
-#include "stencil.h"
-#include "texenvprogram.h"
-#include "texobj.h"
-#include "texstate.h"
-
-
-static void
-update_separate_specular(struct gl_context *ctx)
-{
- if (NEED_SECONDARY_COLOR(ctx))
- ctx->_TriangleCaps |= DD_SEPARATE_SPECULAR;
- else
- ctx->_TriangleCaps &= ~DD_SEPARATE_SPECULAR;
-}
-
-
-/**
- * Compute the index of the last array element that can be safely accessed
- * in a vertex array. We can really only do this when the array lives in
- * a VBO.
- * The array->_MaxElement field will be updated.
- * Later in glDrawArrays/Elements/etc we can do some bounds checking.
- */
-static void
-compute_max_element(struct gl_client_array *array)
-{
- assert(array->Enabled);
- if (array->BufferObj->Name) {
- GLsizeiptrARB offset = (GLsizeiptrARB) array->Ptr;
- GLsizeiptrARB obj_size = (GLsizeiptrARB) array->BufferObj->Size;
-
- if (offset < obj_size) {
- array->_MaxElement = (obj_size - offset +
- array->StrideB -
- array->_ElementSize) / array->StrideB;
- } else {
- array->_MaxElement = 0;
- }
- }
- else {
- /* user-space array, no idea how big it is */
- array->_MaxElement = 2 * 1000 * 1000 * 1000; /* just a big number */
- }
-}
-
-
-/**
- * Helper for update_arrays().
- * \return min(current min, array->_MaxElement).
- */
-static GLuint
-update_min(GLuint min, struct gl_client_array *array)
-{
- compute_max_element(array);
- return MIN2(min, array->_MaxElement);
-}
-
-
-/**
- * Update ctx->Array._MaxElement (the max legal index into all enabled arrays).
- * Need to do this upon new array state or new buffer object state.
- */
-static void
-update_arrays( struct gl_context *ctx )
-{
- struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
- GLuint i, min = ~0;
-
- /* find min of _MaxElement values for all enabled arrays */
-
- /* 0 */
- if (ctx->VertexProgram._Current
- && arrayObj->VertexAttrib[VERT_ATTRIB_POS].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_POS]);
- }
- else if (arrayObj->Vertex.Enabled) {
- min = update_min(min, &arrayObj->Vertex);
- }
-
- /* 1 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_WEIGHT].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_WEIGHT]);
- }
- /* no conventional vertex weight array */
-
- /* 2 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_NORMAL].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_NORMAL]);
- }
- else if (arrayObj->Normal.Enabled) {
- min = update_min(min, &arrayObj->Normal);
- }
-
- /* 3 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR0].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR0]);
- }
- else if (arrayObj->Color.Enabled) {
- min = update_min(min, &arrayObj->Color);
- }
-
- /* 4 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR1].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR1]);
- }
- else if (arrayObj->SecondaryColor.Enabled) {
- min = update_min(min, &arrayObj->SecondaryColor);
- }
-
- /* 5 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_FOG].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_FOG]);
- }
- else if (arrayObj->FogCoord.Enabled) {
- min = update_min(min, &arrayObj->FogCoord);
- }
-
- /* 6 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR_INDEX].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR_INDEX]);
- }
- else if (arrayObj->Index.Enabled) {
- min = update_min(min, &arrayObj->Index);
- }
-
- /* 7 */
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[VERT_ATTRIB_EDGEFLAG].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_EDGEFLAG]);
- }
-
- /* 8..15 */
- for (i = VERT_ATTRIB_TEX0; i <= VERT_ATTRIB_TEX7; i++) {
- if (ctx->VertexProgram._Enabled
- && arrayObj->VertexAttrib[i].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[i]);
- }
- else if (i - VERT_ATTRIB_TEX0 < ctx->Const.MaxTextureCoordUnits
- && arrayObj->TexCoord[i - VERT_ATTRIB_TEX0].Enabled) {
- min = update_min(min, &arrayObj->TexCoord[i - VERT_ATTRIB_TEX0]);
- }
- }
-
- /* 16..31 */
- if (ctx->VertexProgram._Current) {
- for (i = 0; i < Elements(arrayObj->VertexAttrib); i++) {
- if (arrayObj->VertexAttrib[i].Enabled) {
- min = update_min(min, &arrayObj->VertexAttrib[i]);
- }
- }
- }
-
- if (arrayObj->EdgeFlag.Enabled) {
- min = update_min(min, &arrayObj->EdgeFlag);
- }
-
- /* _MaxElement is one past the last legal array element */
- arrayObj->_MaxElement = min;
-}
-
-
-/**
- * Update the following fields:
- * ctx->VertexProgram._Enabled
- * ctx->FragmentProgram._Enabled
- * ctx->ATIFragmentShader._Enabled
- * This needs to be done before texture state validation.
- */
-static void
-update_program_enables(struct gl_context *ctx)
-{
- /* These _Enabled flags indicate if the program is enabled AND valid. */
- ctx->VertexProgram._Enabled = ctx->VertexProgram.Enabled
- && ctx->VertexProgram.Current->Base.Instructions;
- ctx->FragmentProgram._Enabled = ctx->FragmentProgram.Enabled
- && ctx->FragmentProgram.Current->Base.Instructions;
- ctx->ATIFragmentShader._Enabled = ctx->ATIFragmentShader.Enabled
- && ctx->ATIFragmentShader.Current->Instructions[0];
-}
-
-
-/**
- * Update vertex/fragment program state. In particular, update these fields:
- * ctx->VertexProgram._Current
- * ctx->VertexProgram._TnlProgram,
- * These point to the highest priority enabled vertex/fragment program or are
- * NULL if fixed-function processing is to be done.
- *
- * This function needs to be called after texture state validation in case
- * we're generating a fragment program from fixed-function texture state.
- *
- * \return bitfield which will indicate _NEW_PROGRAM state if a new vertex
- * or fragment program is being used.
- */
-static GLbitfield
-update_program(struct gl_context *ctx)
-{
- const struct gl_shader_program *vsProg = ctx->Shader.CurrentVertexProgram;
- const struct gl_shader_program *gsProg = ctx->Shader.CurrentGeometryProgram;
- const struct gl_shader_program *fsProg = ctx->Shader.CurrentFragmentProgram;
- const struct gl_vertex_program *prevVP = ctx->VertexProgram._Current;
- const struct gl_fragment_program *prevFP = ctx->FragmentProgram._Current;
- const struct gl_geometry_program *prevGP = ctx->GeometryProgram._Current;
- GLbitfield new_state = 0x0;
-
- /*
- * Set the ctx->VertexProgram._Current and ctx->FragmentProgram._Current
- * pointers to the programs that should be used for rendering. If either
- * is NULL, use fixed-function code paths.
- *
- * These programs may come from several sources. The priority is as
- * follows:
- * 1. OpenGL 2.0/ARB vertex/fragment shaders
- * 2. ARB/NV vertex/fragment programs
- * 3. Programs derived from fixed-function state.
- *
- * Note: it's possible for a vertex shader to get used with a fragment
- * program (and vice versa) here, but in practice that shouldn't ever
- * come up, or matter.
- */
-
- if (fsProg && fsProg->LinkStatus && fsProg->FragmentProgram) {
- /* Use shader programs */
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
- fsProg->FragmentProgram);
- }
- else if (ctx->FragmentProgram._Enabled) {
- /* use user-defined vertex program */
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
- ctx->FragmentProgram.Current);
- }
- else if (ctx->FragmentProgram._MaintainTexEnvProgram) {
- /* Use fragment program generated from fixed-function state.
- */
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
- _mesa_get_fixed_func_fragment_program(ctx));
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram,
- ctx->FragmentProgram._Current);
- }
- else {
- /* no fragment program */
- _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
- }
-
- if (gsProg && gsProg->LinkStatus && gsProg->GeometryProgram) {
- /* Use shader programs */
- _mesa_reference_geomprog(ctx, &ctx->GeometryProgram._Current,
- gsProg->GeometryProgram);
- } else {
- /* no fragment program */
- _mesa_reference_geomprog(ctx, &ctx->GeometryProgram._Current, NULL);
- }
-
- /* Examine vertex program after fragment program as
- * _mesa_get_fixed_func_vertex_program() needs to know active
- * fragprog inputs.
- */
- if (vsProg && vsProg->LinkStatus && vsProg->VertexProgram) {
- /* Use shader programs */
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
- vsProg->VertexProgram);
- }
- else if (ctx->VertexProgram._Enabled) {
- /* use user-defined vertex program */
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
- ctx->VertexProgram.Current);
- }
- else if (ctx->VertexProgram._MaintainTnlProgram) {
- /* Use vertex program generated from fixed-function state.
- */
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
- _mesa_get_fixed_func_vertex_program(ctx));
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram,
- ctx->VertexProgram._Current);
- }
- else {
- /* no vertex program */
- _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
- }
-
- /* Let the driver know what's happening:
- */
- if (ctx->FragmentProgram._Current != prevFP) {
- new_state |= _NEW_PROGRAM;
- if (ctx->Driver.BindProgram) {
- ctx->Driver.BindProgram(ctx, GL_FRAGMENT_PROGRAM_ARB,
- (struct gl_program *) ctx->FragmentProgram._Current);
- }
- }
-
- if (ctx->GeometryProgram._Current != prevGP) {
- new_state |= _NEW_PROGRAM;
- if (ctx->Driver.BindProgram) {
- ctx->Driver.BindProgram(ctx, MESA_GEOMETRY_PROGRAM,
- (struct gl_program *) ctx->GeometryProgram._Current);
- }
- }
-
- if (ctx->VertexProgram._Current != prevVP) {
- new_state |= _NEW_PROGRAM;
- if (ctx->Driver.BindProgram) {
- ctx->Driver.BindProgram(ctx, GL_VERTEX_PROGRAM_ARB,
- (struct gl_program *) ctx->VertexProgram._Current);
- }
- }
-
- return new_state;
-}
-
-
-/**
- * Examine shader constants and return either _NEW_PROGRAM_CONSTANTS or 0.
- */
-static GLbitfield
-update_program_constants(struct gl_context *ctx)
-{
- GLbitfield new_state = 0x0;
-
- if (ctx->FragmentProgram._Current) {
- const struct gl_program_parameter_list *params =
- ctx->FragmentProgram._Current->Base.Parameters;
- if (params && params->StateFlags & ctx->NewState) {
- new_state |= _NEW_PROGRAM_CONSTANTS;
- }
- }
-
- if (ctx->GeometryProgram._Current) {
- const struct gl_program_parameter_list *params =
- ctx->GeometryProgram._Current->Base.Parameters;
- /*FIXME: StateFlags is always 0 because we have unnamed constant
- * not state changes */
- if (params /*&& params->StateFlags & ctx->NewState*/) {
- new_state |= _NEW_PROGRAM_CONSTANTS;
- }
- }
-
- if (ctx->VertexProgram._Current) {
- const struct gl_program_parameter_list *params =
- ctx->VertexProgram._Current->Base.Parameters;
- if (params && params->StateFlags & ctx->NewState) {
- new_state |= _NEW_PROGRAM_CONSTANTS;
- }
- }
-
- return new_state;
-}
-
-
-
-
-static void
-update_viewport_matrix(struct gl_context *ctx)
-{
- const GLfloat depthMax = ctx->DrawBuffer->_DepthMaxF;
-
- ASSERT(depthMax > 0);
-
- /* Compute scale and bias values. This is really driver-specific
- * and should be maintained elsewhere if at all.
- * NOTE: RasterPos uses this.
- */
- _math_matrix_viewport(&ctx->Viewport._WindowMap,
- ctx->Viewport.X, ctx->Viewport.Y,
- ctx->Viewport.Width, ctx->Viewport.Height,
- ctx->Viewport.Near, ctx->Viewport.Far,
- depthMax);
-}
-
-
-/**
- * Update derived multisample state.
- */
-static void
-update_multisample(struct gl_context *ctx)
-{
- ctx->Multisample._Enabled = GL_FALSE;
- if (ctx->Multisample.Enabled &&
- ctx->DrawBuffer &&
- ctx->DrawBuffer->Visual.sampleBuffers)
- ctx->Multisample._Enabled = GL_TRUE;
-}
-
-
-/**
- * Update derived color/blend/logicop state.
- */
-static void
-update_color(struct gl_context *ctx)
-{
- /* This is needed to support 1.1's RGB logic ops AND
- * 1.0's blending logicops.
- */
- ctx->Color._LogicOpEnabled = RGBA_LOGICOP_ENABLED(ctx);
-}
-
-
-/*
- * Check polygon state and set DD_TRI_CULL_FRONT_BACK and/or DD_TRI_OFFSET
- * in ctx->_TriangleCaps if needed.
- */
-static void
-update_polygon(struct gl_context *ctx)
-{
- ctx->_TriangleCaps &= ~(DD_TRI_CULL_FRONT_BACK | DD_TRI_OFFSET);
-
- if (ctx->Polygon.CullFlag && ctx->Polygon.CullFaceMode == GL_FRONT_AND_BACK)
- ctx->_TriangleCaps |= DD_TRI_CULL_FRONT_BACK;
-
- if ( ctx->Polygon.OffsetPoint
- || ctx->Polygon.OffsetLine
- || ctx->Polygon.OffsetFill)
- ctx->_TriangleCaps |= DD_TRI_OFFSET;
-}
-
-
-/**
- * Update the ctx->_TriangleCaps bitfield.
- * XXX that bitfield should really go away someday!
- * This function must be called after other update_*() functions since
- * there are dependencies on some other derived values.
- */
-#if 0
-static void
-update_tricaps(struct gl_context *ctx, GLbitfield new_state)
-{
- ctx->_TriangleCaps = 0;
-
- /*
- * Points
- */
- if (1/*new_state & _NEW_POINT*/) {
- if (ctx->Point.SmoothFlag)
- ctx->_TriangleCaps |= DD_POINT_SMOOTH;
- if (ctx->Point._Attenuated)
- ctx->_TriangleCaps |= DD_POINT_ATTEN;
- }
-
- /*
- * Lines
- */
- if (1/*new_state & _NEW_LINE*/) {
- if (ctx->Line.SmoothFlag)
- ctx->_TriangleCaps |= DD_LINE_SMOOTH;
- if (ctx->Line.StippleFlag)
- ctx->_TriangleCaps |= DD_LINE_STIPPLE;
- }
-
- /*
- * Polygons
- */
- if (1/*new_state & _NEW_POLYGON*/) {
- if (ctx->Polygon.SmoothFlag)
- ctx->_TriangleCaps |= DD_TRI_SMOOTH;
- if (ctx->Polygon.StippleFlag)
- ctx->_TriangleCaps |= DD_TRI_STIPPLE;
- if (ctx->Polygon.FrontMode != GL_FILL
- || ctx->Polygon.BackMode != GL_FILL)
- ctx->_TriangleCaps |= DD_TRI_UNFILLED;
- if (ctx->Polygon.CullFlag
- && ctx->Polygon.CullFaceMode == GL_FRONT_AND_BACK)
- ctx->_TriangleCaps |= DD_TRI_CULL_FRONT_BACK;
- if (ctx->Polygon.OffsetPoint ||
- ctx->Polygon.OffsetLine ||
- ctx->Polygon.OffsetFill)
- ctx->_TriangleCaps |= DD_TRI_OFFSET;
- }
-
- /*
- * Lighting and shading
- */
- if (ctx->Light.Enabled && ctx->Light.Model.TwoSide)
- ctx->_TriangleCaps |= DD_TRI_LIGHT_TWOSIDE;
- if (ctx->Light.ShadeModel == GL_FLAT)
- ctx->_TriangleCaps |= DD_FLATSHADE;
- if (NEED_SECONDARY_COLOR(ctx))
- ctx->_TriangleCaps |= DD_SEPARATE_SPECULAR;
-
- /*
- * Stencil
- */
- if (ctx->Stencil._TestTwoSide)
- ctx->_TriangleCaps |= DD_TRI_TWOSTENCIL;
-}
-#endif
-
-
-/**
- * Compute derived GL state.
- * If __struct gl_contextRec::NewState is non-zero then this function \b must
- * be called before rendering anything.
- *
- * Calls dd_function_table::UpdateState to perform any internal state
- * management necessary.
- *
- * \sa _mesa_update_modelview_project(), _mesa_update_texture(),
- * _mesa_update_buffer_bounds(),
- * _mesa_update_lighting() and _mesa_update_tnl_spaces().
- */
-void
-_mesa_update_state_locked( struct gl_context *ctx )
-{
- GLbitfield new_state = ctx->NewState;
- GLbitfield prog_flags = _NEW_PROGRAM;
- GLbitfield new_prog_state = 0x0;
-
- if (new_state == _NEW_CURRENT_ATTRIB)
- goto out;
-
- if (MESA_VERBOSE & VERBOSE_STATE)
- _mesa_print_state("_mesa_update_state", new_state);
-
- /* Determine which state flags effect vertex/fragment program state */
- if (ctx->FragmentProgram._MaintainTexEnvProgram) {
- prog_flags |= (_NEW_BUFFERS | _NEW_TEXTURE | _NEW_FOG |
- _NEW_ARRAY | _NEW_LIGHT | _NEW_POINT | _NEW_RENDERMODE |
- _NEW_PROGRAM);
- }
- if (ctx->VertexProgram._MaintainTnlProgram) {
- prog_flags |= (_NEW_ARRAY | _NEW_TEXTURE | _NEW_TEXTURE_MATRIX |
- _NEW_TRANSFORM | _NEW_POINT |
- _NEW_FOG | _NEW_LIGHT |
- _MESA_NEW_NEED_EYE_COORDS);
- }
-
- /*
- * Now update derived state info
- */
-
- if (new_state & prog_flags)
- update_program_enables( ctx );
-
- if (new_state & (_NEW_MODELVIEW|_NEW_PROJECTION))
- _mesa_update_modelview_project( ctx, new_state );
-
- if (new_state & (_NEW_PROGRAM|_NEW_TEXTURE|_NEW_TEXTURE_MATRIX))
- _mesa_update_texture( ctx, new_state );
-
- if (new_state & _NEW_BUFFERS)
- _mesa_update_framebuffer(ctx);
-
- if (new_state & (_NEW_SCISSOR | _NEW_BUFFERS | _NEW_VIEWPORT))
- _mesa_update_draw_buffer_bounds( ctx );
-
- if (new_state & _NEW_POLYGON)
- update_polygon( ctx );
-
- if (new_state & _NEW_LIGHT)
- _mesa_update_lighting( ctx );
-
- if (new_state & (_NEW_STENCIL | _NEW_BUFFERS))
- _mesa_update_stencil( ctx );
-
- if (new_state & _MESA_NEW_TRANSFER_STATE)
- _mesa_update_pixel( ctx, new_state );
-
- if (new_state & _DD_NEW_SEPARATE_SPECULAR)
- update_separate_specular( ctx );
-
- if (new_state & (_NEW_BUFFERS | _NEW_VIEWPORT))
- update_viewport_matrix(ctx);
-
- if (new_state & _NEW_MULTISAMPLE)
- update_multisample( ctx );
-
- if (new_state & _NEW_COLOR)
- update_color( ctx );
-
-#if 0
- if (new_state & (_NEW_POINT | _NEW_LINE | _NEW_POLYGON | _NEW_LIGHT
- | _NEW_STENCIL | _DD_NEW_SEPARATE_SPECULAR))
- update_tricaps( ctx, new_state );
-#endif
-
- /* ctx->_NeedEyeCoords is now up to date.
- *
- * If the truth value of this variable has changed, update for the
- * new lighting space and recompute the positions of lights and the
- * normal transform.
- *
- * If the lighting space hasn't changed, may still need to recompute
- * light positions & normal transforms for other reasons.
- */
- if (new_state & _MESA_NEW_NEED_EYE_COORDS)
- _mesa_update_tnl_spaces( ctx, new_state );
-
- if (new_state & prog_flags) {
- /* When we generate programs from fixed-function vertex/fragment state
- * this call may generate/bind a new program. If so, we need to
- * propogate the _NEW_PROGRAM flag to the driver.
- */
- new_prog_state |= update_program( ctx );
- }
-
- if (new_state & (_NEW_ARRAY | _NEW_PROGRAM | _NEW_BUFFER_OBJECT))
- update_arrays( ctx );
-
- out:
- new_prog_state |= update_program_constants(ctx);
-
- /*
- * Give the driver a chance to act upon the new_state flags.
- * The driver might plug in different span functions, for example.
- * Also, this is where the driver can invalidate the state of any
- * active modules (such as swrast_setup, swrast, tnl, etc).
- *
- * Set ctx->NewState to zero to avoid recursion if
- * Driver.UpdateState() has to call FLUSH_VERTICES(). (fixed?)
- */
- new_state = ctx->NewState | new_prog_state;
- ctx->NewState = 0;
- ctx->Driver.UpdateState(ctx, new_state);
- ctx->Array.NewState = 0;
- if (!ctx->Array.RebindArrays)
- ctx->Array.RebindArrays = (new_state & (_NEW_ARRAY | _NEW_PROGRAM)) != 0;
-}
-
-
-/* This is the usual entrypoint for state updates:
- */
-void
-_mesa_update_state( struct gl_context *ctx )
-{
- _mesa_lock_context_textures(ctx);
- _mesa_update_state_locked(ctx);
- _mesa_unlock_context_textures(ctx);
-}
-
-
-
-
-/**
- * Want to figure out which fragment program inputs are actually
- * constant/current values from ctx->Current. These should be
- * referenced as a tracked state variable rather than a fragment
- * program input, to save the overhead of putting a constant value in
- * every submitted vertex, transferring it to hardware, interpolating
- * it across the triangle, etc...
- *
- * When there is a VP bound, just use vp->outputs. But when we're
- * generating vp from fixed function state, basically want to
- * calculate:
- *
- * vp_out_2_fp_in( vp_in_2_vp_out( varying_inputs ) |
- * potential_vp_outputs )
- *
- * Where potential_vp_outputs is calculated by looking at enabled
- * texgen, etc.
- *
- * The generated fragment program should then only declare inputs that
- * may vary or otherwise differ from the ctx->Current values.
- * Otherwise, the fp should track them as state values instead.
- */
-void
-_mesa_set_varying_vp_inputs( struct gl_context *ctx,
- GLbitfield varying_inputs )
-{
- if (ctx->varying_vp_inputs != varying_inputs) {
- ctx->varying_vp_inputs = varying_inputs;
- ctx->NewState |= _NEW_ARRAY;
- /*printf("%s %x\n", __FUNCTION__, varying_inputs);*/
- }
-}
-
-
-/**
- * Used by drivers to tell core Mesa that the driver is going to
- * install/ use its own vertex program. In particular, this will
- * prevent generated fragment programs from using state vars instead
- * of ordinary varyings/inputs.
- */
-void
-_mesa_set_vp_override(struct gl_context *ctx, GLboolean flag)
-{
- if (ctx->VertexProgram._Overriden != flag) {
- ctx->VertexProgram._Overriden = flag;
-
- /* Set one of the bits which will trigger fragment program
- * regeneration:
- */
- ctx->NewState |= _NEW_PROGRAM;
- }
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.3
+ *
+ * Copyright (C) 1999-2008 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 state.c
+ * State management.
+ *
+ * This file manages recalculation of derived values in struct gl_context.
+ */
+
+
+#include "glheader.h"
+#include "mtypes.h"
+#include "context.h"
+#include "debug.h"
+#include "macros.h"
+#include "ffvertex_prog.h"
+#include "framebuffer.h"
+#include "light.h"
+#include "matrix.h"
+#include "pixel.h"
+#include "program/program.h"
+#include "program/prog_parameter.h"
+#include "state.h"
+#include "stencil.h"
+#include "texenvprogram.h"
+#include "texobj.h"
+#include "texstate.h"
+
+
+static void
+update_separate_specular(struct gl_context *ctx)
+{
+ if (NEED_SECONDARY_COLOR(ctx))
+ ctx->_TriangleCaps |= DD_SEPARATE_SPECULAR;
+ else
+ ctx->_TriangleCaps &= ~DD_SEPARATE_SPECULAR;
+}
+
+
+/**
+ * Compute the index of the last array element that can be safely accessed
+ * in a vertex array. We can really only do this when the array lives in
+ * a VBO.
+ * The array->_MaxElement field will be updated.
+ * Later in glDrawArrays/Elements/etc we can do some bounds checking.
+ */
+static void
+compute_max_element(struct gl_client_array *array)
+{
+ assert(array->Enabled);
+ if (array->BufferObj->Name) {
+ GLsizeiptrARB offset = (GLsizeiptrARB) array->Ptr;
+ GLsizeiptrARB obj_size = (GLsizeiptrARB) array->BufferObj->Size;
+
+ if (offset < obj_size) {
+ array->_MaxElement = (obj_size - offset +
+ array->StrideB -
+ array->_ElementSize) / array->StrideB;
+ } else {
+ array->_MaxElement = 0;
+ }
+ }
+ else {
+ /* user-space array, no idea how big it is */
+ array->_MaxElement = 2 * 1000 * 1000 * 1000; /* just a big number */
+ }
+}
+
+
+/**
+ * Helper for update_arrays().
+ * \return min(current min, array->_MaxElement).
+ */
+static GLuint
+update_min(GLuint min, struct gl_client_array *array)
+{
+ compute_max_element(array);
+ return MIN2(min, array->_MaxElement);
+}
+
+
+/**
+ * Update ctx->Array._MaxElement (the max legal index into all enabled arrays).
+ * Need to do this upon new array state or new buffer object state.
+ */
+static void
+update_arrays( struct gl_context *ctx )
+{
+ struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
+ GLuint i, min = ~0;
+
+ /* find min of _MaxElement values for all enabled arrays */
+
+ /* 0 */
+ if (ctx->VertexProgram._Current
+ && arrayObj->VertexAttrib[VERT_ATTRIB_POS].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_POS]);
+ }
+ else if (arrayObj->Vertex.Enabled) {
+ min = update_min(min, &arrayObj->Vertex);
+ }
+
+ /* 1 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_WEIGHT].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_WEIGHT]);
+ }
+ /* no conventional vertex weight array */
+
+ /* 2 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_NORMAL].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_NORMAL]);
+ }
+ else if (arrayObj->Normal.Enabled) {
+ min = update_min(min, &arrayObj->Normal);
+ }
+
+ /* 3 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR0].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR0]);
+ }
+ else if (arrayObj->Color.Enabled) {
+ min = update_min(min, &arrayObj->Color);
+ }
+
+ /* 4 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR1].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR1]);
+ }
+ else if (arrayObj->SecondaryColor.Enabled) {
+ min = update_min(min, &arrayObj->SecondaryColor);
+ }
+
+ /* 5 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_FOG].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_FOG]);
+ }
+ else if (arrayObj->FogCoord.Enabled) {
+ min = update_min(min, &arrayObj->FogCoord);
+ }
+
+ /* 6 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_COLOR_INDEX].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_COLOR_INDEX]);
+ }
+ else if (arrayObj->Index.Enabled) {
+ min = update_min(min, &arrayObj->Index);
+ }
+
+ /* 7 */
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[VERT_ATTRIB_EDGEFLAG].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[VERT_ATTRIB_EDGEFLAG]);
+ }
+
+ /* 8..15 */
+ for (i = VERT_ATTRIB_TEX0; i <= VERT_ATTRIB_TEX7; i++) {
+ if (ctx->VertexProgram._Enabled
+ && arrayObj->VertexAttrib[i].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[i]);
+ }
+ else if (i - VERT_ATTRIB_TEX0 < ctx->Const.MaxTextureCoordUnits
+ && arrayObj->TexCoord[i - VERT_ATTRIB_TEX0].Enabled) {
+ min = update_min(min, &arrayObj->TexCoord[i - VERT_ATTRIB_TEX0]);
+ }
+ }
+
+ /* 16..31 */
+ if (ctx->VertexProgram._Current) {
+ for (i = 0; i < Elements(arrayObj->VertexAttrib); i++) {
+ if (arrayObj->VertexAttrib[i].Enabled) {
+ min = update_min(min, &arrayObj->VertexAttrib[i]);
+ }
+ }
+ }
+
+ if (arrayObj->EdgeFlag.Enabled) {
+ min = update_min(min, &arrayObj->EdgeFlag);
+ }
+
+ /* _MaxElement is one past the last legal array element */
+ arrayObj->_MaxElement = min;
+}
+
+
+/**
+ * Update the following fields:
+ * ctx->VertexProgram._Enabled
+ * ctx->FragmentProgram._Enabled
+ * ctx->ATIFragmentShader._Enabled
+ * This needs to be done before texture state validation.
+ */
+static void
+update_program_enables(struct gl_context *ctx)
+{
+ /* These _Enabled flags indicate if the program is enabled AND valid. */
+ ctx->VertexProgram._Enabled = ctx->VertexProgram.Enabled
+ && ctx->VertexProgram.Current->Base.Instructions;
+ ctx->FragmentProgram._Enabled = ctx->FragmentProgram.Enabled
+ && ctx->FragmentProgram.Current->Base.Instructions;
+ ctx->ATIFragmentShader._Enabled = ctx->ATIFragmentShader.Enabled
+ && ctx->ATIFragmentShader.Current->Instructions[0];
+}
+
+
+/**
+ * Update vertex/fragment program state. In particular, update these fields:
+ * ctx->VertexProgram._Current
+ * ctx->VertexProgram._TnlProgram,
+ * These point to the highest priority enabled vertex/fragment program or are
+ * NULL if fixed-function processing is to be done.
+ *
+ * This function needs to be called after texture state validation in case
+ * we're generating a fragment program from fixed-function texture state.
+ *
+ * \return bitfield which will indicate _NEW_PROGRAM state if a new vertex
+ * or fragment program is being used.
+ */
+static GLbitfield
+update_program(struct gl_context *ctx)
+{
+ const struct gl_shader_program *vsProg = ctx->Shader.CurrentVertexProgram;
+ const struct gl_shader_program *gsProg = ctx->Shader.CurrentGeometryProgram;
+ const struct gl_shader_program *fsProg = ctx->Shader.CurrentFragmentProgram;
+ const struct gl_vertex_program *prevVP = ctx->VertexProgram._Current;
+ const struct gl_fragment_program *prevFP = ctx->FragmentProgram._Current;
+ const struct gl_geometry_program *prevGP = ctx->GeometryProgram._Current;
+ GLbitfield new_state = 0x0;
+
+ /*
+ * Set the ctx->VertexProgram._Current and ctx->FragmentProgram._Current
+ * pointers to the programs that should be used for rendering. If either
+ * is NULL, use fixed-function code paths.
+ *
+ * These programs may come from several sources. The priority is as
+ * follows:
+ * 1. OpenGL 2.0/ARB vertex/fragment shaders
+ * 2. ARB/NV vertex/fragment programs
+ * 3. Programs derived from fixed-function state.
+ *
+ * Note: it's possible for a vertex shader to get used with a fragment
+ * program (and vice versa) here, but in practice that shouldn't ever
+ * come up, or matter.
+ */
+
+ if (fsProg && fsProg->LinkStatus && fsProg->FragmentProgram) {
+ /* Use shader programs */
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
+ fsProg->FragmentProgram);
+ }
+ else if (ctx->FragmentProgram._Enabled) {
+ /* use user-defined vertex program */
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
+ ctx->FragmentProgram.Current);
+ }
+ else if (ctx->FragmentProgram._MaintainTexEnvProgram) {
+ /* Use fragment program generated from fixed-function state.
+ */
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current,
+ _mesa_get_fixed_func_fragment_program(ctx));
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._TexEnvProgram,
+ ctx->FragmentProgram._Current);
+ }
+ else {
+ /* no fragment program */
+ _mesa_reference_fragprog(ctx, &ctx->FragmentProgram._Current, NULL);
+ }
+
+ if (gsProg && gsProg->LinkStatus && gsProg->GeometryProgram) {
+ /* Use shader programs */
+ _mesa_reference_geomprog(ctx, &ctx->GeometryProgram._Current,
+ gsProg->GeometryProgram);
+ } else {
+ /* no fragment program */
+ _mesa_reference_geomprog(ctx, &ctx->GeometryProgram._Current, NULL);
+ }
+
+ /* Examine vertex program after fragment program as
+ * _mesa_get_fixed_func_vertex_program() needs to know active
+ * fragprog inputs.
+ */
+ if (vsProg && vsProg->LinkStatus && vsProg->VertexProgram) {
+ /* Use shader programs */
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
+ vsProg->VertexProgram);
+ }
+ else if (ctx->VertexProgram._Enabled) {
+ /* use user-defined vertex program */
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
+ ctx->VertexProgram.Current);
+ }
+ else if (ctx->VertexProgram._MaintainTnlProgram) {
+ /* Use vertex program generated from fixed-function state.
+ */
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current,
+ _mesa_get_fixed_func_vertex_program(ctx));
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._TnlProgram,
+ ctx->VertexProgram._Current);
+ }
+ else {
+ /* no vertex program */
+ _mesa_reference_vertprog(ctx, &ctx->VertexProgram._Current, NULL);
+ }
+
+ /* Let the driver know what's happening:
+ */
+ if (ctx->FragmentProgram._Current != prevFP) {
+ new_state |= _NEW_PROGRAM;
+ if (ctx->Driver.BindProgram) {
+ ctx->Driver.BindProgram(ctx, GL_FRAGMENT_PROGRAM_ARB,
+ (struct gl_program *) ctx->FragmentProgram._Current);
+ }
+ }
+
+ if (ctx->GeometryProgram._Current != prevGP) {
+ new_state |= _NEW_PROGRAM;
+ if (ctx->Driver.BindProgram) {
+ ctx->Driver.BindProgram(ctx, MESA_GEOMETRY_PROGRAM,
+ (struct gl_program *) ctx->GeometryProgram._Current);
+ }
+ }
+
+ if (ctx->VertexProgram._Current != prevVP) {
+ new_state |= _NEW_PROGRAM;
+ if (ctx->Driver.BindProgram) {
+ ctx->Driver.BindProgram(ctx, GL_VERTEX_PROGRAM_ARB,
+ (struct gl_program *) ctx->VertexProgram._Current);
+ }
+ }
+
+ return new_state;
+}
+
+
+/**
+ * Examine shader constants and return either _NEW_PROGRAM_CONSTANTS or 0.
+ */
+static GLbitfield
+update_program_constants(struct gl_context *ctx)
+{
+ GLbitfield new_state = 0x0;
+
+ if (ctx->FragmentProgram._Current) {
+ const struct gl_program_parameter_list *params =
+ ctx->FragmentProgram._Current->Base.Parameters;
+ if (params && params->StateFlags & ctx->NewState) {
+ new_state |= _NEW_PROGRAM_CONSTANTS;
+ }
+ }
+
+ if (ctx->GeometryProgram._Current) {
+ const struct gl_program_parameter_list *params =
+ ctx->GeometryProgram._Current->Base.Parameters;
+ /*FIXME: StateFlags is always 0 because we have unnamed constant
+ * not state changes */
+ if (params /*&& params->StateFlags & ctx->NewState*/) {
+ new_state |= _NEW_PROGRAM_CONSTANTS;
+ }
+ }
+
+ if (ctx->VertexProgram._Current) {
+ const struct gl_program_parameter_list *params =
+ ctx->VertexProgram._Current->Base.Parameters;
+ if (params && params->StateFlags & ctx->NewState) {
+ new_state |= _NEW_PROGRAM_CONSTANTS;
+ }
+ }
+
+ return new_state;
+}
+
+
+
+
+static void
+update_viewport_matrix(struct gl_context *ctx)
+{
+ const GLfloat depthMax = ctx->DrawBuffer->_DepthMaxF;
+
+ ASSERT(depthMax > 0);
+
+ /* Compute scale and bias values. This is really driver-specific
+ * and should be maintained elsewhere if at all.
+ * NOTE: RasterPos uses this.
+ */
+ _math_matrix_viewport(&ctx->Viewport._WindowMap,
+ ctx->Viewport.X, ctx->Viewport.Y,
+ ctx->Viewport.Width, ctx->Viewport.Height,
+ ctx->Viewport.Near, ctx->Viewport.Far,
+ depthMax);
+}
+
+
+/**
+ * Update derived multisample state.
+ */
+static void
+update_multisample(struct gl_context *ctx)
+{
+ ctx->Multisample._Enabled = GL_FALSE;
+ if (ctx->Multisample.Enabled &&
+ ctx->DrawBuffer &&
+ ctx->DrawBuffer->Visual.sampleBuffers)
+ ctx->Multisample._Enabled = GL_TRUE;
+}
+
+
+/**
+ * Update derived color/blend/logicop state.
+ */
+static void
+update_color(struct gl_context *ctx)
+{
+ /* This is needed to support 1.1's RGB logic ops AND
+ * 1.0's blending logicops.
+ */
+ ctx->Color._LogicOpEnabled = RGBA_LOGICOP_ENABLED(ctx);
+}
+
+
+/*
+ * Check polygon state and set DD_TRI_CULL_FRONT_BACK and/or DD_TRI_OFFSET
+ * in ctx->_TriangleCaps if needed.
+ */
+static void
+update_polygon(struct gl_context *ctx)
+{
+ ctx->_TriangleCaps &= ~(DD_TRI_CULL_FRONT_BACK | DD_TRI_OFFSET);
+
+ if (ctx->Polygon.CullFlag && ctx->Polygon.CullFaceMode == GL_FRONT_AND_BACK)
+ ctx->_TriangleCaps |= DD_TRI_CULL_FRONT_BACK;
+
+ if ( ctx->Polygon.OffsetPoint
+ || ctx->Polygon.OffsetLine
+ || ctx->Polygon.OffsetFill)
+ ctx->_TriangleCaps |= DD_TRI_OFFSET;
+}
+
+
+/**
+ * Update the ctx->_TriangleCaps bitfield.
+ * XXX that bitfield should really go away someday!
+ * This function must be called after other update_*() functions since
+ * there are dependencies on some other derived values.
+ */
+#if 0
+static void
+update_tricaps(struct gl_context *ctx, GLbitfield new_state)
+{
+ ctx->_TriangleCaps = 0;
+
+ /*
+ * Points
+ */
+ if (1/*new_state & _NEW_POINT*/) {
+ if (ctx->Point.SmoothFlag)
+ ctx->_TriangleCaps |= DD_POINT_SMOOTH;
+ if (ctx->Point._Attenuated)
+ ctx->_TriangleCaps |= DD_POINT_ATTEN;
+ }
+
+ /*
+ * Lines
+ */
+ if (1/*new_state & _NEW_LINE*/) {
+ if (ctx->Line.SmoothFlag)
+ ctx->_TriangleCaps |= DD_LINE_SMOOTH;
+ if (ctx->Line.StippleFlag)
+ ctx->_TriangleCaps |= DD_LINE_STIPPLE;
+ }
+
+ /*
+ * Polygons
+ */
+ if (1/*new_state & _NEW_POLYGON*/) {
+ if (ctx->Polygon.SmoothFlag)
+ ctx->_TriangleCaps |= DD_TRI_SMOOTH;
+ if (ctx->Polygon.StippleFlag)
+ ctx->_TriangleCaps |= DD_TRI_STIPPLE;
+ if (ctx->Polygon.FrontMode != GL_FILL
+ || ctx->Polygon.BackMode != GL_FILL)
+ ctx->_TriangleCaps |= DD_TRI_UNFILLED;
+ if (ctx->Polygon.CullFlag
+ && ctx->Polygon.CullFaceMode == GL_FRONT_AND_BACK)
+ ctx->_TriangleCaps |= DD_TRI_CULL_FRONT_BACK;
+ if (ctx->Polygon.OffsetPoint ||
+ ctx->Polygon.OffsetLine ||
+ ctx->Polygon.OffsetFill)
+ ctx->_TriangleCaps |= DD_TRI_OFFSET;
+ }
+
+ /*
+ * Lighting and shading
+ */
+ if (ctx->Light.Enabled && ctx->Light.Model.TwoSide)
+ ctx->_TriangleCaps |= DD_TRI_LIGHT_TWOSIDE;
+ if (ctx->Light.ShadeModel == GL_FLAT)
+ ctx->_TriangleCaps |= DD_FLATSHADE;
+ if (NEED_SECONDARY_COLOR(ctx))
+ ctx->_TriangleCaps |= DD_SEPARATE_SPECULAR;
+
+ /*
+ * Stencil
+ */
+ if (ctx->Stencil._TestTwoSide)
+ ctx->_TriangleCaps |= DD_TRI_TWOSTENCIL;
+}
+#endif
+
+
+/**
+ * Compute derived GL state.
+ * If __struct gl_contextRec::NewState is non-zero then this function \b must
+ * be called before rendering anything.
+ *
+ * Calls dd_function_table::UpdateState to perform any internal state
+ * management necessary.
+ *
+ * \sa _mesa_update_modelview_project(), _mesa_update_texture(),
+ * _mesa_update_buffer_bounds(),
+ * _mesa_update_lighting() and _mesa_update_tnl_spaces().
+ */
+void
+_mesa_update_state_locked( struct gl_context *ctx )
+{
+ GLbitfield new_state = ctx->NewState;
+ GLbitfield prog_flags = _NEW_PROGRAM;
+ GLbitfield new_prog_state = 0x0;
+
+ if (new_state == _NEW_CURRENT_ATTRIB)
+ goto out;
+
+ if (MESA_VERBOSE & VERBOSE_STATE)
+ _mesa_print_state("_mesa_update_state", new_state);
+
+ /* Determine which state flags effect vertex/fragment program state */
+ if (ctx->FragmentProgram._MaintainTexEnvProgram) {
+ prog_flags |= (_NEW_BUFFERS | _NEW_TEXTURE | _NEW_FOG |
+ _NEW_ARRAY | _NEW_LIGHT | _NEW_POINT | _NEW_RENDERMODE |
+ _NEW_PROGRAM);
+ }
+ if (ctx->VertexProgram._MaintainTnlProgram) {
+ prog_flags |= (_NEW_ARRAY | _NEW_TEXTURE | _NEW_TEXTURE_MATRIX |
+ _NEW_TRANSFORM | _NEW_POINT |
+ _NEW_FOG | _NEW_LIGHT |
+ _MESA_NEW_NEED_EYE_COORDS);
+ }
+
+ /*
+ * Now update derived state info
+ */
+
+ if (new_state & prog_flags)
+ update_program_enables( ctx );
+
+ if (new_state & (_NEW_MODELVIEW|_NEW_PROJECTION))
+ _mesa_update_modelview_project( ctx, new_state );
+
+ if (new_state & (_NEW_PROGRAM|_NEW_TEXTURE|_NEW_TEXTURE_MATRIX))
+ _mesa_update_texture( ctx, new_state );
+
+ if (new_state & _NEW_BUFFERS)
+ _mesa_update_framebuffer(ctx);
+
+ if (new_state & (_NEW_SCISSOR | _NEW_BUFFERS | _NEW_VIEWPORT))
+ _mesa_update_draw_buffer_bounds( ctx );
+
+ if (new_state & _NEW_POLYGON)
+ update_polygon( ctx );
+
+ if (new_state & _NEW_LIGHT)
+ _mesa_update_lighting( ctx );
+
+ if (new_state & (_NEW_STENCIL | _NEW_BUFFERS))
+ _mesa_update_stencil( ctx );
+
+ if (new_state & _MESA_NEW_TRANSFER_STATE)
+ _mesa_update_pixel( ctx, new_state );
+
+ if (new_state & _DD_NEW_SEPARATE_SPECULAR)
+ update_separate_specular( ctx );
+
+ if (new_state & (_NEW_BUFFERS | _NEW_VIEWPORT))
+ update_viewport_matrix(ctx);
+
+ if (new_state & _NEW_MULTISAMPLE)
+ update_multisample( ctx );
+
+ if (new_state & _NEW_COLOR)
+ update_color( ctx );
+
+#if 0
+ if (new_state & (_NEW_POINT | _NEW_LINE | _NEW_POLYGON | _NEW_LIGHT
+ | _NEW_STENCIL | _DD_NEW_SEPARATE_SPECULAR))
+ update_tricaps( ctx, new_state );
+#endif
+
+ /* ctx->_NeedEyeCoords is now up to date.
+ *
+ * If the truth value of this variable has changed, update for the
+ * new lighting space and recompute the positions of lights and the
+ * normal transform.
+ *
+ * If the lighting space hasn't changed, may still need to recompute
+ * light positions & normal transforms for other reasons.
+ */
+ if (new_state & _MESA_NEW_NEED_EYE_COORDS)
+ _mesa_update_tnl_spaces( ctx, new_state );
+
+ if (new_state & prog_flags) {
+ /* When we generate programs from fixed-function vertex/fragment state
+ * this call may generate/bind a new program. If so, we need to
+ * propogate the _NEW_PROGRAM flag to the driver.
+ */
+ new_prog_state |= update_program( ctx );
+ }
+
+ if (new_state & (_NEW_ARRAY | _NEW_PROGRAM | _NEW_BUFFER_OBJECT))
+ update_arrays( ctx );
+
+ out:
+ new_prog_state |= update_program_constants(ctx);
+
+ /*
+ * Give the driver a chance to act upon the new_state flags.
+ * The driver might plug in different span functions, for example.
+ * Also, this is where the driver can invalidate the state of any
+ * active modules (such as swrast_setup, swrast, tnl, etc).
+ *
+ * Set ctx->NewState to zero to avoid recursion if
+ * Driver.UpdateState() has to call FLUSH_VERTICES(). (fixed?)
+ */
+ new_state = ctx->NewState | new_prog_state;
+ ctx->NewState = 0;
+ ctx->Driver.UpdateState(ctx, new_state);
+ ctx->Array.NewState = 0;
+ if (!ctx->Array.RebindArrays)
+ ctx->Array.RebindArrays = (new_state & (_NEW_ARRAY | _NEW_PROGRAM)) != 0;
+}
+
+
+/* This is the usual entrypoint for state updates:
+ */
+void
+_mesa_update_state( struct gl_context *ctx )
+{
+ _mesa_lock_context_textures(ctx);
+ _mesa_update_state_locked(ctx);
+ _mesa_unlock_context_textures(ctx);
+}
+
+
+
+
+/**
+ * Want to figure out which fragment program inputs are actually
+ * constant/current values from ctx->Current. These should be
+ * referenced as a tracked state variable rather than a fragment
+ * program input, to save the overhead of putting a constant value in
+ * every submitted vertex, transferring it to hardware, interpolating
+ * it across the triangle, etc...
+ *
+ * When there is a VP bound, just use vp->outputs. But when we're
+ * generating vp from fixed function state, basically want to
+ * calculate:
+ *
+ * vp_out_2_fp_in( vp_in_2_vp_out( varying_inputs ) |
+ * potential_vp_outputs )
+ *
+ * Where potential_vp_outputs is calculated by looking at enabled
+ * texgen, etc.
+ *
+ * The generated fragment program should then only declare inputs that
+ * may vary or otherwise differ from the ctx->Current values.
+ * Otherwise, the fp should track them as state values instead.
+ */
+void
+_mesa_set_varying_vp_inputs( struct gl_context *ctx,
+ GLbitfield varying_inputs )
+{
+ if (ctx->varying_vp_inputs != varying_inputs) {
+ ctx->varying_vp_inputs = varying_inputs;
+ ctx->NewState |= _NEW_ARRAY;
+ /*printf("%s %x\n", __FUNCTION__, varying_inputs);*/
+ }
+}
+
+
+/**
+ * Used by drivers to tell core Mesa that the driver is going to
+ * install/ use its own vertex program. In particular, this will
+ * prevent generated fragment programs from using state vars instead
+ * of ordinary varyings/inputs.
+ */
+void
+_mesa_set_vp_override(struct gl_context *ctx, GLboolean flag)
+{
+ if (ctx->VertexProgram._Overriden != flag) {
+ ctx->VertexProgram._Overriden = flag;
+
+ /* Set one of the bits which will trigger fragment program
+ * regeneration:
+ */
+ ctx->NewState |= _NEW_PROGRAM;
+ }
+}
diff --git a/mesalib/src/mesa/main/stencil.c b/mesalib/src/mesa/main/stencil.c
index d898bf1d7..b49ddbdbb 100644
--- a/mesalib/src/mesa/main/stencil.c
+++ b/mesalib/src/mesa/main/stencil.c
@@ -1,614 +1,614 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.1
- *
- * Copyright (C) 1999-2007 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 stencil.c
- * Stencil operations.
- *
- * Note: There's some conflict between GL_EXT_stencil_two_side and
- * OpenGL 2.0's two-sided stencil feature.
- *
- * With GL_EXT_stencil_two_side, calling glStencilOp/Func/Mask() only the
- * front OR back face state (as set by glActiveStencilFaceEXT) is set.
- *
- * But with OpenGL 2.0, calling glStencilOp/Func/Mask() sets BOTH the
- * front AND back state.
- *
- * Also, note that GL_ATI_separate_stencil is different as well:
- * glStencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, ...) vs.
- * glStencilFuncSeparate(GLenum face, GLenum func, ...).
- *
- * This problem is solved by keeping three sets of stencil state:
- * state[0] = GL_FRONT state.
- * state[1] = OpenGL 2.0 / GL_ATI_separate_stencil GL_BACK state.
- * state[2] = GL_EXT_stencil_two_side GL_BACK state.
- */
-
-
-#include "glheader.h"
-#include "imports.h"
-#include "context.h"
-#include "macros.h"
-#include "stencil.h"
-#include "mtypes.h"
-
-
-static GLboolean
-validate_stencil_op(struct gl_context *ctx, GLenum op)
-{
- switch (op) {
- case GL_KEEP:
- case GL_ZERO:
- case GL_REPLACE:
- case GL_INCR:
- case GL_DECR:
- case GL_INVERT:
- return GL_TRUE;
- case GL_INCR_WRAP_EXT:
- case GL_DECR_WRAP_EXT:
- if (ctx->Extensions.EXT_stencil_wrap) {
- return GL_TRUE;
- }
- /* FALL-THROUGH */
- default:
- return GL_FALSE;
- }
-}
-
-
-static GLboolean
-validate_stencil_func(struct gl_context *ctx, GLenum func)
-{
- switch (func) {
- case GL_NEVER:
- case GL_LESS:
- case GL_LEQUAL:
- case GL_GREATER:
- case GL_GEQUAL:
- case GL_EQUAL:
- case GL_NOTEQUAL:
- case GL_ALWAYS:
- return GL_TRUE;
- default:
- return GL_FALSE;
- }
-}
-
-
-/**
- * Set the clear value for the stencil buffer.
- *
- * \param s clear value.
- *
- * \sa glClearStencil().
- *
- * Updates gl_stencil_attrib::Clear. On change
- * flushes the vertices and notifies the driver via
- * the dd_function_table::ClearStencil callback.
- */
-void GLAPIENTRY
-_mesa_ClearStencil( GLint s )
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (ctx->Stencil.Clear == (GLuint) s)
- return;
-
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.Clear = (GLuint) s;
-
- if (ctx->Driver.ClearStencil) {
- ctx->Driver.ClearStencil( ctx, s );
- }
-}
-
-
-/**
- * Set the function and reference value for stencil testing.
- *
- * \param frontfunc front test function.
- * \param backfunc back test function.
- * \param ref front and back reference value.
- * \param mask front and back bitmask.
- *
- * \sa glStencilFunc().
- *
- * Verifies the parameters and updates the respective values in
- * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
- * driver via the dd_function_table::StencilFunc callback.
- */
-void GLAPIENTRY
-_mesa_StencilFuncSeparateATI( GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask )
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilFuncSeparateATI()\n");
-
- if (!validate_stencil_func(ctx, frontfunc)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glStencilFuncSeparateATI(frontfunc)");
- return;
- }
- if (!validate_stencil_func(ctx, backfunc)) {
- _mesa_error(ctx, GL_INVALID_ENUM,
- "glStencilFuncSeparateATI(backfunc)");
- return;
- }
-
- ref = CLAMP( ref, 0, stencilMax );
-
- /* set both front and back state */
- if (ctx->Stencil.Function[0] == frontfunc &&
- ctx->Stencil.Function[1] == backfunc &&
- ctx->Stencil.ValueMask[0] == mask &&
- ctx->Stencil.ValueMask[1] == mask &&
- ctx->Stencil.Ref[0] == ref &&
- ctx->Stencil.Ref[1] == ref)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.Function[0] = frontfunc;
- ctx->Stencil.Function[1] = backfunc;
- ctx->Stencil.Ref[0] = ctx->Stencil.Ref[1] = ref;
- ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
- if (ctx->Driver.StencilFuncSeparate) {
- ctx->Driver.StencilFuncSeparate(ctx, GL_FRONT,
- frontfunc, ref, mask);
- ctx->Driver.StencilFuncSeparate(ctx, GL_BACK,
- backfunc, ref, mask);
- }
-}
-
-
-/**
- * Set the function and reference value for stencil testing.
- *
- * \param func test function.
- * \param ref reference value.
- * \param mask bitmask.
- *
- * \sa glStencilFunc().
- *
- * Verifies the parameters and updates the respective values in
- * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
- * driver via the dd_function_table::StencilFunc callback.
- */
-void GLAPIENTRY
-_mesa_StencilFunc( GLenum func, GLint ref, GLuint mask )
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
- const GLint face = ctx->Stencil.ActiveFace;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilFunc()\n");
-
- if (!validate_stencil_func(ctx, func)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFunc(func)");
- return;
- }
-
- ref = CLAMP( ref, 0, stencilMax );
-
- if (face != 0) {
- if (ctx->Stencil.Function[face] == func &&
- ctx->Stencil.ValueMask[face] == mask &&
- ctx->Stencil.Ref[face] == ref)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.Function[face] = func;
- ctx->Stencil.Ref[face] = ref;
- ctx->Stencil.ValueMask[face] = mask;
-
- /* Only propagate the change to the driver if EXT_stencil_two_side
- * is enabled.
- */
- if (ctx->Driver.StencilFuncSeparate && ctx->Stencil.TestTwoSide) {
- ctx->Driver.StencilFuncSeparate(ctx, GL_BACK, func, ref, mask);
- }
- }
- else {
- /* set both front and back state */
- if (ctx->Stencil.Function[0] == func &&
- ctx->Stencil.Function[1] == func &&
- ctx->Stencil.ValueMask[0] == mask &&
- ctx->Stencil.ValueMask[1] == mask &&
- ctx->Stencil.Ref[0] == ref &&
- ctx->Stencil.Ref[1] == ref)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.Function[0] = ctx->Stencil.Function[1] = func;
- ctx->Stencil.Ref[0] = ctx->Stencil.Ref[1] = ref;
- ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
- if (ctx->Driver.StencilFuncSeparate) {
- ctx->Driver.StencilFuncSeparate(ctx,
- ((ctx->Stencil.TestTwoSide)
- ? GL_FRONT : GL_FRONT_AND_BACK),
- func, ref, mask);
- }
- }
-}
-
-
-/**
- * Set the stencil writing mask.
- *
- * \param mask bit-mask to enable/disable writing of individual bits in the
- * stencil planes.
- *
- * \sa glStencilMask().
- *
- * Updates gl_stencil_attrib::WriteMask. On change flushes the vertices and
- * notifies the driver via the dd_function_table::StencilMask callback.
- */
-void GLAPIENTRY
-_mesa_StencilMask( GLuint mask )
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLint face = ctx->Stencil.ActiveFace;
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilMask()\n");
-
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (face != 0) {
- /* Only modify the EXT_stencil_two_side back-face state.
- */
- if (ctx->Stencil.WriteMask[face] == mask)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.WriteMask[face] = mask;
-
- /* Only propagate the change to the driver if EXT_stencil_two_side
- * is enabled.
- */
- if (ctx->Driver.StencilMaskSeparate && ctx->Stencil.TestTwoSide) {
- ctx->Driver.StencilMaskSeparate(ctx, GL_BACK, mask);
- }
- }
- else {
- /* set both front and back state */
- if (ctx->Stencil.WriteMask[0] == mask &&
- ctx->Stencil.WriteMask[1] == mask)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.WriteMask[0] = ctx->Stencil.WriteMask[1] = mask;
- if (ctx->Driver.StencilMaskSeparate) {
- ctx->Driver.StencilMaskSeparate(ctx,
- ((ctx->Stencil.TestTwoSide)
- ? GL_FRONT : GL_FRONT_AND_BACK),
- mask);
- }
- }
-}
-
-
-/**
- * Set the stencil test actions.
- *
- * \param fail action to take when stencil test fails.
- * \param zfail action to take when stencil test passes, but depth test fails.
- * \param zpass action to take when stencil test passes and the depth test
- * passes (or depth testing is not enabled).
- *
- * \sa glStencilOp().
- *
- * Verifies the parameters and updates the respective fields in
- * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
- * driver via the dd_function_table::StencilOp callback.
- */
-void GLAPIENTRY
-_mesa_StencilOp(GLenum fail, GLenum zfail, GLenum zpass)
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLint face = ctx->Stencil.ActiveFace;
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilOp()\n");
-
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (!validate_stencil_op(ctx, fail)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(sfail)");
- return;
- }
- if (!validate_stencil_op(ctx, zfail)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zfail)");
- return;
- }
- if (!validate_stencil_op(ctx, zpass)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zpass)");
- return;
- }
-
- if (face != 0) {
- /* only set active face state */
- if (ctx->Stencil.ZFailFunc[face] == zfail &&
- ctx->Stencil.ZPassFunc[face] == zpass &&
- ctx->Stencil.FailFunc[face] == fail)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.ZFailFunc[face] = zfail;
- ctx->Stencil.ZPassFunc[face] = zpass;
- ctx->Stencil.FailFunc[face] = fail;
-
- /* Only propagate the change to the driver if EXT_stencil_two_side
- * is enabled.
- */
- if (ctx->Driver.StencilOpSeparate && ctx->Stencil.TestTwoSide) {
- ctx->Driver.StencilOpSeparate(ctx, GL_BACK, fail, zfail, zpass);
- }
- }
- else {
- /* set both front and back state */
- if (ctx->Stencil.ZFailFunc[0] == zfail &&
- ctx->Stencil.ZFailFunc[1] == zfail &&
- ctx->Stencil.ZPassFunc[0] == zpass &&
- ctx->Stencil.ZPassFunc[1] == zpass &&
- ctx->Stencil.FailFunc[0] == fail &&
- ctx->Stencil.FailFunc[1] == fail)
- return;
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.ZFailFunc[0] = ctx->Stencil.ZFailFunc[1] = zfail;
- ctx->Stencil.ZPassFunc[0] = ctx->Stencil.ZPassFunc[1] = zpass;
- ctx->Stencil.FailFunc[0] = ctx->Stencil.FailFunc[1] = fail;
- if (ctx->Driver.StencilOpSeparate) {
- ctx->Driver.StencilOpSeparate(ctx,
- ((ctx->Stencil.TestTwoSide)
- ? GL_FRONT : GL_FRONT_AND_BACK),
- fail, zfail, zpass);
- }
- }
-}
-
-
-
-#if _HAVE_FULL_GL
-/* GL_EXT_stencil_two_side */
-void GLAPIENTRY
-_mesa_ActiveStencilFaceEXT(GLenum face)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glActiveStencilFaceEXT()\n");
-
- if (!ctx->Extensions.EXT_stencil_two_side) {
- _mesa_error(ctx, GL_INVALID_OPERATION, "glActiveStencilFaceEXT");
- return;
- }
-
- if (face == GL_FRONT || face == GL_BACK) {
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.ActiveFace = (face == GL_FRONT) ? 0 : 2;
- }
- else {
- _mesa_error(ctx, GL_INVALID_ENUM, "glActiveStencilFaceEXT(face)");
- }
-}
-#endif
-
-
-
-/**
- * OpenGL 2.0 function.
- * \todo Make StencilOp() call this function. And eventually remove the
- * ctx->Driver.StencilOp function and use ctx->Driver.StencilOpSeparate
- * instead.
- */
-void GLAPIENTRY
-_mesa_StencilOpSeparate(GLenum face, GLenum sfail, GLenum zfail, GLenum zpass)
-{
- GLboolean set = GL_FALSE;
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilOpSeparate()\n");
-
- if (!validate_stencil_op(ctx, sfail)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(sfail)");
- return;
- }
- if (!validate_stencil_op(ctx, zfail)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zfail)");
- return;
- }
- if (!validate_stencil_op(ctx, zpass)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zpass)");
- return;
- }
- if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(face)");
- return;
- }
-
- if (face != GL_BACK) {
- /* set front */
- if (ctx->Stencil.ZFailFunc[0] != zfail ||
- ctx->Stencil.ZPassFunc[0] != zpass ||
- ctx->Stencil.FailFunc[0] != sfail){
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.ZFailFunc[0] = zfail;
- ctx->Stencil.ZPassFunc[0] = zpass;
- ctx->Stencil.FailFunc[0] = sfail;
- set = GL_TRUE;
- }
- }
- if (face != GL_FRONT) {
- /* set back */
- if (ctx->Stencil.ZFailFunc[1] != zfail ||
- ctx->Stencil.ZPassFunc[1] != zpass ||
- ctx->Stencil.FailFunc[1] != sfail) {
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
- ctx->Stencil.ZFailFunc[1] = zfail;
- ctx->Stencil.ZPassFunc[1] = zpass;
- ctx->Stencil.FailFunc[1] = sfail;
- set = GL_TRUE;
- }
- }
- if (set && ctx->Driver.StencilOpSeparate) {
- ctx->Driver.StencilOpSeparate(ctx, face, sfail, zfail, zpass);
- }
-}
-
-
-/* OpenGL 2.0 */
-void GLAPIENTRY
-_mesa_StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilFuncSeparate()\n");
-
- if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(face)");
- return;
- }
- if (!validate_stencil_func(ctx, func)) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(func)");
- return;
- }
-
- ref = CLAMP(ref, 0, stencilMax);
-
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
-
- if (face != GL_BACK) {
- /* set front */
- ctx->Stencil.Function[0] = func;
- ctx->Stencil.Ref[0] = ref;
- ctx->Stencil.ValueMask[0] = mask;
- }
- if (face != GL_FRONT) {
- /* set back */
- ctx->Stencil.Function[1] = func;
- ctx->Stencil.Ref[1] = ref;
- ctx->Stencil.ValueMask[1] = mask;
- }
- if (ctx->Driver.StencilFuncSeparate) {
- ctx->Driver.StencilFuncSeparate(ctx, face, func, ref, mask);
- }
-}
-
-
-/* OpenGL 2.0 */
-void GLAPIENTRY
-_mesa_StencilMaskSeparate(GLenum face, GLuint mask)
-{
- GET_CURRENT_CONTEXT(ctx);
- ASSERT_OUTSIDE_BEGIN_END(ctx);
-
- if (MESA_VERBOSE & VERBOSE_API)
- _mesa_debug(ctx, "glStencilMaskSeparate()\n");
-
- if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
- _mesa_error(ctx, GL_INVALID_ENUM, "glStencilaMaskSeparate(face)");
- return;
- }
-
- FLUSH_VERTICES(ctx, _NEW_STENCIL);
-
- if (face != GL_BACK) {
- ctx->Stencil.WriteMask[0] = mask;
- }
- if (face != GL_FRONT) {
- ctx->Stencil.WriteMask[1] = mask;
- }
- if (ctx->Driver.StencilMaskSeparate) {
- ctx->Driver.StencilMaskSeparate(ctx, face, mask);
- }
-}
-
-
-/**
- * Update derived stencil state.
- */
-void
-_mesa_update_stencil(struct gl_context *ctx)
-{
- const GLint face = ctx->Stencil._BackFace;
-
- ctx->Stencil._Enabled = (ctx->Stencil.Enabled &&
- ctx->DrawBuffer->Visual.stencilBits > 0);
-
- ctx->Stencil._TestTwoSide =
- ctx->Stencil._Enabled &&
- (ctx->Stencil.Function[0] != ctx->Stencil.Function[face] ||
- ctx->Stencil.FailFunc[0] != ctx->Stencil.FailFunc[face] ||
- ctx->Stencil.ZPassFunc[0] != ctx->Stencil.ZPassFunc[face] ||
- ctx->Stencil.ZFailFunc[0] != ctx->Stencil.ZFailFunc[face] ||
- ctx->Stencil.Ref[0] != ctx->Stencil.Ref[face] ||
- ctx->Stencil.ValueMask[0] != ctx->Stencil.ValueMask[face] ||
- ctx->Stencil.WriteMask[0] != ctx->Stencil.WriteMask[face]);
-}
-
-
-/**
- * Initialize the context stipple state.
- *
- * \param ctx GL context.
- *
- * Initializes __struct gl_contextRec::Stencil attribute group.
- */
-void
-_mesa_init_stencil(struct gl_context *ctx)
-{
- ctx->Stencil.Enabled = GL_FALSE;
- ctx->Stencil.TestTwoSide = GL_FALSE;
- ctx->Stencil.ActiveFace = 0; /* 0 = GL_FRONT, 2 = GL_BACK */
- ctx->Stencil.Function[0] = GL_ALWAYS;
- ctx->Stencil.Function[1] = GL_ALWAYS;
- ctx->Stencil.Function[2] = GL_ALWAYS;
- ctx->Stencil.FailFunc[0] = GL_KEEP;
- ctx->Stencil.FailFunc[1] = GL_KEEP;
- ctx->Stencil.FailFunc[2] = GL_KEEP;
- ctx->Stencil.ZPassFunc[0] = GL_KEEP;
- ctx->Stencil.ZPassFunc[1] = GL_KEEP;
- ctx->Stencil.ZPassFunc[2] = GL_KEEP;
- ctx->Stencil.ZFailFunc[0] = GL_KEEP;
- ctx->Stencil.ZFailFunc[1] = GL_KEEP;
- ctx->Stencil.ZFailFunc[2] = GL_KEEP;
- ctx->Stencil.Ref[0] = 0;
- ctx->Stencil.Ref[1] = 0;
- ctx->Stencil.Ref[2] = 0;
- ctx->Stencil.ValueMask[0] = ~0U;
- ctx->Stencil.ValueMask[1] = ~0U;
- ctx->Stencil.ValueMask[2] = ~0U;
- ctx->Stencil.WriteMask[0] = ~0U;
- ctx->Stencil.WriteMask[1] = ~0U;
- ctx->Stencil.WriteMask[2] = ~0U;
- ctx->Stencil.Clear = 0;
- ctx->Stencil._BackFace = 1;
-}
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.1
+ *
+ * Copyright (C) 1999-2007 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 stencil.c
+ * Stencil operations.
+ *
+ * Note: There's some conflict between GL_EXT_stencil_two_side and
+ * OpenGL 2.0's two-sided stencil feature.
+ *
+ * With GL_EXT_stencil_two_side, calling glStencilOp/Func/Mask() only the
+ * front OR back face state (as set by glActiveStencilFaceEXT) is set.
+ *
+ * But with OpenGL 2.0, calling glStencilOp/Func/Mask() sets BOTH the
+ * front AND back state.
+ *
+ * Also, note that GL_ATI_separate_stencil is different as well:
+ * glStencilFuncSeparateATI(GLenum frontfunc, GLenum backfunc, ...) vs.
+ * glStencilFuncSeparate(GLenum face, GLenum func, ...).
+ *
+ * This problem is solved by keeping three sets of stencil state:
+ * state[0] = GL_FRONT state.
+ * state[1] = OpenGL 2.0 / GL_ATI_separate_stencil GL_BACK state.
+ * state[2] = GL_EXT_stencil_two_side GL_BACK state.
+ */
+
+
+#include "glheader.h"
+#include "imports.h"
+#include "context.h"
+#include "macros.h"
+#include "stencil.h"
+#include "mtypes.h"
+
+
+static GLboolean
+validate_stencil_op(struct gl_context *ctx, GLenum op)
+{
+ switch (op) {
+ case GL_KEEP:
+ case GL_ZERO:
+ case GL_REPLACE:
+ case GL_INCR:
+ case GL_DECR:
+ case GL_INVERT:
+ return GL_TRUE;
+ case GL_INCR_WRAP_EXT:
+ case GL_DECR_WRAP_EXT:
+ if (ctx->Extensions.EXT_stencil_wrap) {
+ return GL_TRUE;
+ }
+ /* FALL-THROUGH */
+ default:
+ return GL_FALSE;
+ }
+}
+
+
+static GLboolean
+validate_stencil_func(struct gl_context *ctx, GLenum func)
+{
+ switch (func) {
+ case GL_NEVER:
+ case GL_LESS:
+ case GL_LEQUAL:
+ case GL_GREATER:
+ case GL_GEQUAL:
+ case GL_EQUAL:
+ case GL_NOTEQUAL:
+ case GL_ALWAYS:
+ return GL_TRUE;
+ default:
+ return GL_FALSE;
+ }
+}
+
+
+/**
+ * Set the clear value for the stencil buffer.
+ *
+ * \param s clear value.
+ *
+ * \sa glClearStencil().
+ *
+ * Updates gl_stencil_attrib::Clear. On change
+ * flushes the vertices and notifies the driver via
+ * the dd_function_table::ClearStencil callback.
+ */
+void GLAPIENTRY
+_mesa_ClearStencil( GLint s )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (ctx->Stencil.Clear == (GLuint) s)
+ return;
+
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.Clear = (GLuint) s;
+
+ if (ctx->Driver.ClearStencil) {
+ ctx->Driver.ClearStencil( ctx, s );
+ }
+}
+
+
+/**
+ * Set the function and reference value for stencil testing.
+ *
+ * \param frontfunc front test function.
+ * \param backfunc back test function.
+ * \param ref front and back reference value.
+ * \param mask front and back bitmask.
+ *
+ * \sa glStencilFunc().
+ *
+ * Verifies the parameters and updates the respective values in
+ * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
+ * driver via the dd_function_table::StencilFunc callback.
+ */
+void GLAPIENTRY
+_mesa_StencilFuncSeparateATI( GLenum frontfunc, GLenum backfunc, GLint ref, GLuint mask )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilFuncSeparateATI()\n");
+
+ if (!validate_stencil_func(ctx, frontfunc)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glStencilFuncSeparateATI(frontfunc)");
+ return;
+ }
+ if (!validate_stencil_func(ctx, backfunc)) {
+ _mesa_error(ctx, GL_INVALID_ENUM,
+ "glStencilFuncSeparateATI(backfunc)");
+ return;
+ }
+
+ ref = CLAMP( ref, 0, stencilMax );
+
+ /* set both front and back state */
+ if (ctx->Stencil.Function[0] == frontfunc &&
+ ctx->Stencil.Function[1] == backfunc &&
+ ctx->Stencil.ValueMask[0] == mask &&
+ ctx->Stencil.ValueMask[1] == mask &&
+ ctx->Stencil.Ref[0] == ref &&
+ ctx->Stencil.Ref[1] == ref)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.Function[0] = frontfunc;
+ ctx->Stencil.Function[1] = backfunc;
+ ctx->Stencil.Ref[0] = ctx->Stencil.Ref[1] = ref;
+ ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
+ if (ctx->Driver.StencilFuncSeparate) {
+ ctx->Driver.StencilFuncSeparate(ctx, GL_FRONT,
+ frontfunc, ref, mask);
+ ctx->Driver.StencilFuncSeparate(ctx, GL_BACK,
+ backfunc, ref, mask);
+ }
+}
+
+
+/**
+ * Set the function and reference value for stencil testing.
+ *
+ * \param func test function.
+ * \param ref reference value.
+ * \param mask bitmask.
+ *
+ * \sa glStencilFunc().
+ *
+ * Verifies the parameters and updates the respective values in
+ * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
+ * driver via the dd_function_table::StencilFunc callback.
+ */
+void GLAPIENTRY
+_mesa_StencilFunc( GLenum func, GLint ref, GLuint mask )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
+ const GLint face = ctx->Stencil.ActiveFace;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilFunc()\n");
+
+ if (!validate_stencil_func(ctx, func)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFunc(func)");
+ return;
+ }
+
+ ref = CLAMP( ref, 0, stencilMax );
+
+ if (face != 0) {
+ if (ctx->Stencil.Function[face] == func &&
+ ctx->Stencil.ValueMask[face] == mask &&
+ ctx->Stencil.Ref[face] == ref)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.Function[face] = func;
+ ctx->Stencil.Ref[face] = ref;
+ ctx->Stencil.ValueMask[face] = mask;
+
+ /* Only propagate the change to the driver if EXT_stencil_two_side
+ * is enabled.
+ */
+ if (ctx->Driver.StencilFuncSeparate && ctx->Stencil.TestTwoSide) {
+ ctx->Driver.StencilFuncSeparate(ctx, GL_BACK, func, ref, mask);
+ }
+ }
+ else {
+ /* set both front and back state */
+ if (ctx->Stencil.Function[0] == func &&
+ ctx->Stencil.Function[1] == func &&
+ ctx->Stencil.ValueMask[0] == mask &&
+ ctx->Stencil.ValueMask[1] == mask &&
+ ctx->Stencil.Ref[0] == ref &&
+ ctx->Stencil.Ref[1] == ref)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.Function[0] = ctx->Stencil.Function[1] = func;
+ ctx->Stencil.Ref[0] = ctx->Stencil.Ref[1] = ref;
+ ctx->Stencil.ValueMask[0] = ctx->Stencil.ValueMask[1] = mask;
+ if (ctx->Driver.StencilFuncSeparate) {
+ ctx->Driver.StencilFuncSeparate(ctx,
+ ((ctx->Stencil.TestTwoSide)
+ ? GL_FRONT : GL_FRONT_AND_BACK),
+ func, ref, mask);
+ }
+ }
+}
+
+
+/**
+ * Set the stencil writing mask.
+ *
+ * \param mask bit-mask to enable/disable writing of individual bits in the
+ * stencil planes.
+ *
+ * \sa glStencilMask().
+ *
+ * Updates gl_stencil_attrib::WriteMask. On change flushes the vertices and
+ * notifies the driver via the dd_function_table::StencilMask callback.
+ */
+void GLAPIENTRY
+_mesa_StencilMask( GLuint mask )
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLint face = ctx->Stencil.ActiveFace;
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilMask()\n");
+
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (face != 0) {
+ /* Only modify the EXT_stencil_two_side back-face state.
+ */
+ if (ctx->Stencil.WriteMask[face] == mask)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.WriteMask[face] = mask;
+
+ /* Only propagate the change to the driver if EXT_stencil_two_side
+ * is enabled.
+ */
+ if (ctx->Driver.StencilMaskSeparate && ctx->Stencil.TestTwoSide) {
+ ctx->Driver.StencilMaskSeparate(ctx, GL_BACK, mask);
+ }
+ }
+ else {
+ /* set both front and back state */
+ if (ctx->Stencil.WriteMask[0] == mask &&
+ ctx->Stencil.WriteMask[1] == mask)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.WriteMask[0] = ctx->Stencil.WriteMask[1] = mask;
+ if (ctx->Driver.StencilMaskSeparate) {
+ ctx->Driver.StencilMaskSeparate(ctx,
+ ((ctx->Stencil.TestTwoSide)
+ ? GL_FRONT : GL_FRONT_AND_BACK),
+ mask);
+ }
+ }
+}
+
+
+/**
+ * Set the stencil test actions.
+ *
+ * \param fail action to take when stencil test fails.
+ * \param zfail action to take when stencil test passes, but depth test fails.
+ * \param zpass action to take when stencil test passes and the depth test
+ * passes (or depth testing is not enabled).
+ *
+ * \sa glStencilOp().
+ *
+ * Verifies the parameters and updates the respective fields in
+ * __struct gl_contextRec::Stencil. On change flushes the vertices and notifies the
+ * driver via the dd_function_table::StencilOp callback.
+ */
+void GLAPIENTRY
+_mesa_StencilOp(GLenum fail, GLenum zfail, GLenum zpass)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLint face = ctx->Stencil.ActiveFace;
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilOp()\n");
+
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (!validate_stencil_op(ctx, fail)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(sfail)");
+ return;
+ }
+ if (!validate_stencil_op(ctx, zfail)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zfail)");
+ return;
+ }
+ if (!validate_stencil_op(ctx, zpass)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOp(zpass)");
+ return;
+ }
+
+ if (face != 0) {
+ /* only set active face state */
+ if (ctx->Stencil.ZFailFunc[face] == zfail &&
+ ctx->Stencil.ZPassFunc[face] == zpass &&
+ ctx->Stencil.FailFunc[face] == fail)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.ZFailFunc[face] = zfail;
+ ctx->Stencil.ZPassFunc[face] = zpass;
+ ctx->Stencil.FailFunc[face] = fail;
+
+ /* Only propagate the change to the driver if EXT_stencil_two_side
+ * is enabled.
+ */
+ if (ctx->Driver.StencilOpSeparate && ctx->Stencil.TestTwoSide) {
+ ctx->Driver.StencilOpSeparate(ctx, GL_BACK, fail, zfail, zpass);
+ }
+ }
+ else {
+ /* set both front and back state */
+ if (ctx->Stencil.ZFailFunc[0] == zfail &&
+ ctx->Stencil.ZFailFunc[1] == zfail &&
+ ctx->Stencil.ZPassFunc[0] == zpass &&
+ ctx->Stencil.ZPassFunc[1] == zpass &&
+ ctx->Stencil.FailFunc[0] == fail &&
+ ctx->Stencil.FailFunc[1] == fail)
+ return;
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.ZFailFunc[0] = ctx->Stencil.ZFailFunc[1] = zfail;
+ ctx->Stencil.ZPassFunc[0] = ctx->Stencil.ZPassFunc[1] = zpass;
+ ctx->Stencil.FailFunc[0] = ctx->Stencil.FailFunc[1] = fail;
+ if (ctx->Driver.StencilOpSeparate) {
+ ctx->Driver.StencilOpSeparate(ctx,
+ ((ctx->Stencil.TestTwoSide)
+ ? GL_FRONT : GL_FRONT_AND_BACK),
+ fail, zfail, zpass);
+ }
+ }
+}
+
+
+
+#if _HAVE_FULL_GL
+/* GL_EXT_stencil_two_side */
+void GLAPIENTRY
+_mesa_ActiveStencilFaceEXT(GLenum face)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glActiveStencilFaceEXT()\n");
+
+ if (!ctx->Extensions.EXT_stencil_two_side) {
+ _mesa_error(ctx, GL_INVALID_OPERATION, "glActiveStencilFaceEXT");
+ return;
+ }
+
+ if (face == GL_FRONT || face == GL_BACK) {
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.ActiveFace = (face == GL_FRONT) ? 0 : 2;
+ }
+ else {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glActiveStencilFaceEXT(face)");
+ }
+}
+#endif
+
+
+
+/**
+ * OpenGL 2.0 function.
+ * \todo Make StencilOp() call this function. And eventually remove the
+ * ctx->Driver.StencilOp function and use ctx->Driver.StencilOpSeparate
+ * instead.
+ */
+void GLAPIENTRY
+_mesa_StencilOpSeparate(GLenum face, GLenum sfail, GLenum zfail, GLenum zpass)
+{
+ GLboolean set = GL_FALSE;
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilOpSeparate()\n");
+
+ if (!validate_stencil_op(ctx, sfail)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(sfail)");
+ return;
+ }
+ if (!validate_stencil_op(ctx, zfail)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zfail)");
+ return;
+ }
+ if (!validate_stencil_op(ctx, zpass)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(zpass)");
+ return;
+ }
+ if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilOpSeparate(face)");
+ return;
+ }
+
+ if (face != GL_BACK) {
+ /* set front */
+ if (ctx->Stencil.ZFailFunc[0] != zfail ||
+ ctx->Stencil.ZPassFunc[0] != zpass ||
+ ctx->Stencil.FailFunc[0] != sfail){
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.ZFailFunc[0] = zfail;
+ ctx->Stencil.ZPassFunc[0] = zpass;
+ ctx->Stencil.FailFunc[0] = sfail;
+ set = GL_TRUE;
+ }
+ }
+ if (face != GL_FRONT) {
+ /* set back */
+ if (ctx->Stencil.ZFailFunc[1] != zfail ||
+ ctx->Stencil.ZPassFunc[1] != zpass ||
+ ctx->Stencil.FailFunc[1] != sfail) {
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+ ctx->Stencil.ZFailFunc[1] = zfail;
+ ctx->Stencil.ZPassFunc[1] = zpass;
+ ctx->Stencil.FailFunc[1] = sfail;
+ set = GL_TRUE;
+ }
+ }
+ if (set && ctx->Driver.StencilOpSeparate) {
+ ctx->Driver.StencilOpSeparate(ctx, face, sfail, zfail, zpass);
+ }
+}
+
+
+/* OpenGL 2.0 */
+void GLAPIENTRY
+_mesa_StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ const GLint stencilMax = (1 << ctx->DrawBuffer->Visual.stencilBits) - 1;
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilFuncSeparate()\n");
+
+ if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(face)");
+ return;
+ }
+ if (!validate_stencil_func(ctx, func)) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilFuncSeparate(func)");
+ return;
+ }
+
+ ref = CLAMP(ref, 0, stencilMax);
+
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+
+ if (face != GL_BACK) {
+ /* set front */
+ ctx->Stencil.Function[0] = func;
+ ctx->Stencil.Ref[0] = ref;
+ ctx->Stencil.ValueMask[0] = mask;
+ }
+ if (face != GL_FRONT) {
+ /* set back */
+ ctx->Stencil.Function[1] = func;
+ ctx->Stencil.Ref[1] = ref;
+ ctx->Stencil.ValueMask[1] = mask;
+ }
+ if (ctx->Driver.StencilFuncSeparate) {
+ ctx->Driver.StencilFuncSeparate(ctx, face, func, ref, mask);
+ }
+}
+
+
+/* OpenGL 2.0 */
+void GLAPIENTRY
+_mesa_StencilMaskSeparate(GLenum face, GLuint mask)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ ASSERT_OUTSIDE_BEGIN_END(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_API)
+ _mesa_debug(ctx, "glStencilMaskSeparate()\n");
+
+ if (face != GL_FRONT && face != GL_BACK && face != GL_FRONT_AND_BACK) {
+ _mesa_error(ctx, GL_INVALID_ENUM, "glStencilaMaskSeparate(face)");
+ return;
+ }
+
+ FLUSH_VERTICES(ctx, _NEW_STENCIL);
+
+ if (face != GL_BACK) {
+ ctx->Stencil.WriteMask[0] = mask;
+ }
+ if (face != GL_FRONT) {
+ ctx->Stencil.WriteMask[1] = mask;
+ }
+ if (ctx->Driver.StencilMaskSeparate) {
+ ctx->Driver.StencilMaskSeparate(ctx, face, mask);
+ }
+}
+
+
+/**
+ * Update derived stencil state.
+ */
+void
+_mesa_update_stencil(struct gl_context *ctx)
+{
+ const GLint face = ctx->Stencil._BackFace;
+
+ ctx->Stencil._Enabled = (ctx->Stencil.Enabled &&
+ ctx->DrawBuffer->Visual.stencilBits > 0);
+
+ ctx->Stencil._TestTwoSide =
+ ctx->Stencil._Enabled &&
+ (ctx->Stencil.Function[0] != ctx->Stencil.Function[face] ||
+ ctx->Stencil.FailFunc[0] != ctx->Stencil.FailFunc[face] ||
+ ctx->Stencil.ZPassFunc[0] != ctx->Stencil.ZPassFunc[face] ||
+ ctx->Stencil.ZFailFunc[0] != ctx->Stencil.ZFailFunc[face] ||
+ ctx->Stencil.Ref[0] != ctx->Stencil.Ref[face] ||
+ ctx->Stencil.ValueMask[0] != ctx->Stencil.ValueMask[face] ||
+ ctx->Stencil.WriteMask[0] != ctx->Stencil.WriteMask[face]);
+}
+
+
+/**
+ * Initialize the context stipple state.
+ *
+ * \param ctx GL context.
+ *
+ * Initializes __struct gl_contextRec::Stencil attribute group.
+ */
+void
+_mesa_init_stencil(struct gl_context *ctx)
+{
+ ctx->Stencil.Enabled = GL_FALSE;
+ ctx->Stencil.TestTwoSide = GL_FALSE;
+ ctx->Stencil.ActiveFace = 0; /* 0 = GL_FRONT, 2 = GL_BACK */
+ ctx->Stencil.Function[0] = GL_ALWAYS;
+ ctx->Stencil.Function[1] = GL_ALWAYS;
+ ctx->Stencil.Function[2] = GL_ALWAYS;
+ ctx->Stencil.FailFunc[0] = GL_KEEP;
+ ctx->Stencil.FailFunc[1] = GL_KEEP;
+ ctx->Stencil.FailFunc[2] = GL_KEEP;
+ ctx->Stencil.ZPassFunc[0] = GL_KEEP;
+ ctx->Stencil.ZPassFunc[1] = GL_KEEP;
+ ctx->Stencil.ZPassFunc[2] = GL_KEEP;
+ ctx->Stencil.ZFailFunc[0] = GL_KEEP;
+ ctx->Stencil.ZFailFunc[1] = GL_KEEP;
+ ctx->Stencil.ZFailFunc[2] = GL_KEEP;
+ ctx->Stencil.Ref[0] = 0;
+ ctx->Stencil.Ref[1] = 0;
+ ctx->Stencil.Ref[2] = 0;
+ ctx->Stencil.ValueMask[0] = ~0U;
+ ctx->Stencil.ValueMask[1] = ~0U;
+ ctx->Stencil.ValueMask[2] = ~0U;
+ ctx->Stencil.WriteMask[0] = ~0U;
+ ctx->Stencil.WriteMask[1] = ~0U;
+ ctx->Stencil.WriteMask[2] = ~0U;
+ ctx->Stencil.Clear = 0;
+ ctx->Stencil._BackFace = 1;
+}
diff --git a/mesalib/src/mesa/main/syncobj.c b/mesalib/src/mesa/main/syncobj.c
index 676038430..25307a17c 100644
--- a/mesalib/src/mesa/main/syncobj.c
+++ b/mesalib/src/mesa/main/syncobj.c
@@ -125,7 +125,7 @@ _mesa_wait_sync(struct gl_context *ctx, struct gl_sync_object *syncObj,
}
-void
+void GLAPIENTRY
_mesa_init_sync_object_functions(struct dd_function_table *driver)
{
driver->NewSyncObject = _mesa_new_sync_object;
@@ -140,7 +140,7 @@ _mesa_init_sync_object_functions(struct dd_function_table *driver)
}
-void
+void GLAPIENTRY
_mesa_init_sync_dispatch(struct _glapi_table *disp)
{
SET_IsSync(disp, _mesa_IsSync);
@@ -156,7 +156,7 @@ _mesa_init_sync_dispatch(struct _glapi_table *disp)
/**
* Allocate/init the context state related to sync objects.
*/
-void
+void GLAPIENTRY
_mesa_init_sync(struct gl_context *ctx)
{
(void) ctx;
@@ -166,7 +166,7 @@ _mesa_init_sync(struct gl_context *ctx)
/**
* Free the context state related to sync objects.
*/
-void
+void GLAPIENTRY
_mesa_free_sync_data(struct gl_context *ctx)
{
(void) ctx;
@@ -182,7 +182,7 @@ _mesa_validate_sync(struct gl_sync_object *syncObj)
}
-void
+void GLAPIENTRY
_mesa_ref_sync_object(struct gl_context *ctx, struct gl_sync_object *syncObj)
{
_glthread_LOCK_MUTEX(ctx->Shared->Mutex);
@@ -191,7 +191,7 @@ _mesa_ref_sync_object(struct gl_context *ctx, struct gl_sync_object *syncObj)
}
-void
+void GLAPIENTRY
_mesa_unref_sync_object(struct gl_context *ctx, struct gl_sync_object *syncObj)
{
_glthread_LOCK_MUTEX(ctx->Shared->Mutex);
diff --git a/mesalib/src/mesa/main/syncobj.h b/mesalib/src/mesa/main/syncobj.h
index ac1384f61..e83ac8b0e 100644
--- a/mesalib/src/mesa/main/syncobj.h
+++ b/mesalib/src/mesa/main/syncobj.h
@@ -41,22 +41,22 @@ struct gl_sync_object;
#if FEATURE_ARB_sync
-extern void
+extern void GLAPIENTRY
_mesa_init_sync_object_functions(struct dd_function_table *driver);
-extern void
+extern void GLAPIENTRY
_mesa_init_sync_dispatch(struct _glapi_table *disp);
-extern void
+extern void GLAPIENTRY
_mesa_init_sync(struct gl_context *);
-extern void
+extern void GLAPIENTRY
_mesa_free_sync_data(struct gl_context *);
-extern void
+extern void GLAPIENTRY
_mesa_ref_sync_object(struct gl_context *ctx, struct gl_sync_object *syncObj);
-extern void
+extern void GLAPIENTRY
_mesa_unref_sync_object(struct gl_context *ctx, struct gl_sync_object *syncObj);
extern GLboolean GLAPIENTRY
diff --git a/mesalib/src/mesa/main/texcompress_s3tc.c b/mesalib/src/mesa/main/texcompress_s3tc.c
index 90be6c0a8..479806eca 100644
--- a/mesalib/src/mesa/main/texcompress_s3tc.c
+++ b/mesalib/src/mesa/main/texcompress_s3tc.c
@@ -50,7 +50,11 @@
#if defined(_WIN32) || defined(WIN32)
+#ifdef _DEBUG
+#define DXTN_LIBNAME "dxtn_dbg.dll"
+#else
#define DXTN_LIBNAME "dxtn.dll"
+#endif
#define RTLD_LAZY 0
#define RTLD_GLOBAL 0
#elif defined(__DJGPP__)
diff --git a/mesalib/src/mesa/program/sampler.cpp b/mesalib/src/mesa/program/sampler.cpp
index 1457d1199..b219d7016 100644
--- a/mesalib/src/mesa/program/sampler.cpp
+++ b/mesalib/src/mesa/program/sampler.cpp
@@ -1,137 +1,137 @@
-/*
- * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
- * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
- * Copyright © 2010 Intel Corporation
- *
- * 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 (including the next
- * paragraph) 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
- * THE AUTHORS OR COPYRIGHT HOLDERS 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.
- */
-
-#include "ir.h"
-#include "glsl_types.h"
-#include "ir_visitor.h"
-
-extern "C" {
-#include "main/compiler.h"
-#include "main/mtypes.h"
-#include "program/prog_parameter.h"
-}
-
-static void fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
-
-static void fail_link(struct gl_shader_program *prog, const char *fmt, ...)
-{
- va_list args;
- va_start(args, fmt);
- ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
- va_end(args);
-
- prog->LinkStatus = GL_FALSE;
-}
-
-class get_sampler_name : public ir_hierarchical_visitor
-{
-public:
- get_sampler_name(ir_dereference *last,
- struct gl_shader_program *shader_program)
- {
- this->mem_ctx = ralloc_context(NULL);
- this->shader_program = shader_program;
- this->name = NULL;
- this->offset = 0;
- this->last = last;
- }
-
- ~get_sampler_name()
- {
- ralloc_free(this->mem_ctx);
- }
-
- virtual ir_visitor_status visit(ir_dereference_variable *ir)
- {
- this->name = ir->var->name;
- return visit_continue;
- }
-
- virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
- {
- this->name = ralloc_asprintf(mem_ctx, "%s.%s", name, ir->field);
- return visit_continue;
- }
-
- virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
- {
- ir_constant *index = ir->array_index->as_constant();
- int i;
-
- if (index) {
- i = index->value.i[0];
- } else {
- /* GLSL 1.10 and 1.20 allowed variable sampler array indices,
- * while GLSL 1.30 requires that the array indices be
- * constant integer expressions. We don't expect any driver
- * to actually work with a really variable array index, so
- * all that would work would be an unrolled loop counter that ends
- * up being constant above.
- */
- ralloc_strcat(&shader_program->InfoLog,
- "warning: Variable sampler array index unsupported.\n"
- "This feature of the language was removed in GLSL 1.20 "
- "and is unlikely to be supported for 1.10 in Mesa.\n");
- i = 0;
- }
- if (ir != last) {
- this->name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
- } else {
- offset = i;
- }
- return visit_continue;
- }
-
- struct gl_shader_program *shader_program;
- const char *name;
- void *mem_ctx;
- int offset;
- ir_dereference *last;
-};
-
-extern "C" {
-int
-_mesa_get_sampler_uniform_value(class ir_dereference *sampler,
- struct gl_shader_program *shader_program,
- const struct gl_program *prog)
-{
- get_sampler_name getname(sampler, shader_program);
-
- sampler->accept(&getname);
-
- GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
- getname.name);
-
- if (index < 0) {
- fail_link(shader_program,
- "failed to find sampler named %s.\n", getname.name);
- return 0;
- }
-
- index += getname.offset;
-
- return prog->Parameters->ParameterValues[index][0];
-}
-}
+/*
+ * Copyright (C) 2005-2007 Brian Paul All Rights Reserved.
+ * Copyright (C) 2008 VMware, Inc. All Rights Reserved.
+ * Copyright © 2010 Intel Corporation
+ *
+ * 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 (including the next
+ * paragraph) 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
+ * THE AUTHORS OR COPYRIGHT HOLDERS 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.
+ */
+
+#include "ir.h"
+#include "glsl_types.h"
+#include "ir_visitor.h"
+
+extern "C" {
+#include "main/compiler.h"
+#include "main/mtypes.h"
+#include "program/prog_parameter.h"
+}
+
+static void fail_link(struct gl_shader_program *prog, const char *fmt, ...) PRINTFLIKE(2, 3);
+
+static void fail_link(struct gl_shader_program *prog, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ ralloc_vasprintf_append(&prog->InfoLog, fmt, args);
+ va_end(args);
+
+ prog->LinkStatus = GL_FALSE;
+}
+
+class get_sampler_name : public ir_hierarchical_visitor
+{
+public:
+ get_sampler_name(ir_dereference *last,
+ struct gl_shader_program *shader_program)
+ {
+ this->mem_ctx = ralloc_context(NULL);
+ this->shader_program = shader_program;
+ this->name = NULL;
+ this->offset = 0;
+ this->last = last;
+ }
+
+ ~get_sampler_name()
+ {
+ ralloc_free(this->mem_ctx);
+ }
+
+ virtual ir_visitor_status visit(ir_dereference_variable *ir)
+ {
+ this->name = ir->var->name;
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit_leave(ir_dereference_record *ir)
+ {
+ this->name = ralloc_asprintf(mem_ctx, "%s.%s", name, ir->field);
+ return visit_continue;
+ }
+
+ virtual ir_visitor_status visit_leave(ir_dereference_array *ir)
+ {
+ ir_constant *index = ir->array_index->as_constant();
+ int i;
+
+ if (index) {
+ i = index->value.i[0];
+ } else {
+ /* GLSL 1.10 and 1.20 allowed variable sampler array indices,
+ * while GLSL 1.30 requires that the array indices be
+ * constant integer expressions. We don't expect any driver
+ * to actually work with a really variable array index, so
+ * all that would work would be an unrolled loop counter that ends
+ * up being constant above.
+ */
+ ralloc_strcat(&shader_program->InfoLog,
+ "warning: Variable sampler array index unsupported.\n"
+ "This feature of the language was removed in GLSL 1.20 "
+ "and is unlikely to be supported for 1.10 in Mesa.\n");
+ i = 0;
+ }
+ if (ir != last) {
+ this->name = ralloc_asprintf(mem_ctx, "%s[%d]", name, i);
+ } else {
+ offset = i;
+ }
+ return visit_continue;
+ }
+
+ struct gl_shader_program *shader_program;
+ const char *name;
+ void *mem_ctx;
+ int offset;
+ ir_dereference *last;
+};
+
+extern "C" {
+int
+_mesa_get_sampler_uniform_value(class ir_dereference *sampler,
+ struct gl_shader_program *shader_program,
+ const struct gl_program *prog)
+{
+ get_sampler_name getname(sampler, shader_program);
+
+ sampler->accept(&getname);
+
+ GLint index = _mesa_lookup_parameter_index(prog->Parameters, -1,
+ getname.name);
+
+ if (index < 0) {
+ fail_link(shader_program,
+ "failed to find sampler named %s.\n", getname.name);
+ return 0;
+ }
+
+ index += getname.offset;
+
+ return prog->Parameters->ParameterValues[index][0];
+}
+}
diff --git a/mesalib/src/mesa/state_tracker/st_atom_blend.c b/mesalib/src/mesa/state_tracker/st_atom_blend.c
index fb1c7a4ef..e3b3b9936 100644
--- a/mesalib/src/mesa/state_tracker/st_atom_blend.c
+++ b/mesalib/src/mesa/state_tracker/st_atom_blend.c
@@ -1,302 +1,302 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- * Brian Paul
- */
-
-
-#include "st_context.h"
-#include "st_atom.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "cso_cache/cso_context.h"
-
-#include "main/macros.h"
-
-/**
- * Convert GLenum blend tokens to pipe tokens.
- * Both blend factors and blend funcs are accepted.
- */
-static GLuint
-translate_blend(GLenum blend)
-{
- switch (blend) {
- /* blend functions */
- case GL_FUNC_ADD:
- return PIPE_BLEND_ADD;
- case GL_FUNC_SUBTRACT:
- return PIPE_BLEND_SUBTRACT;
- case GL_FUNC_REVERSE_SUBTRACT:
- return PIPE_BLEND_REVERSE_SUBTRACT;
- case GL_MIN:
- return PIPE_BLEND_MIN;
- case GL_MAX:
- return PIPE_BLEND_MAX;
-
- /* blend factors */
- case GL_ONE:
- return PIPE_BLENDFACTOR_ONE;
- case GL_SRC_COLOR:
- return PIPE_BLENDFACTOR_SRC_COLOR;
- case GL_SRC_ALPHA:
- return PIPE_BLENDFACTOR_SRC_ALPHA;
- case GL_DST_ALPHA:
- return PIPE_BLENDFACTOR_DST_ALPHA;
- case GL_DST_COLOR:
- return PIPE_BLENDFACTOR_DST_COLOR;
- case GL_SRC_ALPHA_SATURATE:
- return PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE;
- case GL_CONSTANT_COLOR:
- return PIPE_BLENDFACTOR_CONST_COLOR;
- case GL_CONSTANT_ALPHA:
- return PIPE_BLENDFACTOR_CONST_ALPHA;
- /*
- return PIPE_BLENDFACTOR_SRC1_COLOR;
- return PIPE_BLENDFACTOR_SRC1_ALPHA;
- */
- case GL_ZERO:
- return PIPE_BLENDFACTOR_ZERO;
- case GL_ONE_MINUS_SRC_COLOR:
- return PIPE_BLENDFACTOR_INV_SRC_COLOR;
- case GL_ONE_MINUS_SRC_ALPHA:
- return PIPE_BLENDFACTOR_INV_SRC_ALPHA;
- case GL_ONE_MINUS_DST_COLOR:
- return PIPE_BLENDFACTOR_INV_DST_COLOR;
- case GL_ONE_MINUS_DST_ALPHA:
- return PIPE_BLENDFACTOR_INV_DST_ALPHA;
- case GL_ONE_MINUS_CONSTANT_COLOR:
- return PIPE_BLENDFACTOR_INV_CONST_COLOR;
- case GL_ONE_MINUS_CONSTANT_ALPHA:
- return PIPE_BLENDFACTOR_INV_CONST_ALPHA;
- /*
- return PIPE_BLENDFACTOR_INV_SRC1_COLOR;
- return PIPE_BLENDFACTOR_INV_SRC1_ALPHA;
- */
- default:
- assert("invalid GL token in translate_blend()" == NULL);
- return 0;
- }
-}
-
-
-/**
- * Convert GLenum logicop tokens to pipe tokens.
- */
-static GLuint
-translate_logicop(GLenum logicop)
-{
- switch (logicop) {
- case GL_CLEAR:
- return PIPE_LOGICOP_CLEAR;
- case GL_NOR:
- return PIPE_LOGICOP_NOR;
- case GL_AND_INVERTED:
- return PIPE_LOGICOP_AND_INVERTED;
- case GL_COPY_INVERTED:
- return PIPE_LOGICOP_COPY_INVERTED;
- case GL_AND_REVERSE:
- return PIPE_LOGICOP_AND_REVERSE;
- case GL_INVERT:
- return PIPE_LOGICOP_INVERT;
- case GL_XOR:
- return PIPE_LOGICOP_XOR;
- case GL_NAND:
- return PIPE_LOGICOP_NAND;
- case GL_AND:
- return PIPE_LOGICOP_AND;
- case GL_EQUIV:
- return PIPE_LOGICOP_EQUIV;
- case GL_NOOP:
- return PIPE_LOGICOP_NOOP;
- case GL_OR_INVERTED:
- return PIPE_LOGICOP_OR_INVERTED;
- case GL_COPY:
- return PIPE_LOGICOP_COPY;
- case GL_OR_REVERSE:
- return PIPE_LOGICOP_OR_REVERSE;
- case GL_OR:
- return PIPE_LOGICOP_OR;
- case GL_SET:
- return PIPE_LOGICOP_SET;
- default:
- assert("invalid GL token in translate_logicop()" == NULL);
- return 0;
- }
-}
-
-/**
- * Figure out if colormasks are different per rt.
- */
-static GLboolean
-colormask_per_rt(struct gl_context *ctx)
-{
- /* a bit suboptimal have to compare lots of values */
- unsigned i;
- for (i = 1; i < ctx->Const.MaxDrawBuffers; i++) {
- if (memcmp(ctx->Color.ColorMask[0], ctx->Color.ColorMask[i], 4)) {
- return GL_TRUE;
- }
- }
- return GL_FALSE;
-}
-
-/**
- * Figure out if blend enables/state are different per rt.
- */
-static GLboolean
-blend_per_rt(struct gl_context *ctx)
-{
- if (ctx->Color.BlendEnabled &&
- (ctx->Color.BlendEnabled != ((1 << ctx->Const.MaxDrawBuffers) - 1))) {
- /* This can only happen if GL_EXT_draw_buffers2 is enabled */
- return GL_TRUE;
- }
- if (ctx->Color._BlendFuncPerBuffer || ctx->Color._BlendEquationPerBuffer) {
- /* this can only happen if GL_ARB_draw_buffers_blend is enabled */
- return GL_TRUE;
- }
- return GL_FALSE;
-}
-
-static void
-update_blend( struct st_context *st )
-{
- struct pipe_blend_state *blend = &st->state.blend;
- unsigned num_state = 1;
- unsigned i, j;
-
- memset(blend, 0, sizeof(*blend));
-
- if (blend_per_rt(st->ctx) || colormask_per_rt(st->ctx)) {
- num_state = st->ctx->Const.MaxDrawBuffers;
- blend->independent_blend_enable = 1;
- }
- /* Note it is impossible to correctly deal with EXT_blend_logic_op and
- EXT_draw_buffers2/EXT_blend_equation_separate at the same time.
- These combinations would require support for per-rt logicop enables
- and separate alpha/rgb logicop/blend support respectively. Neither
- possible in gallium nor most hardware. Assume these combinations
- don't happen. */
- if (st->ctx->Color.ColorLogicOpEnabled ||
- (st->ctx->Color.BlendEnabled &&
- st->ctx->Color.Blend[0].EquationRGB == GL_LOGIC_OP)) {
- /* logicop enabled */
- blend->logicop_enable = 1;
- blend->logicop_func = translate_logicop(st->ctx->Color.LogicOp);
- }
- else if (st->ctx->Color.BlendEnabled) {
- /* blending enabled */
- for (i = 0, j = 0; i < num_state; i++) {
-
- blend->rt[i].blend_enable = (st->ctx->Color.BlendEnabled >> i) & 0x1;
-
- if (st->ctx->Extensions.ARB_draw_buffers_blend)
- j = i;
-
- blend->rt[i].rgb_func =
- translate_blend(st->ctx->Color.Blend[j].EquationRGB);
-
- if (st->ctx->Color.Blend[i].EquationRGB == GL_MIN ||
- st->ctx->Color.Blend[i].EquationRGB == GL_MAX) {
- /* Min/max are special */
- blend->rt[i].rgb_src_factor = PIPE_BLENDFACTOR_ONE;
- blend->rt[i].rgb_dst_factor = PIPE_BLENDFACTOR_ONE;
- }
- else {
- blend->rt[i].rgb_src_factor =
- translate_blend(st->ctx->Color.Blend[j].SrcRGB);
- blend->rt[i].rgb_dst_factor =
- translate_blend(st->ctx->Color.Blend[j].DstRGB);
- }
-
- blend->rt[i].alpha_func =
- translate_blend(st->ctx->Color.Blend[j].EquationA);
-
- if (st->ctx->Color.Blend[i].EquationA == GL_MIN ||
- st->ctx->Color.Blend[i].EquationA == GL_MAX) {
- /* Min/max are special */
- blend->rt[i].alpha_src_factor = PIPE_BLENDFACTOR_ONE;
- blend->rt[i].alpha_dst_factor = PIPE_BLENDFACTOR_ONE;
- }
- else {
- blend->rt[i].alpha_src_factor =
- translate_blend(st->ctx->Color.Blend[j].SrcA);
- blend->rt[i].alpha_dst_factor =
- translate_blend(st->ctx->Color.Blend[j].DstA);
- }
- }
- }
- else {
- /* no blending / logicop */
- }
-
- /* Colormask - maybe reverse these bits? */
- for (i = 0; i < num_state; i++) {
- if (st->ctx->Color.ColorMask[i][0])
- blend->rt[i].colormask |= PIPE_MASK_R;
- if (st->ctx->Color.ColorMask[i][1])
- blend->rt[i].colormask |= PIPE_MASK_G;
- if (st->ctx->Color.ColorMask[i][2])
- blend->rt[i].colormask |= PIPE_MASK_B;
- if (st->ctx->Color.ColorMask[i][3])
- blend->rt[i].colormask |= PIPE_MASK_A;
- }
-
- if (st->ctx->Color.DitherFlag)
- blend->dither = 1;
-
- if (st->ctx->Multisample.Enabled) {
- /* unlike in gallium/d3d10 these operations are only performed
- if msaa is enabled */
- if (st->ctx->Multisample.SampleAlphaToCoverage)
- blend->alpha_to_coverage = 1;
- if (st->ctx->Multisample.SampleAlphaToOne)
- blend->alpha_to_one = 1;
- }
-
- cso_set_blend(st->cso_context, blend);
-
- {
- struct pipe_blend_color bc;
- COPY_4FV(bc.color, st->ctx->Color.BlendColor);
- cso_set_blend_color(st->cso_context, &bc);
- }
-}
-
-
-const struct st_tracked_state st_update_blend = {
- "st_update_blend", /* name */
- { /* dirty */
- (_NEW_COLOR | _NEW_MULTISAMPLE), /* XXX _NEW_BLEND someday? */ /* mesa */
- 0, /* st */
- },
- update_blend, /* update */
-};
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ * Brian Paul
+ */
+
+
+#include "st_context.h"
+#include "st_atom.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "cso_cache/cso_context.h"
+
+#include "main/macros.h"
+
+/**
+ * Convert GLenum blend tokens to pipe tokens.
+ * Both blend factors and blend funcs are accepted.
+ */
+static GLuint
+translate_blend(GLenum blend)
+{
+ switch (blend) {
+ /* blend functions */
+ case GL_FUNC_ADD:
+ return PIPE_BLEND_ADD;
+ case GL_FUNC_SUBTRACT:
+ return PIPE_BLEND_SUBTRACT;
+ case GL_FUNC_REVERSE_SUBTRACT:
+ return PIPE_BLEND_REVERSE_SUBTRACT;
+ case GL_MIN:
+ return PIPE_BLEND_MIN;
+ case GL_MAX:
+ return PIPE_BLEND_MAX;
+
+ /* blend factors */
+ case GL_ONE:
+ return PIPE_BLENDFACTOR_ONE;
+ case GL_SRC_COLOR:
+ return PIPE_BLENDFACTOR_SRC_COLOR;
+ case GL_SRC_ALPHA:
+ return PIPE_BLENDFACTOR_SRC_ALPHA;
+ case GL_DST_ALPHA:
+ return PIPE_BLENDFACTOR_DST_ALPHA;
+ case GL_DST_COLOR:
+ return PIPE_BLENDFACTOR_DST_COLOR;
+ case GL_SRC_ALPHA_SATURATE:
+ return PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE;
+ case GL_CONSTANT_COLOR:
+ return PIPE_BLENDFACTOR_CONST_COLOR;
+ case GL_CONSTANT_ALPHA:
+ return PIPE_BLENDFACTOR_CONST_ALPHA;
+ /*
+ return PIPE_BLENDFACTOR_SRC1_COLOR;
+ return PIPE_BLENDFACTOR_SRC1_ALPHA;
+ */
+ case GL_ZERO:
+ return PIPE_BLENDFACTOR_ZERO;
+ case GL_ONE_MINUS_SRC_COLOR:
+ return PIPE_BLENDFACTOR_INV_SRC_COLOR;
+ case GL_ONE_MINUS_SRC_ALPHA:
+ return PIPE_BLENDFACTOR_INV_SRC_ALPHA;
+ case GL_ONE_MINUS_DST_COLOR:
+ return PIPE_BLENDFACTOR_INV_DST_COLOR;
+ case GL_ONE_MINUS_DST_ALPHA:
+ return PIPE_BLENDFACTOR_INV_DST_ALPHA;
+ case GL_ONE_MINUS_CONSTANT_COLOR:
+ return PIPE_BLENDFACTOR_INV_CONST_COLOR;
+ case GL_ONE_MINUS_CONSTANT_ALPHA:
+ return PIPE_BLENDFACTOR_INV_CONST_ALPHA;
+ /*
+ return PIPE_BLENDFACTOR_INV_SRC1_COLOR;
+ return PIPE_BLENDFACTOR_INV_SRC1_ALPHA;
+ */
+ default:
+ assert("invalid GL token in translate_blend()" == NULL);
+ return 0;
+ }
+}
+
+
+/**
+ * Convert GLenum logicop tokens to pipe tokens.
+ */
+static GLuint
+translate_logicop(GLenum logicop)
+{
+ switch (logicop) {
+ case GL_CLEAR:
+ return PIPE_LOGICOP_CLEAR;
+ case GL_NOR:
+ return PIPE_LOGICOP_NOR;
+ case GL_AND_INVERTED:
+ return PIPE_LOGICOP_AND_INVERTED;
+ case GL_COPY_INVERTED:
+ return PIPE_LOGICOP_COPY_INVERTED;
+ case GL_AND_REVERSE:
+ return PIPE_LOGICOP_AND_REVERSE;
+ case GL_INVERT:
+ return PIPE_LOGICOP_INVERT;
+ case GL_XOR:
+ return PIPE_LOGICOP_XOR;
+ case GL_NAND:
+ return PIPE_LOGICOP_NAND;
+ case GL_AND:
+ return PIPE_LOGICOP_AND;
+ case GL_EQUIV:
+ return PIPE_LOGICOP_EQUIV;
+ case GL_NOOP:
+ return PIPE_LOGICOP_NOOP;
+ case GL_OR_INVERTED:
+ return PIPE_LOGICOP_OR_INVERTED;
+ case GL_COPY:
+ return PIPE_LOGICOP_COPY;
+ case GL_OR_REVERSE:
+ return PIPE_LOGICOP_OR_REVERSE;
+ case GL_OR:
+ return PIPE_LOGICOP_OR;
+ case GL_SET:
+ return PIPE_LOGICOP_SET;
+ default:
+ assert("invalid GL token in translate_logicop()" == NULL);
+ return 0;
+ }
+}
+
+/**
+ * Figure out if colormasks are different per rt.
+ */
+static GLboolean
+colormask_per_rt(struct gl_context *ctx)
+{
+ /* a bit suboptimal have to compare lots of values */
+ unsigned i;
+ for (i = 1; i < ctx->Const.MaxDrawBuffers; i++) {
+ if (memcmp(ctx->Color.ColorMask[0], ctx->Color.ColorMask[i], 4)) {
+ return GL_TRUE;
+ }
+ }
+ return GL_FALSE;
+}
+
+/**
+ * Figure out if blend enables/state are different per rt.
+ */
+static GLboolean
+blend_per_rt(struct gl_context *ctx)
+{
+ if (ctx->Color.BlendEnabled &&
+ (ctx->Color.BlendEnabled != ((1 << ctx->Const.MaxDrawBuffers) - 1))) {
+ /* This can only happen if GL_EXT_draw_buffers2 is enabled */
+ return GL_TRUE;
+ }
+ if (ctx->Color._BlendFuncPerBuffer || ctx->Color._BlendEquationPerBuffer) {
+ /* this can only happen if GL_ARB_draw_buffers_blend is enabled */
+ return GL_TRUE;
+ }
+ return GL_FALSE;
+}
+
+static void
+update_blend( struct st_context *st )
+{
+ struct pipe_blend_state *blend = &st->state.blend;
+ unsigned num_state = 1;
+ unsigned i, j;
+
+ memset(blend, 0, sizeof(*blend));
+
+ if (blend_per_rt(st->ctx) || colormask_per_rt(st->ctx)) {
+ num_state = st->ctx->Const.MaxDrawBuffers;
+ blend->independent_blend_enable = 1;
+ }
+ /* Note it is impossible to correctly deal with EXT_blend_logic_op and
+ EXT_draw_buffers2/EXT_blend_equation_separate at the same time.
+ These combinations would require support for per-rt logicop enables
+ and separate alpha/rgb logicop/blend support respectively. Neither
+ possible in gallium nor most hardware. Assume these combinations
+ don't happen. */
+ if (st->ctx->Color.ColorLogicOpEnabled ||
+ (st->ctx->Color.BlendEnabled &&
+ st->ctx->Color.Blend[0].EquationRGB == GL_LOGIC_OP)) {
+ /* logicop enabled */
+ blend->logicop_enable = 1;
+ blend->logicop_func = translate_logicop(st->ctx->Color.LogicOp);
+ }
+ else if (st->ctx->Color.BlendEnabled) {
+ /* blending enabled */
+ for (i = 0, j = 0; i < num_state; i++) {
+
+ blend->rt[i].blend_enable = (st->ctx->Color.BlendEnabled >> i) & 0x1;
+
+ if (st->ctx->Extensions.ARB_draw_buffers_blend)
+ j = i;
+
+ blend->rt[i].rgb_func =
+ translate_blend(st->ctx->Color.Blend[j].EquationRGB);
+
+ if (st->ctx->Color.Blend[i].EquationRGB == GL_MIN ||
+ st->ctx->Color.Blend[i].EquationRGB == GL_MAX) {
+ /* Min/max are special */
+ blend->rt[i].rgb_src_factor = PIPE_BLENDFACTOR_ONE;
+ blend->rt[i].rgb_dst_factor = PIPE_BLENDFACTOR_ONE;
+ }
+ else {
+ blend->rt[i].rgb_src_factor =
+ translate_blend(st->ctx->Color.Blend[j].SrcRGB);
+ blend->rt[i].rgb_dst_factor =
+ translate_blend(st->ctx->Color.Blend[j].DstRGB);
+ }
+
+ blend->rt[i].alpha_func =
+ translate_blend(st->ctx->Color.Blend[j].EquationA);
+
+ if (st->ctx->Color.Blend[i].EquationA == GL_MIN ||
+ st->ctx->Color.Blend[i].EquationA == GL_MAX) {
+ /* Min/max are special */
+ blend->rt[i].alpha_src_factor = PIPE_BLENDFACTOR_ONE;
+ blend->rt[i].alpha_dst_factor = PIPE_BLENDFACTOR_ONE;
+ }
+ else {
+ blend->rt[i].alpha_src_factor =
+ translate_blend(st->ctx->Color.Blend[j].SrcA);
+ blend->rt[i].alpha_dst_factor =
+ translate_blend(st->ctx->Color.Blend[j].DstA);
+ }
+ }
+ }
+ else {
+ /* no blending / logicop */
+ }
+
+ /* Colormask - maybe reverse these bits? */
+ for (i = 0; i < num_state; i++) {
+ if (st->ctx->Color.ColorMask[i][0])
+ blend->rt[i].colormask |= PIPE_MASK_R;
+ if (st->ctx->Color.ColorMask[i][1])
+ blend->rt[i].colormask |= PIPE_MASK_G;
+ if (st->ctx->Color.ColorMask[i][2])
+ blend->rt[i].colormask |= PIPE_MASK_B;
+ if (st->ctx->Color.ColorMask[i][3])
+ blend->rt[i].colormask |= PIPE_MASK_A;
+ }
+
+ if (st->ctx->Color.DitherFlag)
+ blend->dither = 1;
+
+ if (st->ctx->Multisample.Enabled) {
+ /* unlike in gallium/d3d10 these operations are only performed
+ if msaa is enabled */
+ if (st->ctx->Multisample.SampleAlphaToCoverage)
+ blend->alpha_to_coverage = 1;
+ if (st->ctx->Multisample.SampleAlphaToOne)
+ blend->alpha_to_one = 1;
+ }
+
+ cso_set_blend(st->cso_context, blend);
+
+ {
+ struct pipe_blend_color bc;
+ COPY_4FV(bc.color, st->ctx->Color.BlendColor);
+ cso_set_blend_color(st->cso_context, &bc);
+ }
+}
+
+
+const struct st_tracked_state st_update_blend = {
+ "st_update_blend", /* name */
+ { /* dirty */
+ (_NEW_COLOR | _NEW_MULTISAMPLE), /* XXX _NEW_BLEND someday? */ /* mesa */
+ 0, /* st */
+ },
+ update_blend, /* update */
+};
diff --git a/mesalib/src/mesa/state_tracker/st_atom_framebuffer.c b/mesalib/src/mesa/state_tracker/st_atom_framebuffer.c
index 76386fe01..678a270c7 100644
--- a/mesalib/src/mesa/state_tracker/st_atom_framebuffer.c
+++ b/mesalib/src/mesa/state_tracker/st_atom_framebuffer.c
@@ -1,182 +1,182 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- * Brian Paul
- */
-
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_cb_fbo.h"
-#include "st_texture.h"
-#include "pipe/p_context.h"
-#include "cso_cache/cso_context.h"
-#include "util/u_math.h"
-#include "util/u_inlines.h"
-#include "util/u_format.h"
-
-
-/**
- * When doing GL render to texture, we have to be sure that finalize_texture()
- * didn't yank out the pipe_resource that we earlier created a surface for.
- * Check for that here and create a new surface if needed.
- */
-static void
-update_renderbuffer_surface(struct st_context *st,
- struct st_renderbuffer *strb)
-{
- struct pipe_context *pipe = st->pipe;
- struct pipe_resource *resource = strb->rtt->pt;
- int rtt_width = strb->Base.Width;
- int rtt_height = strb->Base.Height;
- enum pipe_format format = st->ctx->Color.sRGBEnabled ? resource->format : util_format_linear(resource->format);
-
- if (!strb->surface ||
- strb->surface->format != format ||
- strb->surface->texture != resource ||
- strb->surface->width != rtt_width ||
- strb->surface->height != rtt_height) {
- GLuint level;
- /* find matching mipmap level size */
- for (level = 0; level <= resource->last_level; level++) {
- if (u_minify(resource->width0, level) == rtt_width &&
- u_minify(resource->height0, level) == rtt_height) {
- struct pipe_surface surf_tmpl;
- memset(&surf_tmpl, 0, sizeof(surf_tmpl));
- surf_tmpl.format = format;
- surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
- surf_tmpl.u.tex.level = level;
- surf_tmpl.u.tex.first_layer = strb->rtt_face + strb->rtt_slice;
- surf_tmpl.u.tex.last_layer = strb->rtt_face + strb->rtt_slice;
-
- pipe_surface_reference(&strb->surface, NULL);
-
- strb->surface = pipe->create_surface(pipe,
- resource,
- &surf_tmpl);
-#if 0
- printf("-- alloc new surface %d x %d into tex %p\n",
- strb->surface->width, strb->surface->height,
- texture);
-#endif
- break;
- }
- }
- }
-}
-
-
-/**
- * Update framebuffer state (color, depth, stencil, etc. buffers)
- */
-static void
-update_framebuffer_state( struct st_context *st )
-{
- struct pipe_framebuffer_state *framebuffer = &st->state.framebuffer;
- struct gl_framebuffer *fb = st->ctx->DrawBuffer;
- struct st_renderbuffer *strb;
- GLuint i;
-
- framebuffer->width = fb->Width;
- framebuffer->height = fb->Height;
-
- /*printf("------ fb size %d x %d\n", fb->Width, fb->Height);*/
-
- /* Examine Mesa's ctx->DrawBuffer->_ColorDrawBuffers state
- * to determine which surfaces to draw to
- */
- framebuffer->nr_cbufs = 0;
- for (i = 0; i < fb->_NumColorDrawBuffers; i++) {
- strb = st_renderbuffer(fb->_ColorDrawBuffers[i]);
-
- if (strb) {
- /*printf("--------- framebuffer surface rtt %p\n", strb->rtt);*/
- if (strb->rtt) {
- /* rendering to a GL texture, may have to update surface */
- update_renderbuffer_surface(st, strb);
- }
-
- if (strb->surface) {
- pipe_surface_reference(&framebuffer->cbufs[framebuffer->nr_cbufs],
- strb->surface);
- framebuffer->nr_cbufs++;
- }
- strb->defined = GL_TRUE; /* we'll be drawing something */
- }
- }
- for (i = framebuffer->nr_cbufs; i < PIPE_MAX_COLOR_BUFS; i++) {
- pipe_surface_reference(&framebuffer->cbufs[i], NULL);
- }
-
- /*
- * Depth/Stencil renderbuffer/surface.
- */
- strb = st_renderbuffer(fb->Attachment[BUFFER_DEPTH].Renderbuffer);
- if (strb) {
- strb = st_renderbuffer(strb->Base.Wrapped);
- if (strb->rtt) {
- /* rendering to a GL texture, may have to update surface */
- update_renderbuffer_surface(st, strb);
- }
- pipe_surface_reference(&framebuffer->zsbuf, strb->surface);
- }
- else {
- strb = st_renderbuffer(fb->Attachment[BUFFER_STENCIL].Renderbuffer);
- if (strb) {
- strb = st_renderbuffer(strb->Base.Wrapped);
- assert(strb->surface);
- pipe_surface_reference(&framebuffer->zsbuf, strb->surface);
- }
- else
- pipe_surface_reference(&framebuffer->zsbuf, NULL);
- }
-
-#ifdef DEBUG
- /* Make sure the resource binding flags were set properly */
- for (i = 0; i < framebuffer->nr_cbufs; i++) {
- assert(framebuffer->cbufs[i]->texture->bind & PIPE_BIND_RENDER_TARGET);
- }
- if (framebuffer->zsbuf) {
- assert(framebuffer->zsbuf->texture->bind & PIPE_BIND_DEPTH_STENCIL);
- }
-#endif
-
- cso_set_framebuffer(st->cso_context, framebuffer);
-}
-
-
-const struct st_tracked_state st_update_framebuffer = {
- "st_update_framebuffer", /* name */
- { /* dirty */
- _NEW_BUFFERS, /* mesa */
- ST_NEW_FRAMEBUFFER, /* st */
- },
- update_framebuffer_state /* update */
-};
-
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ * Brian Paul
+ */
+
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_cb_fbo.h"
+#include "st_texture.h"
+#include "pipe/p_context.h"
+#include "cso_cache/cso_context.h"
+#include "util/u_math.h"
+#include "util/u_inlines.h"
+#include "util/u_format.h"
+
+
+/**
+ * When doing GL render to texture, we have to be sure that finalize_texture()
+ * didn't yank out the pipe_resource that we earlier created a surface for.
+ * Check for that here and create a new surface if needed.
+ */
+static void
+update_renderbuffer_surface(struct st_context *st,
+ struct st_renderbuffer *strb)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_resource *resource = strb->rtt->pt;
+ int rtt_width = strb->Base.Width;
+ int rtt_height = strb->Base.Height;
+ enum pipe_format format = st->ctx->Color.sRGBEnabled ? resource->format : util_format_linear(resource->format);
+
+ if (!strb->surface ||
+ strb->surface->format != format ||
+ strb->surface->texture != resource ||
+ strb->surface->width != rtt_width ||
+ strb->surface->height != rtt_height) {
+ GLuint level;
+ /* find matching mipmap level size */
+ for (level = 0; level <= resource->last_level; level++) {
+ if (u_minify(resource->width0, level) == rtt_width &&
+ u_minify(resource->height0, level) == rtt_height) {
+ struct pipe_surface surf_tmpl;
+ memset(&surf_tmpl, 0, sizeof(surf_tmpl));
+ surf_tmpl.format = format;
+ surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
+ surf_tmpl.u.tex.level = level;
+ surf_tmpl.u.tex.first_layer = strb->rtt_face + strb->rtt_slice;
+ surf_tmpl.u.tex.last_layer = strb->rtt_face + strb->rtt_slice;
+
+ pipe_surface_reference(&strb->surface, NULL);
+
+ strb->surface = pipe->create_surface(pipe,
+ resource,
+ &surf_tmpl);
+#if 0
+ printf("-- alloc new surface %d x %d into tex %p\n",
+ strb->surface->width, strb->surface->height,
+ texture);
+#endif
+ break;
+ }
+ }
+ }
+}
+
+
+/**
+ * Update framebuffer state (color, depth, stencil, etc. buffers)
+ */
+static void
+update_framebuffer_state( struct st_context *st )
+{
+ struct pipe_framebuffer_state *framebuffer = &st->state.framebuffer;
+ struct gl_framebuffer *fb = st->ctx->DrawBuffer;
+ struct st_renderbuffer *strb;
+ GLuint i;
+
+ framebuffer->width = fb->Width;
+ framebuffer->height = fb->Height;
+
+ /*printf("------ fb size %d x %d\n", fb->Width, fb->Height);*/
+
+ /* Examine Mesa's ctx->DrawBuffer->_ColorDrawBuffers state
+ * to determine which surfaces to draw to
+ */
+ framebuffer->nr_cbufs = 0;
+ for (i = 0; i < fb->_NumColorDrawBuffers; i++) {
+ strb = st_renderbuffer(fb->_ColorDrawBuffers[i]);
+
+ if (strb) {
+ /*printf("--------- framebuffer surface rtt %p\n", strb->rtt);*/
+ if (strb->rtt) {
+ /* rendering to a GL texture, may have to update surface */
+ update_renderbuffer_surface(st, strb);
+ }
+
+ if (strb->surface) {
+ pipe_surface_reference(&framebuffer->cbufs[framebuffer->nr_cbufs],
+ strb->surface);
+ framebuffer->nr_cbufs++;
+ }
+ strb->defined = GL_TRUE; /* we'll be drawing something */
+ }
+ }
+ for (i = framebuffer->nr_cbufs; i < PIPE_MAX_COLOR_BUFS; i++) {
+ pipe_surface_reference(&framebuffer->cbufs[i], NULL);
+ }
+
+ /*
+ * Depth/Stencil renderbuffer/surface.
+ */
+ strb = st_renderbuffer(fb->Attachment[BUFFER_DEPTH].Renderbuffer);
+ if (strb) {
+ strb = st_renderbuffer(strb->Base.Wrapped);
+ if (strb->rtt) {
+ /* rendering to a GL texture, may have to update surface */
+ update_renderbuffer_surface(st, strb);
+ }
+ pipe_surface_reference(&framebuffer->zsbuf, strb->surface);
+ }
+ else {
+ strb = st_renderbuffer(fb->Attachment[BUFFER_STENCIL].Renderbuffer);
+ if (strb) {
+ strb = st_renderbuffer(strb->Base.Wrapped);
+ assert(strb->surface);
+ pipe_surface_reference(&framebuffer->zsbuf, strb->surface);
+ }
+ else
+ pipe_surface_reference(&framebuffer->zsbuf, NULL);
+ }
+
+#ifdef DEBUG
+ /* Make sure the resource binding flags were set properly */
+ for (i = 0; i < framebuffer->nr_cbufs; i++) {
+ assert(framebuffer->cbufs[i]->texture->bind & PIPE_BIND_RENDER_TARGET);
+ }
+ if (framebuffer->zsbuf) {
+ assert(framebuffer->zsbuf->texture->bind & PIPE_BIND_DEPTH_STENCIL);
+ }
+#endif
+
+ cso_set_framebuffer(st->cso_context, framebuffer);
+}
+
+
+const struct st_tracked_state st_update_framebuffer = {
+ "st_update_framebuffer", /* name */
+ { /* dirty */
+ _NEW_BUFFERS, /* mesa */
+ ST_NEW_FRAMEBUFFER, /* st */
+ },
+ update_framebuffer_state /* update */
+};
+
diff --git a/mesalib/src/mesa/state_tracker/st_atom_sampler.c b/mesalib/src/mesa/state_tracker/st_atom_sampler.c
index 474cbd589..17596d4c8 100644
--- a/mesalib/src/mesa/state_tracker/st_atom_sampler.c
+++ b/mesalib/src/mesa/state_tracker/st_atom_sampler.c
@@ -1,228 +1,228 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- * Brian Paul
- */
-
-
-#include "main/macros.h"
-
-#include "st_context.h"
-#include "st_cb_texture.h"
-#include "st_format.h"
-#include "st_atom.h"
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-
-#include "cso_cache/cso_context.h"
-
-
-/**
- * Convert GLenum texcoord wrap tokens to pipe tokens.
- */
-static GLuint
-gl_wrap_xlate(GLenum wrap)
-{
- switch (wrap) {
- case GL_REPEAT:
- return PIPE_TEX_WRAP_REPEAT;
- case GL_CLAMP:
- return PIPE_TEX_WRAP_CLAMP;
- case GL_CLAMP_TO_EDGE:
- return PIPE_TEX_WRAP_CLAMP_TO_EDGE;
- case GL_CLAMP_TO_BORDER:
- return PIPE_TEX_WRAP_CLAMP_TO_BORDER;
- case GL_MIRRORED_REPEAT:
- return PIPE_TEX_WRAP_MIRROR_REPEAT;
- case GL_MIRROR_CLAMP_EXT:
- return PIPE_TEX_WRAP_MIRROR_CLAMP;
- case GL_MIRROR_CLAMP_TO_EDGE_EXT:
- return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE;
- case GL_MIRROR_CLAMP_TO_BORDER_EXT:
- return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER;
- default:
- assert(0);
- return 0;
- }
-}
-
-
-static GLuint
-gl_filter_to_mip_filter(GLenum filter)
-{
- switch (filter) {
- case GL_NEAREST:
- case GL_LINEAR:
- return PIPE_TEX_MIPFILTER_NONE;
-
- case GL_NEAREST_MIPMAP_NEAREST:
- case GL_LINEAR_MIPMAP_NEAREST:
- return PIPE_TEX_MIPFILTER_NEAREST;
-
- case GL_NEAREST_MIPMAP_LINEAR:
- case GL_LINEAR_MIPMAP_LINEAR:
- return PIPE_TEX_MIPFILTER_LINEAR;
-
- default:
- assert(0);
- return PIPE_TEX_MIPFILTER_NONE;
- }
-}
-
-
-static GLuint
-gl_filter_to_img_filter(GLenum filter)
-{
- switch (filter) {
- case GL_NEAREST:
- case GL_NEAREST_MIPMAP_NEAREST:
- case GL_NEAREST_MIPMAP_LINEAR:
- return PIPE_TEX_FILTER_NEAREST;
-
- case GL_LINEAR:
- case GL_LINEAR_MIPMAP_NEAREST:
- case GL_LINEAR_MIPMAP_LINEAR:
- return PIPE_TEX_FILTER_LINEAR;
-
- default:
- assert(0);
- return PIPE_TEX_FILTER_NEAREST;
- }
-}
-
-
-static void
-update_samplers(struct st_context *st)
-{
- struct gl_vertex_program *vprog = st->ctx->VertexProgram._Current;
- struct gl_fragment_program *fprog = st->ctx->FragmentProgram._Current;
- const GLbitfield samplersUsed = (vprog->Base.SamplersUsed |
- fprog->Base.SamplersUsed);
- GLuint su;
-
- st->state.num_samplers = 0;
-
- /* loop over sampler units (aka tex image units) */
- for (su = 0; su < st->ctx->Const.MaxTextureImageUnits; su++) {
- struct pipe_sampler_state *sampler = st->state.samplers + su;
-
- memset(sampler, 0, sizeof(*sampler));
-
- if (samplersUsed & (1 << su)) {
- struct gl_texture_object *texobj;
- struct gl_texture_image *teximg;
- GLuint texUnit;
-
- if (fprog->Base.SamplersUsed & (1 << su))
- texUnit = fprog->Base.SamplerUnits[su];
- else
- texUnit = vprog->Base.SamplerUnits[su];
-
- texobj = st->ctx->Texture.Unit[texUnit]._Current;
- if (!texobj) {
- texobj = st_get_default_texture(st);
- }
-
- teximg = texobj->Image[0][texobj->BaseLevel];
-
- sampler->wrap_s = gl_wrap_xlate(texobj->WrapS);
- sampler->wrap_t = gl_wrap_xlate(texobj->WrapT);
- sampler->wrap_r = gl_wrap_xlate(texobj->WrapR);
-
- sampler->min_img_filter = gl_filter_to_img_filter(texobj->MinFilter);
- sampler->min_mip_filter = gl_filter_to_mip_filter(texobj->MinFilter);
- sampler->mag_img_filter = gl_filter_to_img_filter(texobj->MagFilter);
-
- if (texobj->Target != GL_TEXTURE_RECTANGLE_ARB)
- sampler->normalized_coords = 1;
-
- sampler->lod_bias = st->ctx->Texture.Unit[su].LodBias;
-
- sampler->min_lod = texobj->BaseLevel + texobj->MinLod;
- if (sampler->min_lod < texobj->BaseLevel)
- sampler->min_lod = texobj->BaseLevel;
-
- sampler->max_lod = MIN2((GLfloat) texobj->MaxLevel,
- (texobj->MaxLod + texobj->BaseLevel));
- if (sampler->max_lod < sampler->min_lod) {
- /* The GL spec doesn't seem to specify what to do in this case.
- * Swap the values.
- */
- float tmp = sampler->max_lod;
- sampler->max_lod = sampler->min_lod;
- sampler->min_lod = tmp;
- assert(sampler->min_lod <= sampler->max_lod);
- }
-
- st_translate_color(texobj->BorderColor.f,
- teximg ? teximg->_BaseFormat : GL_RGBA,
- sampler->border_color);
-
- sampler->max_anisotropy = (texobj->MaxAnisotropy == 1.0 ? 0 : (GLuint)texobj->MaxAnisotropy);
-
- /* only care about ARB_shadow, not SGI shadow */
- if (texobj->CompareMode == GL_COMPARE_R_TO_TEXTURE) {
- sampler->compare_mode = PIPE_TEX_COMPARE_R_TO_TEXTURE;
- sampler->compare_func
- = st_compare_func_to_pipe(texobj->CompareFunc);
- }
-
- st->state.num_samplers = su + 1;
-
- /*printf("%s su=%u non-null\n", __FUNCTION__, su);*/
- cso_single_sampler(st->cso_context, su, sampler);
- if (su < st->ctx->Const.MaxVertexTextureImageUnits) {
- cso_single_vertex_sampler(st->cso_context, su, sampler);
- }
- }
- else {
- /*printf("%s su=%u null\n", __FUNCTION__, su);*/
- cso_single_sampler(st->cso_context, su, NULL);
- if (su < st->ctx->Const.MaxVertexTextureImageUnits) {
- cso_single_vertex_sampler(st->cso_context, su, NULL);
- }
- }
- }
-
- cso_single_sampler_done(st->cso_context);
- if (st->ctx->Const.MaxVertexTextureImageUnits > 0) {
- cso_single_vertex_sampler_done(st->cso_context);
- }
-}
-
-
-const struct st_tracked_state st_update_sampler = {
- "st_update_sampler", /* name */
- { /* dirty */
- _NEW_TEXTURE, /* mesa */
- 0, /* st */
- },
- update_samplers /* update */
-};
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ * Brian Paul
+ */
+
+
+#include "main/macros.h"
+
+#include "st_context.h"
+#include "st_cb_texture.h"
+#include "st_format.h"
+#include "st_atom.h"
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+
+#include "cso_cache/cso_context.h"
+
+
+/**
+ * Convert GLenum texcoord wrap tokens to pipe tokens.
+ */
+static GLuint
+gl_wrap_xlate(GLenum wrap)
+{
+ switch (wrap) {
+ case GL_REPEAT:
+ return PIPE_TEX_WRAP_REPEAT;
+ case GL_CLAMP:
+ return PIPE_TEX_WRAP_CLAMP;
+ case GL_CLAMP_TO_EDGE:
+ return PIPE_TEX_WRAP_CLAMP_TO_EDGE;
+ case GL_CLAMP_TO_BORDER:
+ return PIPE_TEX_WRAP_CLAMP_TO_BORDER;
+ case GL_MIRRORED_REPEAT:
+ return PIPE_TEX_WRAP_MIRROR_REPEAT;
+ case GL_MIRROR_CLAMP_EXT:
+ return PIPE_TEX_WRAP_MIRROR_CLAMP;
+ case GL_MIRROR_CLAMP_TO_EDGE_EXT:
+ return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE;
+ case GL_MIRROR_CLAMP_TO_BORDER_EXT:
+ return PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER;
+ default:
+ assert(0);
+ return 0;
+ }
+}
+
+
+static GLuint
+gl_filter_to_mip_filter(GLenum filter)
+{
+ switch (filter) {
+ case GL_NEAREST:
+ case GL_LINEAR:
+ return PIPE_TEX_MIPFILTER_NONE;
+
+ case GL_NEAREST_MIPMAP_NEAREST:
+ case GL_LINEAR_MIPMAP_NEAREST:
+ return PIPE_TEX_MIPFILTER_NEAREST;
+
+ case GL_NEAREST_MIPMAP_LINEAR:
+ case GL_LINEAR_MIPMAP_LINEAR:
+ return PIPE_TEX_MIPFILTER_LINEAR;
+
+ default:
+ assert(0);
+ return PIPE_TEX_MIPFILTER_NONE;
+ }
+}
+
+
+static GLuint
+gl_filter_to_img_filter(GLenum filter)
+{
+ switch (filter) {
+ case GL_NEAREST:
+ case GL_NEAREST_MIPMAP_NEAREST:
+ case GL_NEAREST_MIPMAP_LINEAR:
+ return PIPE_TEX_FILTER_NEAREST;
+
+ case GL_LINEAR:
+ case GL_LINEAR_MIPMAP_NEAREST:
+ case GL_LINEAR_MIPMAP_LINEAR:
+ return PIPE_TEX_FILTER_LINEAR;
+
+ default:
+ assert(0);
+ return PIPE_TEX_FILTER_NEAREST;
+ }
+}
+
+
+static void
+update_samplers(struct st_context *st)
+{
+ struct gl_vertex_program *vprog = st->ctx->VertexProgram._Current;
+ struct gl_fragment_program *fprog = st->ctx->FragmentProgram._Current;
+ const GLbitfield samplersUsed = (vprog->Base.SamplersUsed |
+ fprog->Base.SamplersUsed);
+ GLuint su;
+
+ st->state.num_samplers = 0;
+
+ /* loop over sampler units (aka tex image units) */
+ for (su = 0; su < st->ctx->Const.MaxTextureImageUnits; su++) {
+ struct pipe_sampler_state *sampler = st->state.samplers + su;
+
+ memset(sampler, 0, sizeof(*sampler));
+
+ if (samplersUsed & (1 << su)) {
+ struct gl_texture_object *texobj;
+ struct gl_texture_image *teximg;
+ GLuint texUnit;
+
+ if (fprog->Base.SamplersUsed & (1 << su))
+ texUnit = fprog->Base.SamplerUnits[su];
+ else
+ texUnit = vprog->Base.SamplerUnits[su];
+
+ texobj = st->ctx->Texture.Unit[texUnit]._Current;
+ if (!texobj) {
+ texobj = st_get_default_texture(st);
+ }
+
+ teximg = texobj->Image[0][texobj->BaseLevel];
+
+ sampler->wrap_s = gl_wrap_xlate(texobj->WrapS);
+ sampler->wrap_t = gl_wrap_xlate(texobj->WrapT);
+ sampler->wrap_r = gl_wrap_xlate(texobj->WrapR);
+
+ sampler->min_img_filter = gl_filter_to_img_filter(texobj->MinFilter);
+ sampler->min_mip_filter = gl_filter_to_mip_filter(texobj->MinFilter);
+ sampler->mag_img_filter = gl_filter_to_img_filter(texobj->MagFilter);
+
+ if (texobj->Target != GL_TEXTURE_RECTANGLE_ARB)
+ sampler->normalized_coords = 1;
+
+ sampler->lod_bias = st->ctx->Texture.Unit[su].LodBias;
+
+ sampler->min_lod = texobj->BaseLevel + texobj->MinLod;
+ if (sampler->min_lod < texobj->BaseLevel)
+ sampler->min_lod = texobj->BaseLevel;
+
+ sampler->max_lod = MIN2((GLfloat) texobj->MaxLevel,
+ (texobj->MaxLod + texobj->BaseLevel));
+ if (sampler->max_lod < sampler->min_lod) {
+ /* The GL spec doesn't seem to specify what to do in this case.
+ * Swap the values.
+ */
+ float tmp = sampler->max_lod;
+ sampler->max_lod = sampler->min_lod;
+ sampler->min_lod = tmp;
+ assert(sampler->min_lod <= sampler->max_lod);
+ }
+
+ st_translate_color(texobj->BorderColor.f,
+ teximg ? teximg->_BaseFormat : GL_RGBA,
+ sampler->border_color);
+
+ sampler->max_anisotropy = (texobj->MaxAnisotropy == 1.0 ? 0 : (GLuint)texobj->MaxAnisotropy);
+
+ /* only care about ARB_shadow, not SGI shadow */
+ if (texobj->CompareMode == GL_COMPARE_R_TO_TEXTURE) {
+ sampler->compare_mode = PIPE_TEX_COMPARE_R_TO_TEXTURE;
+ sampler->compare_func
+ = st_compare_func_to_pipe(texobj->CompareFunc);
+ }
+
+ st->state.num_samplers = su + 1;
+
+ /*printf("%s su=%u non-null\n", __FUNCTION__, su);*/
+ cso_single_sampler(st->cso_context, su, sampler);
+ if (su < st->ctx->Const.MaxVertexTextureImageUnits) {
+ cso_single_vertex_sampler(st->cso_context, su, sampler);
+ }
+ }
+ else {
+ /*printf("%s su=%u null\n", __FUNCTION__, su);*/
+ cso_single_sampler(st->cso_context, su, NULL);
+ if (su < st->ctx->Const.MaxVertexTextureImageUnits) {
+ cso_single_vertex_sampler(st->cso_context, su, NULL);
+ }
+ }
+ }
+
+ cso_single_sampler_done(st->cso_context);
+ if (st->ctx->Const.MaxVertexTextureImageUnits > 0) {
+ cso_single_vertex_sampler_done(st->cso_context);
+ }
+}
+
+
+const struct st_tracked_state st_update_sampler = {
+ "st_update_sampler", /* name */
+ { /* dirty */
+ _NEW_TEXTURE, /* mesa */
+ 0, /* st */
+ },
+ update_samplers /* update */
+};
diff --git a/mesalib/src/mesa/state_tracker/st_cb_bitmap.c b/mesalib/src/mesa/state_tracker/st_cb_bitmap.c
index 0ea567155..51623c179 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_bitmap.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_bitmap.c
@@ -1,893 +1,893 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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
- */
-
-#include "main/imports.h"
-#include "main/image.h"
-#include "main/bufferobj.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-#include "program/program.h"
-#include "program/prog_print.h"
-
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_atom_constbuf.h"
-#include "st_program.h"
-#include "st_cb_bitmap.h"
-#include "st_texture.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "pipe/p_shader_tokens.h"
-#include "util/u_inlines.h"
-#include "util/u_draw_quad.h"
-#include "util/u_simple_shaders.h"
-#include "program/prog_instruction.h"
-#include "cso_cache/cso_context.h"
-
-
-#if FEATURE_drawpix
-
-/**
- * glBitmaps are drawn as textured quads. The user's bitmap pattern
- * is stored in a texture image. An alpha8 texture format is used.
- * The fragment shader samples a bit (texel) from the texture, then
- * discards the fragment if the bit is off.
- *
- * Note that we actually store the inverse image of the bitmap to
- * simplify the fragment program. An "on" bit gets stored as texel=0x0
- * and an "off" bit is stored as texel=0xff. Then we kill the
- * fragment if the negated texel value is less than zero.
- */
-
-
-/**
- * The bitmap cache attempts to accumulate multiple glBitmap calls in a
- * buffer which is then rendered en mass upon a flush, state change, etc.
- * A wide, short buffer is used to target the common case of a series
- * of glBitmap calls being used to draw text.
- */
-static GLboolean UseBitmapCache = GL_TRUE;
-
-
-#define BITMAP_CACHE_WIDTH 512
-#define BITMAP_CACHE_HEIGHT 32
-
-struct bitmap_cache
-{
- /** Window pos to render the cached image */
- GLint xpos, ypos;
- /** Bounds of region used in window coords */
- GLint xmin, ymin, xmax, ymax;
-
- GLfloat color[4];
-
- /** Bitmap's Z position */
- GLfloat zpos;
-
- struct pipe_resource *texture;
- struct pipe_transfer *trans;
-
- GLboolean empty;
-
- /** An I8 texture image: */
- ubyte *buffer;
-};
-
-
-/** Epsilon for Z comparisons */
-#define Z_EPSILON 1e-06
-
-
-/**
- * Make fragment program for glBitmap:
- * Sample the texture and kill the fragment if the bit is 0.
- * This program will be combined with the user's fragment program.
- */
-static struct st_fragment_program *
-make_bitmap_fragment_program(struct gl_context *ctx, GLuint samplerIndex)
-{
- struct st_context *st = st_context(ctx);
- struct st_fragment_program *stfp;
- struct gl_program *p;
- GLuint ic = 0;
-
- p = ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
- if (!p)
- return NULL;
-
- p->NumInstructions = 3;
-
- p->Instructions = _mesa_alloc_instructions(p->NumInstructions);
- if (!p->Instructions) {
- ctx->Driver.DeleteProgram(ctx, p);
- return NULL;
- }
- _mesa_init_instructions(p->Instructions, p->NumInstructions);
-
- /* TEX tmp0, fragment.texcoord[0], texture[0], 2D; */
- p->Instructions[ic].Opcode = OPCODE_TEX;
- p->Instructions[ic].DstReg.File = PROGRAM_TEMPORARY;
- p->Instructions[ic].DstReg.Index = 0;
- p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
- p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
- p->Instructions[ic].TexSrcUnit = samplerIndex;
- p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
- ic++;
-
- /* KIL if -tmp0 < 0 # texel=0 -> keep / texel=0 -> discard */
- p->Instructions[ic].Opcode = OPCODE_KIL;
- p->Instructions[ic].SrcReg[0].File = PROGRAM_TEMPORARY;
-
- if (st->bitmap.tex_format == PIPE_FORMAT_L8_UNORM)
- p->Instructions[ic].SrcReg[0].Swizzle = SWIZZLE_XXXX;
-
- p->Instructions[ic].SrcReg[0].Index = 0;
- p->Instructions[ic].SrcReg[0].Negate = NEGATE_XYZW;
- ic++;
-
- /* END; */
- p->Instructions[ic++].Opcode = OPCODE_END;
-
- assert(ic == p->NumInstructions);
-
- p->InputsRead = FRAG_BIT_TEX0;
- p->OutputsWritten = 0x0;
- p->SamplersUsed = (1 << samplerIndex);
-
- stfp = (struct st_fragment_program *) p;
- stfp->Base.UsesKill = GL_TRUE;
-
- return stfp;
-}
-
-
-static int
-find_free_bit(uint bitfield)
-{
- int i;
- for (i = 0; i < 32; i++) {
- if ((bitfield & (1 << i)) == 0) {
- return i;
- }
- }
- return -1;
-}
-
-
-/**
- * Combine basic bitmap fragment program with the user-defined program.
- * \param st current context
- * \param fpIn the incoming fragment program
- * \param fpOut the new fragment program which does fragment culling
- * \param bitmap_sampler sampler number for the bitmap texture
- */
-void
-st_make_bitmap_fragment_program(struct st_context *st,
- struct gl_fragment_program *fpIn,
- struct gl_fragment_program **fpOut,
- GLuint *bitmap_sampler)
-{
- struct st_fragment_program *bitmap_prog;
- struct gl_program *newProg;
- uint sampler;
-
- /*
- * Generate new program which is the user-defined program prefixed
- * with the bitmap sampler/kill instructions.
- */
- sampler = find_free_bit(fpIn->Base.SamplersUsed);
- bitmap_prog = make_bitmap_fragment_program(st->ctx, sampler);
-
- newProg = _mesa_combine_programs(st->ctx,
- &bitmap_prog->Base.Base,
- &fpIn->Base);
- /* done with this after combining */
- st_reference_fragprog(st, &bitmap_prog, NULL);
-
-#if 0
- {
- printf("Combined bitmap program:\n");
- _mesa_print_program(newProg);
- printf("InputsRead: 0x%x\n", newProg->InputsRead);
- printf("OutputsWritten: 0x%x\n", newProg->OutputsWritten);
- _mesa_print_parameter_list(newProg->Parameters);
- }
-#endif
-
- /* return results */
- *fpOut = (struct gl_fragment_program *) newProg;
- *bitmap_sampler = sampler;
-}
-
-
-/**
- * Copy user-provide bitmap bits into texture buffer, expanding
- * bits into texels.
- * "On" bits will set texels to 0x0.
- * "Off" bits will not modify texels.
- * Note that the image is actually going to be upside down in
- * the texture. We deal with that with texcoords.
- */
-static void
-unpack_bitmap(struct st_context *st,
- GLint px, GLint py, GLsizei width, GLsizei height,
- const struct gl_pixelstore_attrib *unpack,
- const GLubyte *bitmap,
- ubyte *destBuffer, uint destStride)
-{
- destBuffer += py * destStride + px;
-
- _mesa_expand_bitmap(width, height, unpack, bitmap,
- destBuffer, destStride, 0x0);
-}
-
-
-/**
- * Create a texture which represents a bitmap image.
- */
-static struct pipe_resource *
-make_bitmap_texture(struct gl_context *ctx, GLsizei width, GLsizei height,
- const struct gl_pixelstore_attrib *unpack,
- const GLubyte *bitmap)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_transfer *transfer;
- ubyte *dest;
- struct pipe_resource *pt;
-
- /* PBO source... */
- bitmap = _mesa_map_pbo_source(ctx, unpack, bitmap);
- if (!bitmap) {
- return NULL;
- }
-
- /**
- * Create texture to hold bitmap pattern.
- */
- pt = st_texture_create(st, st->internal_target, st->bitmap.tex_format,
- 0, width, height, 1, 1,
- PIPE_BIND_SAMPLER_VIEW);
- if (!pt) {
- _mesa_unmap_pbo_source(ctx, unpack);
- return NULL;
- }
-
- transfer = pipe_get_transfer(st->pipe, pt, 0, 0,
- PIPE_TRANSFER_WRITE,
- 0, 0, width, height);
-
- dest = pipe_transfer_map(pipe, transfer);
-
- /* Put image into texture transfer */
- memset(dest, 0xff, height * transfer->stride);
- unpack_bitmap(st, 0, 0, width, height, unpack, bitmap,
- dest, transfer->stride);
-
- _mesa_unmap_pbo_source(ctx, unpack);
-
- /* Release transfer */
- pipe_transfer_unmap(pipe, transfer);
- pipe->transfer_destroy(pipe, transfer);
-
- return pt;
-}
-
-static GLuint
-setup_bitmap_vertex_data(struct st_context *st, bool normalized,
- int x, int y, int width, int height,
- float z, const float color[4])
-{
- struct pipe_context *pipe = st->pipe;
- const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
- const GLfloat fb_width = (GLfloat)fb->Width;
- const GLfloat fb_height = (GLfloat)fb->Height;
- const GLfloat x0 = (GLfloat)x;
- const GLfloat x1 = (GLfloat)(x + width);
- const GLfloat y0 = (GLfloat)y;
- const GLfloat y1 = (GLfloat)(y + height);
- GLfloat sLeft = (GLfloat)0.0, sRight = (GLfloat)1.0;
- GLfloat tTop = (GLfloat)0.0, tBot = (GLfloat)1.0 - tTop;
- const GLfloat clip_x0 = (GLfloat)(x0 / fb_width * 2.0 - 1.0);
- const GLfloat clip_y0 = (GLfloat)(y0 / fb_height * 2.0 - 1.0);
- const GLfloat clip_x1 = (GLfloat)(x1 / fb_width * 2.0 - 1.0);
- const GLfloat clip_y1 = (GLfloat)(y1 / fb_height * 2.0 - 1.0);
- const GLuint max_slots = 1; /* 4096 / sizeof(st->bitmap.vertices); */
- GLuint i;
-
- if(!normalized)
- {
- sRight = width;
- tBot = height;
- }
-
- /* XXX: Need to improve buffer_write to allow NO_WAIT (as well as
- * no_flush) updates to buffers where we know there is no conflict
- * with previous data. Currently using max_slots > 1 will cause
- * synchronous rendering if the driver flushes its command buffers
- * between one bitmap and the next. Our flush hook below isn't
- * sufficient to catch this as the driver doesn't tell us when it
- * flushes its own command buffers. Until this gets fixed, pay the
- * price of allocating a new buffer for each bitmap cache-flush to
- * avoid synchronous rendering.
- */
- if (st->bitmap.vbuf_slot >= max_slots) {
- pipe_resource_reference(&st->bitmap.vbuf, NULL);
- st->bitmap.vbuf_slot = 0;
- }
-
- if (!st->bitmap.vbuf) {
- st->bitmap.vbuf = pipe_buffer_create(pipe->screen,
- PIPE_BIND_VERTEX_BUFFER,
- PIPE_USAGE_STREAM,
- max_slots *
- sizeof(st->bitmap.vertices));
- }
-
- /* Positions are in clip coords since we need to do clipping in case
- * the bitmap quad goes beyond the window bounds.
- */
- st->bitmap.vertices[0][0][0] = clip_x0;
- st->bitmap.vertices[0][0][1] = clip_y0;
- st->bitmap.vertices[0][2][0] = sLeft;
- st->bitmap.vertices[0][2][1] = tTop;
-
- st->bitmap.vertices[1][0][0] = clip_x1;
- st->bitmap.vertices[1][0][1] = clip_y0;
- st->bitmap.vertices[1][2][0] = sRight;
- st->bitmap.vertices[1][2][1] = tTop;
-
- st->bitmap.vertices[2][0][0] = clip_x1;
- st->bitmap.vertices[2][0][1] = clip_y1;
- st->bitmap.vertices[2][2][0] = sRight;
- st->bitmap.vertices[2][2][1] = tBot;
-
- st->bitmap.vertices[3][0][0] = clip_x0;
- st->bitmap.vertices[3][0][1] = clip_y1;
- st->bitmap.vertices[3][2][0] = sLeft;
- st->bitmap.vertices[3][2][1] = tBot;
-
- /* same for all verts: */
- for (i = 0; i < 4; i++) {
- st->bitmap.vertices[i][0][2] = z;
- st->bitmap.vertices[i][0][3] = 1.0;
- st->bitmap.vertices[i][1][0] = color[0];
- st->bitmap.vertices[i][1][1] = color[1];
- st->bitmap.vertices[i][1][2] = color[2];
- st->bitmap.vertices[i][1][3] = color[3];
- st->bitmap.vertices[i][2][2] = 0.0; /*R*/
- st->bitmap.vertices[i][2][3] = 1.0; /*Q*/
- }
-
- /* put vertex data into vbuf */
- pipe_buffer_write_nooverlap(st->pipe,
- st->bitmap.vbuf,
- st->bitmap.vbuf_slot
- * sizeof(st->bitmap.vertices),
- sizeof st->bitmap.vertices,
- st->bitmap.vertices);
-
- return st->bitmap.vbuf_slot++ * sizeof st->bitmap.vertices;
-}
-
-
-
-/**
- * Render a glBitmap by drawing a textured quad
- */
-static void
-draw_bitmap_quad(struct gl_context *ctx, GLint x, GLint y, GLfloat z,
- GLsizei width, GLsizei height,
- struct pipe_sampler_view *sv,
- const GLfloat *color)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct cso_context *cso = st->cso_context;
- struct st_fp_variant *fpv;
- struct st_fp_variant_key key;
- GLuint maxSize;
- GLuint offset;
-
- memset(&key, 0, sizeof(key));
- key.st = st;
- key.bitmap = GL_TRUE;
-
- fpv = st_get_fp_variant(st, st->fp, &key);
-
- /* As an optimization, Mesa's fragment programs will sometimes get the
- * primary color from a statevar/constant rather than a varying variable.
- * when that's the case, we need to ensure that we use the 'color'
- * parameter and not the current attribute color (which may have changed
- * through glRasterPos and state validation.
- * So, we force the proper color here. Not elegant, but it works.
- */
- {
- GLfloat colorSave[4];
- COPY_4V(colorSave, ctx->Current.Attrib[VERT_ATTRIB_COLOR0]);
- COPY_4V(ctx->Current.Attrib[VERT_ATTRIB_COLOR0], color);
- st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
- COPY_4V(ctx->Current.Attrib[VERT_ATTRIB_COLOR0], colorSave);
- }
-
-
- /* limit checks */
- /* XXX if the bitmap is larger than the max texture size, break
- * it up into chunks.
- */
- maxSize = 1 << (pipe->screen->get_param(pipe->screen,
- PIPE_CAP_MAX_TEXTURE_2D_LEVELS) - 1);
- assert(width <= (GLsizei)maxSize);
- assert(height <= (GLsizei)maxSize);
-
- cso_save_rasterizer(cso);
- cso_save_samplers(cso);
- cso_save_fragment_sampler_views(cso);
- cso_save_viewport(cso);
- cso_save_fragment_shader(cso);
- cso_save_vertex_shader(cso);
- cso_save_vertex_elements(cso);
- cso_save_vertex_buffers(cso);
-
- /* rasterizer state: just scissor */
- st->bitmap.rasterizer.scissor = ctx->Scissor.Enabled;
- cso_set_rasterizer(cso, &st->bitmap.rasterizer);
-
- /* fragment shader state: TEX lookup program */
- cso_set_fragment_shader_handle(cso, fpv->driver_shader);
-
- /* vertex shader state: position + texcoord pass-through */
- cso_set_vertex_shader_handle(cso, st->bitmap.vs);
-
- /* user samplers, plus our bitmap sampler */
- {
- struct pipe_sampler_state *samplers[PIPE_MAX_SAMPLERS];
- uint num = MAX2(fpv->bitmap_sampler + 1, st->state.num_samplers);
- uint i;
- for (i = 0; i < st->state.num_samplers; i++) {
- samplers[i] = &st->state.samplers[i];
- }
- samplers[fpv->bitmap_sampler] =
- &st->bitmap.samplers[sv->texture->target != PIPE_TEXTURE_RECT];
- cso_set_samplers(cso, num, (const struct pipe_sampler_state **) samplers);
- }
-
- /* user textures, plus the bitmap texture */
- {
- struct pipe_sampler_view *sampler_views[PIPE_MAX_SAMPLERS];
- uint num = MAX2(fpv->bitmap_sampler + 1, st->state.num_textures);
- memcpy(sampler_views, st->state.sampler_views, sizeof(sampler_views));
- sampler_views[fpv->bitmap_sampler] = sv;
- cso_set_fragment_sampler_views(cso, num, sampler_views);
- }
-
- /* viewport state: viewport matching window dims */
- {
- const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
- const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
- const GLfloat width = (GLfloat)fb->Width;
- const GLfloat height = (GLfloat)fb->Height;
- struct pipe_viewport_state vp;
- vp.scale[0] = 0.5f * width;
- vp.scale[1] = height * (invert ? -0.5f : 0.5f);
- vp.scale[2] = 0.5f;
- vp.scale[3] = 1.0f;
- vp.translate[0] = 0.5f * width;
- vp.translate[1] = 0.5f * height;
- vp.translate[2] = 0.5f;
- vp.translate[3] = 0.0f;
- cso_set_viewport(cso, &vp);
- }
-
- cso_set_vertex_elements(cso, 3, st->velems_util_draw);
-
- /* convert Z from [0,1] to [-1,-1] to match viewport Z scale/bias */
- z = z * 2.0 - 1.0;
-
- /* draw textured quad */
- offset = setup_bitmap_vertex_data(st,
- sv->texture->target != PIPE_TEXTURE_RECT,
- x, y, width, height, z, color);
-
- util_draw_vertex_buffer(pipe, st->cso_context, st->bitmap.vbuf, offset,
- PIPE_PRIM_TRIANGLE_FAN,
- 4, /* verts */
- 3); /* attribs/vert */
-
-
- /* restore state */
- cso_restore_rasterizer(cso);
- cso_restore_samplers(cso);
- cso_restore_fragment_sampler_views(cso);
- cso_restore_viewport(cso);
- cso_restore_fragment_shader(cso);
- cso_restore_vertex_shader(cso);
- cso_restore_vertex_elements(cso);
- cso_restore_vertex_buffers(cso);
-}
-
-
-static void
-reset_cache(struct st_context *st)
-{
- struct pipe_context *pipe = st->pipe;
- struct bitmap_cache *cache = st->bitmap.cache;
-
- /*memset(cache->buffer, 0xff, sizeof(cache->buffer));*/
- cache->empty = GL_TRUE;
-
- cache->xmin = 1000000;
- cache->xmax = -1000000;
- cache->ymin = 1000000;
- cache->ymax = -1000000;
-
- if (cache->trans) {
- pipe->transfer_destroy(pipe, cache->trans);
- cache->trans = NULL;
- }
-
- assert(!cache->texture);
-
- /* allocate a new texture */
- cache->texture = st_texture_create(st, PIPE_TEXTURE_2D,
- st->bitmap.tex_format, 0,
- BITMAP_CACHE_WIDTH, BITMAP_CACHE_HEIGHT,
- 1, 1,
- PIPE_BIND_SAMPLER_VIEW);
-}
-
-
-/** Print bitmap image to stdout (debug) */
-static void
-print_cache(const struct bitmap_cache *cache)
-{
- int i, j, k;
-
- for (i = 0; i < BITMAP_CACHE_HEIGHT; i++) {
- k = BITMAP_CACHE_WIDTH * (BITMAP_CACHE_HEIGHT - i - 1);
- for (j = 0; j < BITMAP_CACHE_WIDTH; j++) {
- if (cache->buffer[k])
- printf("X");
- else
- printf(" ");
- k++;
- }
- printf("\n");
- }
-}
-
-
-/**
- * Create gallium pipe_transfer object for the bitmap cache.
- */
-static void
-create_cache_trans(struct st_context *st)
-{
- struct pipe_context *pipe = st->pipe;
- struct bitmap_cache *cache = st->bitmap.cache;
-
- if (cache->trans)
- return;
-
- /* Map the texture transfer.
- * Subsequent glBitmap calls will write into the texture image.
- */
- cache->trans = pipe_get_transfer(st->pipe, cache->texture, 0, 0,
- PIPE_TRANSFER_WRITE, 0, 0,
- BITMAP_CACHE_WIDTH,
- BITMAP_CACHE_HEIGHT);
- cache->buffer = pipe_transfer_map(pipe, cache->trans);
-
- /* init image to all 0xff */
- memset(cache->buffer, 0xff, cache->trans->stride * BITMAP_CACHE_HEIGHT);
-}
-
-
-/**
- * If there's anything in the bitmap cache, draw/flush it now.
- */
-void
-st_flush_bitmap_cache(struct st_context *st)
-{
- if (!st->bitmap.cache->empty) {
- struct bitmap_cache *cache = st->bitmap.cache;
-
- if (st->ctx->DrawBuffer) {
- struct pipe_context *pipe = st->pipe;
- struct pipe_sampler_view *sv;
-
- assert(cache->xmin <= cache->xmax);
-
-/* printf("flush size %d x %d at %d, %d\n",
- cache->xmax - cache->xmin,
- cache->ymax - cache->ymin,
- cache->xpos, cache->ypos);
-*/
-
- /* The texture transfer has been mapped until now.
- * So unmap and release the texture transfer before drawing.
- */
- if (cache->trans) {
- if (0)
- print_cache(cache);
- pipe_transfer_unmap(pipe, cache->trans);
- cache->buffer = NULL;
-
- pipe->transfer_destroy(pipe, cache->trans);
- cache->trans = NULL;
- }
-
- sv = st_create_texture_sampler_view(st->pipe, cache->texture);
- if (sv) {
- draw_bitmap_quad(st->ctx,
- cache->xpos,
- cache->ypos,
- cache->zpos,
- BITMAP_CACHE_WIDTH, BITMAP_CACHE_HEIGHT,
- sv,
- cache->color);
-
- pipe_sampler_view_reference(&sv, NULL);
- }
- }
-
- /* release/free the texture */
- pipe_resource_reference(&cache->texture, NULL);
-
- reset_cache(st);
- }
-}
-
-
-/**
- * Flush bitmap cache and release vertex buffer.
- */
-void
-st_flush_bitmap( struct st_context *st )
-{
- st_flush_bitmap_cache(st);
-
- /* Release vertex buffer to avoid synchronous rendering if we were
- * to map it in the next frame.
- */
- pipe_resource_reference(&st->bitmap.vbuf, NULL);
- st->bitmap.vbuf_slot = 0;
-}
-
-
-/**
- * Try to accumulate this glBitmap call in the bitmap cache.
- * \return GL_TRUE for success, GL_FALSE if bitmap is too large, etc.
- */
-static GLboolean
-accum_bitmap(struct st_context *st,
- GLint x, GLint y, GLsizei width, GLsizei height,
- const struct gl_pixelstore_attrib *unpack,
- const GLubyte *bitmap )
-{
- struct bitmap_cache *cache = st->bitmap.cache;
- int px = -999, py = -999;
- const GLfloat z = st->ctx->Current.RasterPos[2];
-
- if (width > BITMAP_CACHE_WIDTH ||
- height > BITMAP_CACHE_HEIGHT)
- return GL_FALSE; /* too big to cache */
-
- if (!cache->empty) {
- px = x - cache->xpos; /* pos in buffer */
- py = y - cache->ypos;
- if (px < 0 || px + width > BITMAP_CACHE_WIDTH ||
- py < 0 || py + height > BITMAP_CACHE_HEIGHT ||
- !TEST_EQ_4V(st->ctx->Current.RasterColor, cache->color) ||
- ((fabs(z - cache->zpos) > Z_EPSILON))) {
- /* This bitmap would extend beyond cache bounds, or the bitmap
- * color is changing
- * so flush and continue.
- */
- st_flush_bitmap_cache(st);
- }
- }
-
- if (cache->empty) {
- /* Initialize. Center bitmap vertically in the buffer. */
- px = 0;
- py = (BITMAP_CACHE_HEIGHT - height) / 2;
- cache->xpos = x;
- cache->ypos = y - py;
- cache->zpos = z;
- cache->empty = GL_FALSE;
- COPY_4FV(cache->color, st->ctx->Current.RasterColor);
- }
-
- assert(px != -999);
- assert(py != -999);
-
- if (x < cache->xmin)
- cache->xmin = x;
- if (y < cache->ymin)
- cache->ymin = y;
- if (x + width > cache->xmax)
- cache->xmax = x + width;
- if (y + height > cache->ymax)
- cache->ymax = y + height;
-
- /* create the transfer if needed */
- create_cache_trans(st);
-
- unpack_bitmap(st, px, py, width, height, unpack, bitmap,
- cache->buffer, BITMAP_CACHE_WIDTH);
-
- return GL_TRUE; /* accumulated */
-}
-
-
-
-/**
- * Called via ctx->Driver.Bitmap()
- */
-static void
-st_Bitmap(struct gl_context *ctx, GLint x, GLint y,
- GLsizei width, GLsizei height,
- const struct gl_pixelstore_attrib *unpack, const GLubyte *bitmap )
-{
- struct st_context *st = st_context(ctx);
- struct pipe_resource *pt;
-
- if (width == 0 || height == 0)
- return;
-
- st_validate_state(st);
-
- if (!st->bitmap.vs) {
- /* create pass-through vertex shader now */
- const uint semantic_names[] = { TGSI_SEMANTIC_POSITION,
- TGSI_SEMANTIC_COLOR,
- TGSI_SEMANTIC_GENERIC };
- const uint semantic_indexes[] = { 0, 0, 0 };
- st->bitmap.vs = util_make_vertex_passthrough_shader(st->pipe, 3,
- semantic_names,
- semantic_indexes);
- }
-
- if (UseBitmapCache && accum_bitmap(st, x, y, width, height, unpack, bitmap))
- return;
-
- pt = make_bitmap_texture(ctx, width, height, unpack, bitmap);
- if (pt) {
- struct pipe_sampler_view *sv =
- st_create_texture_sampler_view(st->pipe, pt);
-
- assert(pt->target == PIPE_TEXTURE_2D || pt->target == PIPE_TEXTURE_RECT);
-
- if (sv) {
- draw_bitmap_quad(ctx, x, y, ctx->Current.RasterPos[2],
- width, height, sv,
- st->ctx->Current.RasterColor);
-
- pipe_sampler_view_reference(&sv, NULL);
- }
-
- /* release/free the texture */
- pipe_resource_reference(&pt, NULL);
- }
-}
-
-
-/** Per-context init */
-void
-st_init_bitmap_functions(struct dd_function_table *functions)
-{
- functions->Bitmap = st_Bitmap;
-}
-
-
-/** Per-context init */
-void
-st_init_bitmap(struct st_context *st)
-{
- struct pipe_sampler_state *sampler = &st->bitmap.samplers[0];
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *screen = pipe->screen;
-
- /* init sampler state once */
- memset(sampler, 0, sizeof(*sampler));
- sampler->wrap_s = PIPE_TEX_WRAP_CLAMP;
- sampler->wrap_t = PIPE_TEX_WRAP_CLAMP;
- sampler->wrap_r = PIPE_TEX_WRAP_CLAMP;
- sampler->min_img_filter = PIPE_TEX_FILTER_NEAREST;
- sampler->min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
- sampler->mag_img_filter = PIPE_TEX_FILTER_NEAREST;
- st->bitmap.samplers[1] = *sampler;
- st->bitmap.samplers[1].normalized_coords = 1;
-
- /* init baseline rasterizer state once */
- memset(&st->bitmap.rasterizer, 0, sizeof(st->bitmap.rasterizer));
- st->bitmap.rasterizer.gl_rasterization_rules = 1;
-
- /* find a usable texture format */
- if (screen->is_format_supported(screen, PIPE_FORMAT_I8_UNORM,
- PIPE_TEXTURE_2D, 0,
- PIPE_BIND_SAMPLER_VIEW, 0)) {
- st->bitmap.tex_format = PIPE_FORMAT_I8_UNORM;
- }
- else if (screen->is_format_supported(screen, PIPE_FORMAT_A8_UNORM,
- PIPE_TEXTURE_2D, 0,
- PIPE_BIND_SAMPLER_VIEW, 0)) {
- st->bitmap.tex_format = PIPE_FORMAT_A8_UNORM;
- }
- else if (screen->is_format_supported(screen, PIPE_FORMAT_L8_UNORM,
- PIPE_TEXTURE_2D, 0,
- PIPE_BIND_SAMPLER_VIEW, 0)) {
- st->bitmap.tex_format = PIPE_FORMAT_L8_UNORM;
- }
- else {
- /* XXX support more formats */
- assert(0);
- }
-
- /* alloc bitmap cache object */
- st->bitmap.cache = ST_CALLOC_STRUCT(bitmap_cache);
-
- reset_cache(st);
-}
-
-
-/** Per-context tear-down */
-void
-st_destroy_bitmap(struct st_context *st)
-{
- struct pipe_context *pipe = st->pipe;
- struct bitmap_cache *cache = st->bitmap.cache;
-
- if (st->bitmap.vs) {
- cso_delete_vertex_shader(st->cso_context, st->bitmap.vs);
- st->bitmap.vs = NULL;
- }
-
- if (st->bitmap.vbuf) {
- pipe_resource_reference(&st->bitmap.vbuf, NULL);
- st->bitmap.vbuf = NULL;
- }
-
- if (cache) {
- if (cache->trans) {
- pipe_transfer_unmap(pipe, cache->trans);
- pipe->transfer_destroy(pipe, cache->trans);
- }
- pipe_resource_reference(&st->bitmap.cache->texture, NULL);
- free(st->bitmap.cache);
- st->bitmap.cache = NULL;
- }
-}
-
-#endif /* FEATURE_drawpix */
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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
+ */
+
+#include "main/imports.h"
+#include "main/image.h"
+#include "main/bufferobj.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+#include "program/program.h"
+#include "program/prog_print.h"
+
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_atom_constbuf.h"
+#include "st_program.h"
+#include "st_cb_bitmap.h"
+#include "st_texture.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "pipe/p_shader_tokens.h"
+#include "util/u_inlines.h"
+#include "util/u_draw_quad.h"
+#include "util/u_simple_shaders.h"
+#include "program/prog_instruction.h"
+#include "cso_cache/cso_context.h"
+
+
+#if FEATURE_drawpix
+
+/**
+ * glBitmaps are drawn as textured quads. The user's bitmap pattern
+ * is stored in a texture image. An alpha8 texture format is used.
+ * The fragment shader samples a bit (texel) from the texture, then
+ * discards the fragment if the bit is off.
+ *
+ * Note that we actually store the inverse image of the bitmap to
+ * simplify the fragment program. An "on" bit gets stored as texel=0x0
+ * and an "off" bit is stored as texel=0xff. Then we kill the
+ * fragment if the negated texel value is less than zero.
+ */
+
+
+/**
+ * The bitmap cache attempts to accumulate multiple glBitmap calls in a
+ * buffer which is then rendered en mass upon a flush, state change, etc.
+ * A wide, short buffer is used to target the common case of a series
+ * of glBitmap calls being used to draw text.
+ */
+static GLboolean UseBitmapCache = GL_TRUE;
+
+
+#define BITMAP_CACHE_WIDTH 512
+#define BITMAP_CACHE_HEIGHT 32
+
+struct bitmap_cache
+{
+ /** Window pos to render the cached image */
+ GLint xpos, ypos;
+ /** Bounds of region used in window coords */
+ GLint xmin, ymin, xmax, ymax;
+
+ GLfloat color[4];
+
+ /** Bitmap's Z position */
+ GLfloat zpos;
+
+ struct pipe_resource *texture;
+ struct pipe_transfer *trans;
+
+ GLboolean empty;
+
+ /** An I8 texture image: */
+ ubyte *buffer;
+};
+
+
+/** Epsilon for Z comparisons */
+#define Z_EPSILON 1e-06
+
+
+/**
+ * Make fragment program for glBitmap:
+ * Sample the texture and kill the fragment if the bit is 0.
+ * This program will be combined with the user's fragment program.
+ */
+static struct st_fragment_program *
+make_bitmap_fragment_program(struct gl_context *ctx, GLuint samplerIndex)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_fragment_program *stfp;
+ struct gl_program *p;
+ GLuint ic = 0;
+
+ p = ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0);
+ if (!p)
+ return NULL;
+
+ p->NumInstructions = 3;
+
+ p->Instructions = _mesa_alloc_instructions(p->NumInstructions);
+ if (!p->Instructions) {
+ ctx->Driver.DeleteProgram(ctx, p);
+ return NULL;
+ }
+ _mesa_init_instructions(p->Instructions, p->NumInstructions);
+
+ /* TEX tmp0, fragment.texcoord[0], texture[0], 2D; */
+ p->Instructions[ic].Opcode = OPCODE_TEX;
+ p->Instructions[ic].DstReg.File = PROGRAM_TEMPORARY;
+ p->Instructions[ic].DstReg.Index = 0;
+ p->Instructions[ic].SrcReg[0].File = PROGRAM_INPUT;
+ p->Instructions[ic].SrcReg[0].Index = FRAG_ATTRIB_TEX0;
+ p->Instructions[ic].TexSrcUnit = samplerIndex;
+ p->Instructions[ic].TexSrcTarget = TEXTURE_2D_INDEX;
+ ic++;
+
+ /* KIL if -tmp0 < 0 # texel=0 -> keep / texel=0 -> discard */
+ p->Instructions[ic].Opcode = OPCODE_KIL;
+ p->Instructions[ic].SrcReg[0].File = PROGRAM_TEMPORARY;
+
+ if (st->bitmap.tex_format == PIPE_FORMAT_L8_UNORM)
+ p->Instructions[ic].SrcReg[0].Swizzle = SWIZZLE_XXXX;
+
+ p->Instructions[ic].SrcReg[0].Index = 0;
+ p->Instructions[ic].SrcReg[0].Negate = NEGATE_XYZW;
+ ic++;
+
+ /* END; */
+ p->Instructions[ic++].Opcode = OPCODE_END;
+
+ assert(ic == p->NumInstructions);
+
+ p->InputsRead = FRAG_BIT_TEX0;
+ p->OutputsWritten = 0x0;
+ p->SamplersUsed = (1 << samplerIndex);
+
+ stfp = (struct st_fragment_program *) p;
+ stfp->Base.UsesKill = GL_TRUE;
+
+ return stfp;
+}
+
+
+static int
+find_free_bit(uint bitfield)
+{
+ int i;
+ for (i = 0; i < 32; i++) {
+ if ((bitfield & (1 << i)) == 0) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+
+/**
+ * Combine basic bitmap fragment program with the user-defined program.
+ * \param st current context
+ * \param fpIn the incoming fragment program
+ * \param fpOut the new fragment program which does fragment culling
+ * \param bitmap_sampler sampler number for the bitmap texture
+ */
+void
+st_make_bitmap_fragment_program(struct st_context *st,
+ struct gl_fragment_program *fpIn,
+ struct gl_fragment_program **fpOut,
+ GLuint *bitmap_sampler)
+{
+ struct st_fragment_program *bitmap_prog;
+ struct gl_program *newProg;
+ uint sampler;
+
+ /*
+ * Generate new program which is the user-defined program prefixed
+ * with the bitmap sampler/kill instructions.
+ */
+ sampler = find_free_bit(fpIn->Base.SamplersUsed);
+ bitmap_prog = make_bitmap_fragment_program(st->ctx, sampler);
+
+ newProg = _mesa_combine_programs(st->ctx,
+ &bitmap_prog->Base.Base,
+ &fpIn->Base);
+ /* done with this after combining */
+ st_reference_fragprog(st, &bitmap_prog, NULL);
+
+#if 0
+ {
+ printf("Combined bitmap program:\n");
+ _mesa_print_program(newProg);
+ printf("InputsRead: 0x%x\n", newProg->InputsRead);
+ printf("OutputsWritten: 0x%x\n", newProg->OutputsWritten);
+ _mesa_print_parameter_list(newProg->Parameters);
+ }
+#endif
+
+ /* return results */
+ *fpOut = (struct gl_fragment_program *) newProg;
+ *bitmap_sampler = sampler;
+}
+
+
+/**
+ * Copy user-provide bitmap bits into texture buffer, expanding
+ * bits into texels.
+ * "On" bits will set texels to 0x0.
+ * "Off" bits will not modify texels.
+ * Note that the image is actually going to be upside down in
+ * the texture. We deal with that with texcoords.
+ */
+static void
+unpack_bitmap(struct st_context *st,
+ GLint px, GLint py, GLsizei width, GLsizei height,
+ const struct gl_pixelstore_attrib *unpack,
+ const GLubyte *bitmap,
+ ubyte *destBuffer, uint destStride)
+{
+ destBuffer += py * destStride + px;
+
+ _mesa_expand_bitmap(width, height, unpack, bitmap,
+ destBuffer, destStride, 0x0);
+}
+
+
+/**
+ * Create a texture which represents a bitmap image.
+ */
+static struct pipe_resource *
+make_bitmap_texture(struct gl_context *ctx, GLsizei width, GLsizei height,
+ const struct gl_pixelstore_attrib *unpack,
+ const GLubyte *bitmap)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_transfer *transfer;
+ ubyte *dest;
+ struct pipe_resource *pt;
+
+ /* PBO source... */
+ bitmap = _mesa_map_pbo_source(ctx, unpack, bitmap);
+ if (!bitmap) {
+ return NULL;
+ }
+
+ /**
+ * Create texture to hold bitmap pattern.
+ */
+ pt = st_texture_create(st, st->internal_target, st->bitmap.tex_format,
+ 0, width, height, 1, 1,
+ PIPE_BIND_SAMPLER_VIEW);
+ if (!pt) {
+ _mesa_unmap_pbo_source(ctx, unpack);
+ return NULL;
+ }
+
+ transfer = pipe_get_transfer(st->pipe, pt, 0, 0,
+ PIPE_TRANSFER_WRITE,
+ 0, 0, width, height);
+
+ dest = pipe_transfer_map(pipe, transfer);
+
+ /* Put image into texture transfer */
+ memset(dest, 0xff, height * transfer->stride);
+ unpack_bitmap(st, 0, 0, width, height, unpack, bitmap,
+ dest, transfer->stride);
+
+ _mesa_unmap_pbo_source(ctx, unpack);
+
+ /* Release transfer */
+ pipe_transfer_unmap(pipe, transfer);
+ pipe->transfer_destroy(pipe, transfer);
+
+ return pt;
+}
+
+static GLuint
+setup_bitmap_vertex_data(struct st_context *st, bool normalized,
+ int x, int y, int width, int height,
+ float z, const float color[4])
+{
+ struct pipe_context *pipe = st->pipe;
+ const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
+ const GLfloat fb_width = (GLfloat)fb->Width;
+ const GLfloat fb_height = (GLfloat)fb->Height;
+ const GLfloat x0 = (GLfloat)x;
+ const GLfloat x1 = (GLfloat)(x + width);
+ const GLfloat y0 = (GLfloat)y;
+ const GLfloat y1 = (GLfloat)(y + height);
+ GLfloat sLeft = (GLfloat)0.0, sRight = (GLfloat)1.0;
+ GLfloat tTop = (GLfloat)0.0, tBot = (GLfloat)1.0 - tTop;
+ const GLfloat clip_x0 = (GLfloat)(x0 / fb_width * 2.0 - 1.0);
+ const GLfloat clip_y0 = (GLfloat)(y0 / fb_height * 2.0 - 1.0);
+ const GLfloat clip_x1 = (GLfloat)(x1 / fb_width * 2.0 - 1.0);
+ const GLfloat clip_y1 = (GLfloat)(y1 / fb_height * 2.0 - 1.0);
+ const GLuint max_slots = 1; /* 4096 / sizeof(st->bitmap.vertices); */
+ GLuint i;
+
+ if(!normalized)
+ {
+ sRight = width;
+ tBot = height;
+ }
+
+ /* XXX: Need to improve buffer_write to allow NO_WAIT (as well as
+ * no_flush) updates to buffers where we know there is no conflict
+ * with previous data. Currently using max_slots > 1 will cause
+ * synchronous rendering if the driver flushes its command buffers
+ * between one bitmap and the next. Our flush hook below isn't
+ * sufficient to catch this as the driver doesn't tell us when it
+ * flushes its own command buffers. Until this gets fixed, pay the
+ * price of allocating a new buffer for each bitmap cache-flush to
+ * avoid synchronous rendering.
+ */
+ if (st->bitmap.vbuf_slot >= max_slots) {
+ pipe_resource_reference(&st->bitmap.vbuf, NULL);
+ st->bitmap.vbuf_slot = 0;
+ }
+
+ if (!st->bitmap.vbuf) {
+ st->bitmap.vbuf = pipe_buffer_create(pipe->screen,
+ PIPE_BIND_VERTEX_BUFFER,
+ PIPE_USAGE_STREAM,
+ max_slots *
+ sizeof(st->bitmap.vertices));
+ }
+
+ /* Positions are in clip coords since we need to do clipping in case
+ * the bitmap quad goes beyond the window bounds.
+ */
+ st->bitmap.vertices[0][0][0] = clip_x0;
+ st->bitmap.vertices[0][0][1] = clip_y0;
+ st->bitmap.vertices[0][2][0] = sLeft;
+ st->bitmap.vertices[0][2][1] = tTop;
+
+ st->bitmap.vertices[1][0][0] = clip_x1;
+ st->bitmap.vertices[1][0][1] = clip_y0;
+ st->bitmap.vertices[1][2][0] = sRight;
+ st->bitmap.vertices[1][2][1] = tTop;
+
+ st->bitmap.vertices[2][0][0] = clip_x1;
+ st->bitmap.vertices[2][0][1] = clip_y1;
+ st->bitmap.vertices[2][2][0] = sRight;
+ st->bitmap.vertices[2][2][1] = tBot;
+
+ st->bitmap.vertices[3][0][0] = clip_x0;
+ st->bitmap.vertices[3][0][1] = clip_y1;
+ st->bitmap.vertices[3][2][0] = sLeft;
+ st->bitmap.vertices[3][2][1] = tBot;
+
+ /* same for all verts: */
+ for (i = 0; i < 4; i++) {
+ st->bitmap.vertices[i][0][2] = z;
+ st->bitmap.vertices[i][0][3] = 1.0;
+ st->bitmap.vertices[i][1][0] = color[0];
+ st->bitmap.vertices[i][1][1] = color[1];
+ st->bitmap.vertices[i][1][2] = color[2];
+ st->bitmap.vertices[i][1][3] = color[3];
+ st->bitmap.vertices[i][2][2] = 0.0; /*R*/
+ st->bitmap.vertices[i][2][3] = 1.0; /*Q*/
+ }
+
+ /* put vertex data into vbuf */
+ pipe_buffer_write_nooverlap(st->pipe,
+ st->bitmap.vbuf,
+ st->bitmap.vbuf_slot
+ * sizeof(st->bitmap.vertices),
+ sizeof st->bitmap.vertices,
+ st->bitmap.vertices);
+
+ return st->bitmap.vbuf_slot++ * sizeof st->bitmap.vertices;
+}
+
+
+
+/**
+ * Render a glBitmap by drawing a textured quad
+ */
+static void
+draw_bitmap_quad(struct gl_context *ctx, GLint x, GLint y, GLfloat z,
+ GLsizei width, GLsizei height,
+ struct pipe_sampler_view *sv,
+ const GLfloat *color)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct cso_context *cso = st->cso_context;
+ struct st_fp_variant *fpv;
+ struct st_fp_variant_key key;
+ GLuint maxSize;
+ GLuint offset;
+
+ memset(&key, 0, sizeof(key));
+ key.st = st;
+ key.bitmap = GL_TRUE;
+
+ fpv = st_get_fp_variant(st, st->fp, &key);
+
+ /* As an optimization, Mesa's fragment programs will sometimes get the
+ * primary color from a statevar/constant rather than a varying variable.
+ * when that's the case, we need to ensure that we use the 'color'
+ * parameter and not the current attribute color (which may have changed
+ * through glRasterPos and state validation.
+ * So, we force the proper color here. Not elegant, but it works.
+ */
+ {
+ GLfloat colorSave[4];
+ COPY_4V(colorSave, ctx->Current.Attrib[VERT_ATTRIB_COLOR0]);
+ COPY_4V(ctx->Current.Attrib[VERT_ATTRIB_COLOR0], color);
+ st_upload_constants(st, fpv->parameters, PIPE_SHADER_FRAGMENT);
+ COPY_4V(ctx->Current.Attrib[VERT_ATTRIB_COLOR0], colorSave);
+ }
+
+
+ /* limit checks */
+ /* XXX if the bitmap is larger than the max texture size, break
+ * it up into chunks.
+ */
+ maxSize = 1 << (pipe->screen->get_param(pipe->screen,
+ PIPE_CAP_MAX_TEXTURE_2D_LEVELS) - 1);
+ assert(width <= (GLsizei)maxSize);
+ assert(height <= (GLsizei)maxSize);
+
+ cso_save_rasterizer(cso);
+ cso_save_samplers(cso);
+ cso_save_fragment_sampler_views(cso);
+ cso_save_viewport(cso);
+ cso_save_fragment_shader(cso);
+ cso_save_vertex_shader(cso);
+ cso_save_vertex_elements(cso);
+ cso_save_vertex_buffers(cso);
+
+ /* rasterizer state: just scissor */
+ st->bitmap.rasterizer.scissor = ctx->Scissor.Enabled;
+ cso_set_rasterizer(cso, &st->bitmap.rasterizer);
+
+ /* fragment shader state: TEX lookup program */
+ cso_set_fragment_shader_handle(cso, fpv->driver_shader);
+
+ /* vertex shader state: position + texcoord pass-through */
+ cso_set_vertex_shader_handle(cso, st->bitmap.vs);
+
+ /* user samplers, plus our bitmap sampler */
+ {
+ struct pipe_sampler_state *samplers[PIPE_MAX_SAMPLERS];
+ uint num = MAX2(fpv->bitmap_sampler + 1, st->state.num_samplers);
+ uint i;
+ for (i = 0; i < st->state.num_samplers; i++) {
+ samplers[i] = &st->state.samplers[i];
+ }
+ samplers[fpv->bitmap_sampler] =
+ &st->bitmap.samplers[sv->texture->target != PIPE_TEXTURE_RECT];
+ cso_set_samplers(cso, num, (const struct pipe_sampler_state **) samplers);
+ }
+
+ /* user textures, plus the bitmap texture */
+ {
+ struct pipe_sampler_view *sampler_views[PIPE_MAX_SAMPLERS];
+ uint num = MAX2(fpv->bitmap_sampler + 1, st->state.num_textures);
+ memcpy(sampler_views, st->state.sampler_views, sizeof(sampler_views));
+ sampler_views[fpv->bitmap_sampler] = sv;
+ cso_set_fragment_sampler_views(cso, num, sampler_views);
+ }
+
+ /* viewport state: viewport matching window dims */
+ {
+ const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
+ const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
+ const GLfloat width = (GLfloat)fb->Width;
+ const GLfloat height = (GLfloat)fb->Height;
+ struct pipe_viewport_state vp;
+ vp.scale[0] = 0.5f * width;
+ vp.scale[1] = height * (invert ? -0.5f : 0.5f);
+ vp.scale[2] = 0.5f;
+ vp.scale[3] = 1.0f;
+ vp.translate[0] = 0.5f * width;
+ vp.translate[1] = 0.5f * height;
+ vp.translate[2] = 0.5f;
+ vp.translate[3] = 0.0f;
+ cso_set_viewport(cso, &vp);
+ }
+
+ cso_set_vertex_elements(cso, 3, st->velems_util_draw);
+
+ /* convert Z from [0,1] to [-1,-1] to match viewport Z scale/bias */
+ z = z * 2.0 - 1.0;
+
+ /* draw textured quad */
+ offset = setup_bitmap_vertex_data(st,
+ sv->texture->target != PIPE_TEXTURE_RECT,
+ x, y, width, height, z, color);
+
+ util_draw_vertex_buffer(pipe, st->cso_context, st->bitmap.vbuf, offset,
+ PIPE_PRIM_TRIANGLE_FAN,
+ 4, /* verts */
+ 3); /* attribs/vert */
+
+
+ /* restore state */
+ cso_restore_rasterizer(cso);
+ cso_restore_samplers(cso);
+ cso_restore_fragment_sampler_views(cso);
+ cso_restore_viewport(cso);
+ cso_restore_fragment_shader(cso);
+ cso_restore_vertex_shader(cso);
+ cso_restore_vertex_elements(cso);
+ cso_restore_vertex_buffers(cso);
+}
+
+
+static void
+reset_cache(struct st_context *st)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct bitmap_cache *cache = st->bitmap.cache;
+
+ /*memset(cache->buffer, 0xff, sizeof(cache->buffer));*/
+ cache->empty = GL_TRUE;
+
+ cache->xmin = 1000000;
+ cache->xmax = -1000000;
+ cache->ymin = 1000000;
+ cache->ymax = -1000000;
+
+ if (cache->trans) {
+ pipe->transfer_destroy(pipe, cache->trans);
+ cache->trans = NULL;
+ }
+
+ assert(!cache->texture);
+
+ /* allocate a new texture */
+ cache->texture = st_texture_create(st, PIPE_TEXTURE_2D,
+ st->bitmap.tex_format, 0,
+ BITMAP_CACHE_WIDTH, BITMAP_CACHE_HEIGHT,
+ 1, 1,
+ PIPE_BIND_SAMPLER_VIEW);
+}
+
+
+/** Print bitmap image to stdout (debug) */
+static void
+print_cache(const struct bitmap_cache *cache)
+{
+ int i, j, k;
+
+ for (i = 0; i < BITMAP_CACHE_HEIGHT; i++) {
+ k = BITMAP_CACHE_WIDTH * (BITMAP_CACHE_HEIGHT - i - 1);
+ for (j = 0; j < BITMAP_CACHE_WIDTH; j++) {
+ if (cache->buffer[k])
+ printf("X");
+ else
+ printf(" ");
+ k++;
+ }
+ printf("\n");
+ }
+}
+
+
+/**
+ * Create gallium pipe_transfer object for the bitmap cache.
+ */
+static void
+create_cache_trans(struct st_context *st)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct bitmap_cache *cache = st->bitmap.cache;
+
+ if (cache->trans)
+ return;
+
+ /* Map the texture transfer.
+ * Subsequent glBitmap calls will write into the texture image.
+ */
+ cache->trans = pipe_get_transfer(st->pipe, cache->texture, 0, 0,
+ PIPE_TRANSFER_WRITE, 0, 0,
+ BITMAP_CACHE_WIDTH,
+ BITMAP_CACHE_HEIGHT);
+ cache->buffer = pipe_transfer_map(pipe, cache->trans);
+
+ /* init image to all 0xff */
+ memset(cache->buffer, 0xff, cache->trans->stride * BITMAP_CACHE_HEIGHT);
+}
+
+
+/**
+ * If there's anything in the bitmap cache, draw/flush it now.
+ */
+void
+st_flush_bitmap_cache(struct st_context *st)
+{
+ if (!st->bitmap.cache->empty) {
+ struct bitmap_cache *cache = st->bitmap.cache;
+
+ if (st->ctx->DrawBuffer) {
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_sampler_view *sv;
+
+ assert(cache->xmin <= cache->xmax);
+
+/* printf("flush size %d x %d at %d, %d\n",
+ cache->xmax - cache->xmin,
+ cache->ymax - cache->ymin,
+ cache->xpos, cache->ypos);
+*/
+
+ /* The texture transfer has been mapped until now.
+ * So unmap and release the texture transfer before drawing.
+ */
+ if (cache->trans) {
+ if (0)
+ print_cache(cache);
+ pipe_transfer_unmap(pipe, cache->trans);
+ cache->buffer = NULL;
+
+ pipe->transfer_destroy(pipe, cache->trans);
+ cache->trans = NULL;
+ }
+
+ sv = st_create_texture_sampler_view(st->pipe, cache->texture);
+ if (sv) {
+ draw_bitmap_quad(st->ctx,
+ cache->xpos,
+ cache->ypos,
+ cache->zpos,
+ BITMAP_CACHE_WIDTH, BITMAP_CACHE_HEIGHT,
+ sv,
+ cache->color);
+
+ pipe_sampler_view_reference(&sv, NULL);
+ }
+ }
+
+ /* release/free the texture */
+ pipe_resource_reference(&cache->texture, NULL);
+
+ reset_cache(st);
+ }
+}
+
+
+/**
+ * Flush bitmap cache and release vertex buffer.
+ */
+void
+st_flush_bitmap( struct st_context *st )
+{
+ st_flush_bitmap_cache(st);
+
+ /* Release vertex buffer to avoid synchronous rendering if we were
+ * to map it in the next frame.
+ */
+ pipe_resource_reference(&st->bitmap.vbuf, NULL);
+ st->bitmap.vbuf_slot = 0;
+}
+
+
+/**
+ * Try to accumulate this glBitmap call in the bitmap cache.
+ * \return GL_TRUE for success, GL_FALSE if bitmap is too large, etc.
+ */
+static GLboolean
+accum_bitmap(struct st_context *st,
+ GLint x, GLint y, GLsizei width, GLsizei height,
+ const struct gl_pixelstore_attrib *unpack,
+ const GLubyte *bitmap )
+{
+ struct bitmap_cache *cache = st->bitmap.cache;
+ int px = -999, py = -999;
+ const GLfloat z = st->ctx->Current.RasterPos[2];
+
+ if (width > BITMAP_CACHE_WIDTH ||
+ height > BITMAP_CACHE_HEIGHT)
+ return GL_FALSE; /* too big to cache */
+
+ if (!cache->empty) {
+ px = x - cache->xpos; /* pos in buffer */
+ py = y - cache->ypos;
+ if (px < 0 || px + width > BITMAP_CACHE_WIDTH ||
+ py < 0 || py + height > BITMAP_CACHE_HEIGHT ||
+ !TEST_EQ_4V(st->ctx->Current.RasterColor, cache->color) ||
+ ((fabs(z - cache->zpos) > Z_EPSILON))) {
+ /* This bitmap would extend beyond cache bounds, or the bitmap
+ * color is changing
+ * so flush and continue.
+ */
+ st_flush_bitmap_cache(st);
+ }
+ }
+
+ if (cache->empty) {
+ /* Initialize. Center bitmap vertically in the buffer. */
+ px = 0;
+ py = (BITMAP_CACHE_HEIGHT - height) / 2;
+ cache->xpos = x;
+ cache->ypos = y - py;
+ cache->zpos = z;
+ cache->empty = GL_FALSE;
+ COPY_4FV(cache->color, st->ctx->Current.RasterColor);
+ }
+
+ assert(px != -999);
+ assert(py != -999);
+
+ if (x < cache->xmin)
+ cache->xmin = x;
+ if (y < cache->ymin)
+ cache->ymin = y;
+ if (x + width > cache->xmax)
+ cache->xmax = x + width;
+ if (y + height > cache->ymax)
+ cache->ymax = y + height;
+
+ /* create the transfer if needed */
+ create_cache_trans(st);
+
+ unpack_bitmap(st, px, py, width, height, unpack, bitmap,
+ cache->buffer, BITMAP_CACHE_WIDTH);
+
+ return GL_TRUE; /* accumulated */
+}
+
+
+
+/**
+ * Called via ctx->Driver.Bitmap()
+ */
+static void
+st_Bitmap(struct gl_context *ctx, GLint x, GLint y,
+ GLsizei width, GLsizei height,
+ const struct gl_pixelstore_attrib *unpack, const GLubyte *bitmap )
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_resource *pt;
+
+ if (width == 0 || height == 0)
+ return;
+
+ st_validate_state(st);
+
+ if (!st->bitmap.vs) {
+ /* create pass-through vertex shader now */
+ const uint semantic_names[] = { TGSI_SEMANTIC_POSITION,
+ TGSI_SEMANTIC_COLOR,
+ TGSI_SEMANTIC_GENERIC };
+ const uint semantic_indexes[] = { 0, 0, 0 };
+ st->bitmap.vs = util_make_vertex_passthrough_shader(st->pipe, 3,
+ semantic_names,
+ semantic_indexes);
+ }
+
+ if (UseBitmapCache && accum_bitmap(st, x, y, width, height, unpack, bitmap))
+ return;
+
+ pt = make_bitmap_texture(ctx, width, height, unpack, bitmap);
+ if (pt) {
+ struct pipe_sampler_view *sv =
+ st_create_texture_sampler_view(st->pipe, pt);
+
+ assert(pt->target == PIPE_TEXTURE_2D || pt->target == PIPE_TEXTURE_RECT);
+
+ if (sv) {
+ draw_bitmap_quad(ctx, x, y, ctx->Current.RasterPos[2],
+ width, height, sv,
+ st->ctx->Current.RasterColor);
+
+ pipe_sampler_view_reference(&sv, NULL);
+ }
+
+ /* release/free the texture */
+ pipe_resource_reference(&pt, NULL);
+ }
+}
+
+
+/** Per-context init */
+void
+st_init_bitmap_functions(struct dd_function_table *functions)
+{
+ functions->Bitmap = st_Bitmap;
+}
+
+
+/** Per-context init */
+void
+st_init_bitmap(struct st_context *st)
+{
+ struct pipe_sampler_state *sampler = &st->bitmap.samplers[0];
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *screen = pipe->screen;
+
+ /* init sampler state once */
+ memset(sampler, 0, sizeof(*sampler));
+ sampler->wrap_s = PIPE_TEX_WRAP_CLAMP;
+ sampler->wrap_t = PIPE_TEX_WRAP_CLAMP;
+ sampler->wrap_r = PIPE_TEX_WRAP_CLAMP;
+ sampler->min_img_filter = PIPE_TEX_FILTER_NEAREST;
+ sampler->min_mip_filter = PIPE_TEX_MIPFILTER_NONE;
+ sampler->mag_img_filter = PIPE_TEX_FILTER_NEAREST;
+ st->bitmap.samplers[1] = *sampler;
+ st->bitmap.samplers[1].normalized_coords = 1;
+
+ /* init baseline rasterizer state once */
+ memset(&st->bitmap.rasterizer, 0, sizeof(st->bitmap.rasterizer));
+ st->bitmap.rasterizer.gl_rasterization_rules = 1;
+
+ /* find a usable texture format */
+ if (screen->is_format_supported(screen, PIPE_FORMAT_I8_UNORM,
+ PIPE_TEXTURE_2D, 0,
+ PIPE_BIND_SAMPLER_VIEW, 0)) {
+ st->bitmap.tex_format = PIPE_FORMAT_I8_UNORM;
+ }
+ else if (screen->is_format_supported(screen, PIPE_FORMAT_A8_UNORM,
+ PIPE_TEXTURE_2D, 0,
+ PIPE_BIND_SAMPLER_VIEW, 0)) {
+ st->bitmap.tex_format = PIPE_FORMAT_A8_UNORM;
+ }
+ else if (screen->is_format_supported(screen, PIPE_FORMAT_L8_UNORM,
+ PIPE_TEXTURE_2D, 0,
+ PIPE_BIND_SAMPLER_VIEW, 0)) {
+ st->bitmap.tex_format = PIPE_FORMAT_L8_UNORM;
+ }
+ else {
+ /* XXX support more formats */
+ assert(0);
+ }
+
+ /* alloc bitmap cache object */
+ st->bitmap.cache = ST_CALLOC_STRUCT(bitmap_cache);
+
+ reset_cache(st);
+}
+
+
+/** Per-context tear-down */
+void
+st_destroy_bitmap(struct st_context *st)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct bitmap_cache *cache = st->bitmap.cache;
+
+ if (st->bitmap.vs) {
+ cso_delete_vertex_shader(st->cso_context, st->bitmap.vs);
+ st->bitmap.vs = NULL;
+ }
+
+ if (st->bitmap.vbuf) {
+ pipe_resource_reference(&st->bitmap.vbuf, NULL);
+ st->bitmap.vbuf = NULL;
+ }
+
+ if (cache) {
+ if (cache->trans) {
+ pipe_transfer_unmap(pipe, cache->trans);
+ pipe->transfer_destroy(pipe, cache->trans);
+ }
+ pipe_resource_reference(&st->bitmap.cache->texture, NULL);
+ free(st->bitmap.cache);
+ st->bitmap.cache = NULL;
+ }
+}
+
+#endif /* FEATURE_drawpix */
diff --git a/mesalib/src/mesa/state_tracker/st_cb_bufferobjects.c b/mesalib/src/mesa/state_tracker/st_cb_bufferobjects.c
index 12528f49f..9dd1f8a3e 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_bufferobjects.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_bufferobjects.c
@@ -1,468 +1,468 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-
-/**
- * Functions for pixel buffer objects and vertex/element buffer objects.
- */
-
-
-#include "main/imports.h"
-#include "main/mtypes.h"
-#include "main/arrayobj.h"
-#include "main/bufferobj.h"
-
-#include "st_context.h"
-#include "st_cb_bufferobjects.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-
-
-/**
- * There is some duplication between mesa's bufferobjects and our
- * bufmgr buffers. Both have an integer handle and a hashtable to
- * lookup an opaque structure. It would be nice if the handles and
- * internal structure where somehow shared.
- */
-static struct gl_buffer_object *
-st_bufferobj_alloc(struct gl_context *ctx, GLuint name, GLenum target)
-{
- struct st_buffer_object *st_obj = ST_CALLOC_STRUCT(st_buffer_object);
-
- if (!st_obj)
- return NULL;
-
- _mesa_initialize_buffer_object(&st_obj->Base, name, target);
-
- return &st_obj->Base;
-}
-
-
-
-/**
- * Deallocate/free a vertex/pixel buffer object.
- * Called via glDeleteBuffersARB().
- */
-static void
-st_bufferobj_free(struct gl_context *ctx, struct gl_buffer_object *obj)
-{
- struct st_buffer_object *st_obj = st_buffer_object(obj);
-
- assert(obj->RefCount == 0);
- assert(st_obj->transfer == NULL);
-
- if (st_obj->buffer)
- pipe_resource_reference(&st_obj->buffer, NULL);
-
- free(st_obj);
-}
-
-
-
-/**
- * Replace data in a subrange of buffer object. If the data range
- * specified by size + offset extends beyond the end of the buffer or
- * if data is NULL, no copy is performed.
- * Called via glBufferSubDataARB().
- */
-static void
-st_bufferobj_subdata(struct gl_context *ctx,
- GLenum target,
- GLintptrARB offset,
- GLsizeiptrARB size,
- const GLvoid * data, struct gl_buffer_object *obj)
-{
- struct st_buffer_object *st_obj = st_buffer_object(obj);
-
- /* we may be called from VBO code, so double-check params here */
- ASSERT(offset >= 0);
- ASSERT(size >= 0);
- ASSERT(offset + size <= obj->Size);
-
- if (!size)
- return;
-
- /*
- * According to ARB_vertex_buffer_object specification, if data is null,
- * then the contents of the buffer object's data store is undefined. We just
- * ignore, and leave it unchanged.
- */
- if (!data)
- return;
-
- /* Now that transfers are per-context, we don't have to figure out
- * flushing here. Usually drivers won't need to flush in this case
- * even if the buffer is currently referenced by hardware - they
- * just queue the upload as dma rather than mapping the underlying
- * buffer directly.
- */
- pipe_buffer_write(st_context(ctx)->pipe,
- st_obj->buffer,
- offset, size, data);
-}
-
-
-/**
- * Called via glGetBufferSubDataARB().
- */
-static void
-st_bufferobj_get_subdata(struct gl_context *ctx,
- GLenum target,
- GLintptrARB offset,
- GLsizeiptrARB size,
- GLvoid * data, struct gl_buffer_object *obj)
-{
- struct st_buffer_object *st_obj = st_buffer_object(obj);
-
- /* we may be called from VBO code, so double-check params here */
- ASSERT(offset >= 0);
- ASSERT(size >= 0);
- ASSERT(offset + size <= obj->Size);
-
- if (!size)
- return;
-
- pipe_buffer_read(st_context(ctx)->pipe, st_obj->buffer,
- offset, size, data);
-}
-
-
-/**
- * Allocate space for and store data in a buffer object. Any data that was
- * previously stored in the buffer object is lost. If data is NULL,
- * memory will be allocated, but no copy will occur.
- * Called via ctx->Driver.BufferData().
- * \return GL_TRUE for success, GL_FALSE if out of memory
- */
-static GLboolean
-st_bufferobj_data(struct gl_context *ctx,
- GLenum target,
- GLsizeiptrARB size,
- const GLvoid * data,
- GLenum usage,
- struct gl_buffer_object *obj)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct st_buffer_object *st_obj = st_buffer_object(obj);
- unsigned bind, pipe_usage;
-
- st_obj->Base.Size = size;
- st_obj->Base.Usage = usage;
-
- switch(target) {
- case GL_PIXEL_PACK_BUFFER_ARB:
- case GL_PIXEL_UNPACK_BUFFER_ARB:
- bind = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
- break;
- case GL_ARRAY_BUFFER_ARB:
- bind = PIPE_BIND_VERTEX_BUFFER;
- break;
- case GL_ELEMENT_ARRAY_BUFFER_ARB:
- bind = PIPE_BIND_INDEX_BUFFER;
- break;
- default:
- bind = 0;
- }
-
- switch (usage) {
- case GL_STATIC_DRAW:
- case GL_STATIC_READ:
- case GL_STATIC_COPY:
- pipe_usage = PIPE_USAGE_STATIC;
- break;
- case GL_DYNAMIC_DRAW:
- case GL_DYNAMIC_READ:
- case GL_DYNAMIC_COPY:
- pipe_usage = PIPE_USAGE_DYNAMIC;
- break;
- case GL_STREAM_DRAW:
- case GL_STREAM_READ:
- case GL_STREAM_COPY:
- pipe_usage = PIPE_USAGE_STREAM;
- break;
- default:
- pipe_usage = PIPE_USAGE_DEFAULT;
- }
-
- pipe_resource_reference( &st_obj->buffer, NULL );
-
- if (size != 0) {
- st_obj->buffer = pipe_buffer_create(pipe->screen, bind,
- pipe_usage, size);
-
- if (!st_obj->buffer) {
- return GL_FALSE;
- }
-
- if (data)
- pipe_buffer_write(st_context(ctx)->pipe, st_obj->buffer, 0,
- size, data);
- return GL_TRUE;
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Dummy data whose's pointer is used for zero size buffers or ranges.
- */
-static long st_bufferobj_zero_length = 0;
-
-
-
-/**
- * Called via glMapBufferARB().
- */
-static void *
-st_bufferobj_map(struct gl_context *ctx, GLenum target, GLenum access,
- struct gl_buffer_object *obj)
-{
- struct st_buffer_object *st_obj = st_buffer_object(obj);
- uint flags;
-
- switch (access) {
- case GL_WRITE_ONLY:
- flags = PIPE_TRANSFER_WRITE;
- break;
- case GL_READ_ONLY:
- flags = PIPE_TRANSFER_READ;
- break;
- case GL_READ_WRITE:
- default:
- flags = PIPE_TRANSFER_READ_WRITE;
- break;
- }
-
- /* Handle zero-size buffers here rather than in drivers */
- if (obj->Size == 0) {
- obj->Pointer = &st_bufferobj_zero_length;
- }
- else {
- obj->Pointer = pipe_buffer_map(st_context(ctx)->pipe,
- st_obj->buffer,
- flags,
- &st_obj->transfer);
- }
-
- if (obj->Pointer) {
- obj->Offset = 0;
- obj->Length = obj->Size;
- }
- return obj->Pointer;
-}
-
-
-/**
- * Called via glMapBufferRange().
- */
-static void *
-st_bufferobj_map_range(struct gl_context *ctx, GLenum target,
- GLintptr offset, GLsizeiptr length, GLbitfield access,
- struct gl_buffer_object *obj)
-{
- struct pipe_context *pipe = st_context(ctx)->pipe;
- struct st_buffer_object *st_obj = st_buffer_object(obj);
- enum pipe_transfer_usage flags = 0x0;
-
- if (access & GL_MAP_WRITE_BIT)
- flags |= PIPE_TRANSFER_WRITE;
-
- if (access & GL_MAP_READ_BIT)
- flags |= PIPE_TRANSFER_READ;
-
- if (access & GL_MAP_FLUSH_EXPLICIT_BIT)
- flags |= PIPE_TRANSFER_FLUSH_EXPLICIT;
-
- if (access & GL_MAP_INVALIDATE_RANGE_BIT)
- flags |= PIPE_TRANSFER_DISCARD;
-
- if (access & GL_MAP_INVALIDATE_BUFFER_BIT)
- flags |= PIPE_TRANSFER_DISCARD;
-
- if (access & GL_MAP_UNSYNCHRONIZED_BIT)
- flags |= PIPE_TRANSFER_UNSYNCHRONIZED;
-
- /* ... other flags ...
- */
-
- if (access & MESA_MAP_NOWAIT_BIT)
- flags |= PIPE_TRANSFER_DONTBLOCK;
-
- assert(offset >= 0);
- assert(length >= 0);
- assert(offset < obj->Size);
- assert(offset + length <= obj->Size);
-
- /*
- * We go out of way here to hide the degenerate yet valid case of zero
- * length range from the pipe driver.
- */
- if (!length) {
- obj->Pointer = &st_bufferobj_zero_length;
- }
- else {
- obj->Pointer = pipe_buffer_map_range(pipe,
- st_obj->buffer,
- offset, length,
- flags,
- &st_obj->transfer);
- if (obj->Pointer) {
- obj->Pointer = (ubyte *) obj->Pointer + offset;
- }
- }
-
- if (obj->Pointer) {
- obj->Offset = offset;
- obj->Length = length;
- obj->AccessFlags = access;
- }
-
- return obj->Pointer;
-}
-
-
-static void
-st_bufferobj_flush_mapped_range(struct gl_context *ctx, GLenum target,
- GLintptr offset, GLsizeiptr length,
- struct gl_buffer_object *obj)
-{
- struct pipe_context *pipe = st_context(ctx)->pipe;
- struct st_buffer_object *st_obj = st_buffer_object(obj);
-
- /* Subrange is relative to mapped range */
- assert(offset >= 0);
- assert(length >= 0);
- assert(offset + length <= obj->Length);
- assert(obj->Pointer);
-
- if (!length)
- return;
-
- pipe_buffer_flush_mapped_range(pipe, st_obj->transfer,
- obj->Offset + offset, length);
-}
-
-
-/**
- * Called via glUnmapBufferARB().
- */
-static GLboolean
-st_bufferobj_unmap(struct gl_context *ctx, GLenum target, struct gl_buffer_object *obj)
-{
- struct pipe_context *pipe = st_context(ctx)->pipe;
- struct st_buffer_object *st_obj = st_buffer_object(obj);
-
- if (obj->Length)
- pipe_buffer_unmap(pipe, st_obj->transfer);
-
- st_obj->transfer = NULL;
- obj->Pointer = NULL;
- obj->Offset = 0;
- obj->Length = 0;
- return GL_TRUE;
-}
-
-
-/**
- * Called via glCopyBufferSubData().
- */
-static void
-st_copy_buffer_subdata(struct gl_context *ctx,
- struct gl_buffer_object *src,
- struct gl_buffer_object *dst,
- GLintptr readOffset, GLintptr writeOffset,
- GLsizeiptr size)
-{
- struct pipe_context *pipe = st_context(ctx)->pipe;
- struct st_buffer_object *srcObj = st_buffer_object(src);
- struct st_buffer_object *dstObj = st_buffer_object(dst);
- struct pipe_transfer *src_transfer;
- struct pipe_transfer *dst_transfer;
- ubyte *srcPtr, *dstPtr;
-
- if(!size)
- return;
-
- /* buffer should not already be mapped */
- assert(!src->Pointer);
- assert(!dst->Pointer);
-
- srcPtr = (ubyte *) pipe_buffer_map_range(pipe,
- srcObj->buffer,
- readOffset, size,
- PIPE_TRANSFER_READ,
- &src_transfer);
-
- dstPtr = (ubyte *) pipe_buffer_map_range(pipe,
- dstObj->buffer,
- writeOffset, size,
- PIPE_TRANSFER_WRITE,
- &dst_transfer);
-
- if (srcPtr && dstPtr)
- memcpy(dstPtr + writeOffset, srcPtr + readOffset, size);
-
- pipe_buffer_unmap(pipe, src_transfer);
- pipe_buffer_unmap(pipe, dst_transfer);
-}
-
-
-/* TODO: if buffer wasn't created with appropriate usage flags, need
- * to recreate it now and copy contents -- or possibly create a
- * gallium entrypoint to extend the usage flags and let the driver
- * decide if a copy is necessary.
- */
-void
-st_bufferobj_validate_usage(struct st_context *st,
- struct st_buffer_object *obj,
- unsigned usage)
-{
-}
-
-
-void
-st_init_bufferobject_functions(struct dd_function_table *functions)
-{
- functions->NewBufferObject = st_bufferobj_alloc;
- functions->DeleteBuffer = st_bufferobj_free;
- functions->BufferData = st_bufferobj_data;
- functions->BufferSubData = st_bufferobj_subdata;
- functions->GetBufferSubData = st_bufferobj_get_subdata;
- functions->MapBuffer = st_bufferobj_map;
- functions->MapBufferRange = st_bufferobj_map_range;
- functions->FlushMappedBufferRange = st_bufferobj_flush_mapped_range;
- functions->UnmapBuffer = st_bufferobj_unmap;
- functions->CopyBufferSubData = st_copy_buffer_subdata;
-
- /* For GL_APPLE_vertex_array_object */
- functions->NewArrayObject = _mesa_new_array_object;
- functions->DeleteArrayObject = _mesa_delete_array_object;
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+
+/**
+ * Functions for pixel buffer objects and vertex/element buffer objects.
+ */
+
+
+#include "main/imports.h"
+#include "main/mtypes.h"
+#include "main/arrayobj.h"
+#include "main/bufferobj.h"
+
+#include "st_context.h"
+#include "st_cb_bufferobjects.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+
+
+/**
+ * There is some duplication between mesa's bufferobjects and our
+ * bufmgr buffers. Both have an integer handle and a hashtable to
+ * lookup an opaque structure. It would be nice if the handles and
+ * internal structure where somehow shared.
+ */
+static struct gl_buffer_object *
+st_bufferobj_alloc(struct gl_context *ctx, GLuint name, GLenum target)
+{
+ struct st_buffer_object *st_obj = ST_CALLOC_STRUCT(st_buffer_object);
+
+ if (!st_obj)
+ return NULL;
+
+ _mesa_initialize_buffer_object(&st_obj->Base, name, target);
+
+ return &st_obj->Base;
+}
+
+
+
+/**
+ * Deallocate/free a vertex/pixel buffer object.
+ * Called via glDeleteBuffersARB().
+ */
+static void
+st_bufferobj_free(struct gl_context *ctx, struct gl_buffer_object *obj)
+{
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+
+ assert(obj->RefCount == 0);
+ assert(st_obj->transfer == NULL);
+
+ if (st_obj->buffer)
+ pipe_resource_reference(&st_obj->buffer, NULL);
+
+ free(st_obj);
+}
+
+
+
+/**
+ * Replace data in a subrange of buffer object. If the data range
+ * specified by size + offset extends beyond the end of the buffer or
+ * if data is NULL, no copy is performed.
+ * Called via glBufferSubDataARB().
+ */
+static void
+st_bufferobj_subdata(struct gl_context *ctx,
+ GLenum target,
+ GLintptrARB offset,
+ GLsizeiptrARB size,
+ const GLvoid * data, struct gl_buffer_object *obj)
+{
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+
+ /* we may be called from VBO code, so double-check params here */
+ ASSERT(offset >= 0);
+ ASSERT(size >= 0);
+ ASSERT(offset + size <= obj->Size);
+
+ if (!size)
+ return;
+
+ /*
+ * According to ARB_vertex_buffer_object specification, if data is null,
+ * then the contents of the buffer object's data store is undefined. We just
+ * ignore, and leave it unchanged.
+ */
+ if (!data)
+ return;
+
+ /* Now that transfers are per-context, we don't have to figure out
+ * flushing here. Usually drivers won't need to flush in this case
+ * even if the buffer is currently referenced by hardware - they
+ * just queue the upload as dma rather than mapping the underlying
+ * buffer directly.
+ */
+ pipe_buffer_write(st_context(ctx)->pipe,
+ st_obj->buffer,
+ offset, size, data);
+}
+
+
+/**
+ * Called via glGetBufferSubDataARB().
+ */
+static void
+st_bufferobj_get_subdata(struct gl_context *ctx,
+ GLenum target,
+ GLintptrARB offset,
+ GLsizeiptrARB size,
+ GLvoid * data, struct gl_buffer_object *obj)
+{
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+
+ /* we may be called from VBO code, so double-check params here */
+ ASSERT(offset >= 0);
+ ASSERT(size >= 0);
+ ASSERT(offset + size <= obj->Size);
+
+ if (!size)
+ return;
+
+ pipe_buffer_read(st_context(ctx)->pipe, st_obj->buffer,
+ offset, size, data);
+}
+
+
+/**
+ * Allocate space for and store data in a buffer object. Any data that was
+ * previously stored in the buffer object is lost. If data is NULL,
+ * memory will be allocated, but no copy will occur.
+ * Called via ctx->Driver.BufferData().
+ * \return GL_TRUE for success, GL_FALSE if out of memory
+ */
+static GLboolean
+st_bufferobj_data(struct gl_context *ctx,
+ GLenum target,
+ GLsizeiptrARB size,
+ const GLvoid * data,
+ GLenum usage,
+ struct gl_buffer_object *obj)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+ unsigned bind, pipe_usage;
+
+ st_obj->Base.Size = size;
+ st_obj->Base.Usage = usage;
+
+ switch(target) {
+ case GL_PIXEL_PACK_BUFFER_ARB:
+ case GL_PIXEL_UNPACK_BUFFER_ARB:
+ bind = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
+ break;
+ case GL_ARRAY_BUFFER_ARB:
+ bind = PIPE_BIND_VERTEX_BUFFER;
+ break;
+ case GL_ELEMENT_ARRAY_BUFFER_ARB:
+ bind = PIPE_BIND_INDEX_BUFFER;
+ break;
+ default:
+ bind = 0;
+ }
+
+ switch (usage) {
+ case GL_STATIC_DRAW:
+ case GL_STATIC_READ:
+ case GL_STATIC_COPY:
+ pipe_usage = PIPE_USAGE_STATIC;
+ break;
+ case GL_DYNAMIC_DRAW:
+ case GL_DYNAMIC_READ:
+ case GL_DYNAMIC_COPY:
+ pipe_usage = PIPE_USAGE_DYNAMIC;
+ break;
+ case GL_STREAM_DRAW:
+ case GL_STREAM_READ:
+ case GL_STREAM_COPY:
+ pipe_usage = PIPE_USAGE_STREAM;
+ break;
+ default:
+ pipe_usage = PIPE_USAGE_DEFAULT;
+ }
+
+ pipe_resource_reference( &st_obj->buffer, NULL );
+
+ if (size != 0) {
+ st_obj->buffer = pipe_buffer_create(pipe->screen, bind,
+ pipe_usage, size);
+
+ if (!st_obj->buffer) {
+ return GL_FALSE;
+ }
+
+ if (data)
+ pipe_buffer_write(st_context(ctx)->pipe, st_obj->buffer, 0,
+ size, data);
+ return GL_TRUE;
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Dummy data whose's pointer is used for zero size buffers or ranges.
+ */
+static long st_bufferobj_zero_length = 0;
+
+
+
+/**
+ * Called via glMapBufferARB().
+ */
+static void *
+st_bufferobj_map(struct gl_context *ctx, GLenum target, GLenum access,
+ struct gl_buffer_object *obj)
+{
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+ uint flags;
+
+ switch (access) {
+ case GL_WRITE_ONLY:
+ flags = PIPE_TRANSFER_WRITE;
+ break;
+ case GL_READ_ONLY:
+ flags = PIPE_TRANSFER_READ;
+ break;
+ case GL_READ_WRITE:
+ default:
+ flags = PIPE_TRANSFER_READ_WRITE;
+ break;
+ }
+
+ /* Handle zero-size buffers here rather than in drivers */
+ if (obj->Size == 0) {
+ obj->Pointer = &st_bufferobj_zero_length;
+ }
+ else {
+ obj->Pointer = pipe_buffer_map(st_context(ctx)->pipe,
+ st_obj->buffer,
+ flags,
+ &st_obj->transfer);
+ }
+
+ if (obj->Pointer) {
+ obj->Offset = 0;
+ obj->Length = obj->Size;
+ }
+ return obj->Pointer;
+}
+
+
+/**
+ * Called via glMapBufferRange().
+ */
+static void *
+st_bufferobj_map_range(struct gl_context *ctx, GLenum target,
+ GLintptr offset, GLsizeiptr length, GLbitfield access,
+ struct gl_buffer_object *obj)
+{
+ struct pipe_context *pipe = st_context(ctx)->pipe;
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+ enum pipe_transfer_usage flags = 0x0;
+
+ if (access & GL_MAP_WRITE_BIT)
+ flags |= PIPE_TRANSFER_WRITE;
+
+ if (access & GL_MAP_READ_BIT)
+ flags |= PIPE_TRANSFER_READ;
+
+ if (access & GL_MAP_FLUSH_EXPLICIT_BIT)
+ flags |= PIPE_TRANSFER_FLUSH_EXPLICIT;
+
+ if (access & GL_MAP_INVALIDATE_RANGE_BIT)
+ flags |= PIPE_TRANSFER_DISCARD;
+
+ if (access & GL_MAP_INVALIDATE_BUFFER_BIT)
+ flags |= PIPE_TRANSFER_DISCARD;
+
+ if (access & GL_MAP_UNSYNCHRONIZED_BIT)
+ flags |= PIPE_TRANSFER_UNSYNCHRONIZED;
+
+ /* ... other flags ...
+ */
+
+ if (access & MESA_MAP_NOWAIT_BIT)
+ flags |= PIPE_TRANSFER_DONTBLOCK;
+
+ assert(offset >= 0);
+ assert(length >= 0);
+ assert(offset < obj->Size);
+ assert(offset + length <= obj->Size);
+
+ /*
+ * We go out of way here to hide the degenerate yet valid case of zero
+ * length range from the pipe driver.
+ */
+ if (!length) {
+ obj->Pointer = &st_bufferobj_zero_length;
+ }
+ else {
+ obj->Pointer = pipe_buffer_map_range(pipe,
+ st_obj->buffer,
+ offset, length,
+ flags,
+ &st_obj->transfer);
+ if (obj->Pointer) {
+ obj->Pointer = (ubyte *) obj->Pointer + offset;
+ }
+ }
+
+ if (obj->Pointer) {
+ obj->Offset = offset;
+ obj->Length = length;
+ obj->AccessFlags = access;
+ }
+
+ return obj->Pointer;
+}
+
+
+static void
+st_bufferobj_flush_mapped_range(struct gl_context *ctx, GLenum target,
+ GLintptr offset, GLsizeiptr length,
+ struct gl_buffer_object *obj)
+{
+ struct pipe_context *pipe = st_context(ctx)->pipe;
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+
+ /* Subrange is relative to mapped range */
+ assert(offset >= 0);
+ assert(length >= 0);
+ assert(offset + length <= obj->Length);
+ assert(obj->Pointer);
+
+ if (!length)
+ return;
+
+ pipe_buffer_flush_mapped_range(pipe, st_obj->transfer,
+ obj->Offset + offset, length);
+}
+
+
+/**
+ * Called via glUnmapBufferARB().
+ */
+static GLboolean
+st_bufferobj_unmap(struct gl_context *ctx, GLenum target, struct gl_buffer_object *obj)
+{
+ struct pipe_context *pipe = st_context(ctx)->pipe;
+ struct st_buffer_object *st_obj = st_buffer_object(obj);
+
+ if (obj->Length)
+ pipe_buffer_unmap(pipe, st_obj->transfer);
+
+ st_obj->transfer = NULL;
+ obj->Pointer = NULL;
+ obj->Offset = 0;
+ obj->Length = 0;
+ return GL_TRUE;
+}
+
+
+/**
+ * Called via glCopyBufferSubData().
+ */
+static void
+st_copy_buffer_subdata(struct gl_context *ctx,
+ struct gl_buffer_object *src,
+ struct gl_buffer_object *dst,
+ GLintptr readOffset, GLintptr writeOffset,
+ GLsizeiptr size)
+{
+ struct pipe_context *pipe = st_context(ctx)->pipe;
+ struct st_buffer_object *srcObj = st_buffer_object(src);
+ struct st_buffer_object *dstObj = st_buffer_object(dst);
+ struct pipe_transfer *src_transfer;
+ struct pipe_transfer *dst_transfer;
+ ubyte *srcPtr, *dstPtr;
+
+ if(!size)
+ return;
+
+ /* buffer should not already be mapped */
+ assert(!src->Pointer);
+ assert(!dst->Pointer);
+
+ srcPtr = (ubyte *) pipe_buffer_map_range(pipe,
+ srcObj->buffer,
+ readOffset, size,
+ PIPE_TRANSFER_READ,
+ &src_transfer);
+
+ dstPtr = (ubyte *) pipe_buffer_map_range(pipe,
+ dstObj->buffer,
+ writeOffset, size,
+ PIPE_TRANSFER_WRITE,
+ &dst_transfer);
+
+ if (srcPtr && dstPtr)
+ memcpy(dstPtr + writeOffset, srcPtr + readOffset, size);
+
+ pipe_buffer_unmap(pipe, src_transfer);
+ pipe_buffer_unmap(pipe, dst_transfer);
+}
+
+
+/* TODO: if buffer wasn't created with appropriate usage flags, need
+ * to recreate it now and copy contents -- or possibly create a
+ * gallium entrypoint to extend the usage flags and let the driver
+ * decide if a copy is necessary.
+ */
+void
+st_bufferobj_validate_usage(struct st_context *st,
+ struct st_buffer_object *obj,
+ unsigned usage)
+{
+}
+
+
+void
+st_init_bufferobject_functions(struct dd_function_table *functions)
+{
+ functions->NewBufferObject = st_bufferobj_alloc;
+ functions->DeleteBuffer = st_bufferobj_free;
+ functions->BufferData = st_bufferobj_data;
+ functions->BufferSubData = st_bufferobj_subdata;
+ functions->GetBufferSubData = st_bufferobj_get_subdata;
+ functions->MapBuffer = st_bufferobj_map;
+ functions->MapBufferRange = st_bufferobj_map_range;
+ functions->FlushMappedBufferRange = st_bufferobj_flush_mapped_range;
+ functions->UnmapBuffer = st_bufferobj_unmap;
+ functions->CopyBufferSubData = st_copy_buffer_subdata;
+
+ /* For GL_APPLE_vertex_array_object */
+ functions->NewArrayObject = _mesa_new_array_object;
+ functions->DeleteArrayObject = _mesa_delete_array_object;
+}
diff --git a/mesalib/src/mesa/state_tracker/st_cb_clear.c b/mesalib/src/mesa/state_tracker/st_cb_clear.c
index 0e0c4326e..79e58182f 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_clear.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_clear.c
@@ -1,579 +1,579 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- * Copyright 2009 VMware, Inc. 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- * Brian Paul
- * Michel Dänzer
- */
-
-#include "main/glheader.h"
-#include "main/formats.h"
-#include "main/macros.h"
-#include "program/prog_instruction.h"
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_cb_accum.h"
-#include "st_cb_clear.h"
-#include "st_cb_fbo.h"
-#include "st_format.h"
-#include "st_program.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_shader_tokens.h"
-#include "pipe/p_state.h"
-#include "pipe/p_defines.h"
-#include "util/u_format.h"
-#include "util/u_inlines.h"
-#include "util/u_simple_shaders.h"
-#include "util/u_draw_quad.h"
-
-#include "cso_cache/cso_context.h"
-
-
-/**
- * Do per-context initialization for glClear.
- */
-void
-st_init_clear(struct st_context *st)
-{
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *pscreen = st->pipe->screen;
-
- memset(&st->clear, 0, sizeof(st->clear));
-
- st->clear.raster.gl_rasterization_rules = 1;
- st->clear.enable_ds_separate = pscreen->get_param(pscreen, PIPE_CAP_DEPTHSTENCIL_CLEAR_SEPARATE);
-
- /* fragment shader state: color pass-through program */
- st->clear.fs = util_make_fragment_passthrough_shader(pipe);
-
- /* vertex shader state: color/position pass-through */
- {
- const uint semantic_names[] = { TGSI_SEMANTIC_POSITION,
- TGSI_SEMANTIC_COLOR };
- const uint semantic_indexes[] = { 0, 0 };
- st->clear.vs = util_make_vertex_passthrough_shader(pipe, 2,
- semantic_names,
- semantic_indexes);
- }
-}
-
-
-/**
- * Free per-context state for glClear.
- */
-void
-st_destroy_clear(struct st_context *st)
-{
- if (st->clear.fs) {
- cso_delete_fragment_shader(st->cso_context, st->clear.fs);
- st->clear.fs = NULL;
- }
- if (st->clear.vs) {
- cso_delete_vertex_shader(st->cso_context, st->clear.vs);
- st->clear.vs = NULL;
- }
- if (st->clear.vbuf) {
- pipe_resource_reference(&st->clear.vbuf, NULL);
- st->clear.vbuf = NULL;
- }
-}
-
-
-/**
- * Draw a screen-aligned quadrilateral.
- * Coords are clip coords with y=0=bottom.
- */
-static void
-draw_quad(struct st_context *st,
- float x0, float y0, float x1, float y1, GLfloat z,
- const GLfloat color[4])
-{
- struct pipe_context *pipe = st->pipe;
-
- /* XXX: Need to improve buffer_write to allow NO_WAIT (as well as
- * no_flush) updates to buffers where we know there is no conflict
- * with previous data. Currently using max_slots > 1 will cause
- * synchronous rendering if the driver flushes its command buffers
- * between one bitmap and the next. Our flush hook below isn't
- * sufficient to catch this as the driver doesn't tell us when it
- * flushes its own command buffers. Until this gets fixed, pay the
- * price of allocating a new buffer for each bitmap cache-flush to
- * avoid synchronous rendering.
- */
- const GLuint max_slots = 1; /* 1024 / sizeof(st->clear.vertices); */
- GLuint i;
-
- if (st->clear.vbuf_slot >= max_slots) {
- pipe_resource_reference(&st->clear.vbuf, NULL);
- st->clear.vbuf_slot = 0;
- }
-
- if (!st->clear.vbuf) {
- st->clear.vbuf = pipe_buffer_create(pipe->screen,
- PIPE_BIND_VERTEX_BUFFER,
- PIPE_USAGE_STREAM,
- max_slots * sizeof(st->clear.vertices));
- }
-
- /* positions */
- st->clear.vertices[0][0][0] = x0;
- st->clear.vertices[0][0][1] = y0;
-
- st->clear.vertices[1][0][0] = x1;
- st->clear.vertices[1][0][1] = y0;
-
- st->clear.vertices[2][0][0] = x1;
- st->clear.vertices[2][0][1] = y1;
-
- st->clear.vertices[3][0][0] = x0;
- st->clear.vertices[3][0][1] = y1;
-
- /* same for all verts: */
- for (i = 0; i < 4; i++) {
- st->clear.vertices[i][0][2] = z;
- st->clear.vertices[i][0][3] = 1.0;
- st->clear.vertices[i][1][0] = color[0];
- st->clear.vertices[i][1][1] = color[1];
- st->clear.vertices[i][1][2] = color[2];
- st->clear.vertices[i][1][3] = color[3];
- }
-
- /* put vertex data into vbuf */
- pipe_buffer_write_nooverlap(st->pipe, st->clear.vbuf,
- st->clear.vbuf_slot
- * sizeof(st->clear.vertices),
- sizeof(st->clear.vertices),
- st->clear.vertices);
-
- /* draw */
- util_draw_vertex_buffer(pipe,
- st->cso_context,
- st->clear.vbuf,
- st->clear.vbuf_slot * sizeof(st->clear.vertices),
- PIPE_PRIM_TRIANGLE_FAN,
- 4, /* verts */
- 2); /* attribs/vert */
-
- /* Increment slot */
- st->clear.vbuf_slot++;
-}
-
-
-
-/**
- * Do glClear by drawing a quadrilateral.
- * The vertices of the quad will be computed from the
- * ctx->DrawBuffer->_X/Ymin/max fields.
- */
-static void
-clear_with_quad(struct gl_context *ctx,
- GLboolean color, GLboolean depth, GLboolean stencil)
-{
- struct st_context *st = st_context(ctx);
- const struct gl_framebuffer *fb = ctx->DrawBuffer;
- const GLfloat fb_width = (GLfloat) fb->Width;
- const GLfloat fb_height = (GLfloat) fb->Height;
- const GLfloat x0 = (GLfloat) ctx->DrawBuffer->_Xmin / fb_width * 2.0f - 1.0f;
- const GLfloat x1 = (GLfloat) ctx->DrawBuffer->_Xmax / fb_width * 2.0f - 1.0f;
- const GLfloat y0 = (GLfloat) ctx->DrawBuffer->_Ymin / fb_height * 2.0f - 1.0f;
- const GLfloat y1 = (GLfloat) ctx->DrawBuffer->_Ymax / fb_height * 2.0f - 1.0f;
- float clearColor[4];
-
- /*
- printf("%s %s%s%s %f,%f %f,%f\n", __FUNCTION__,
- color ? "color, " : "",
- depth ? "depth, " : "",
- stencil ? "stencil" : "",
- x0, y0,
- x1, y1);
- */
-
- cso_save_blend(st->cso_context);
- cso_save_stencil_ref(st->cso_context);
- cso_save_depth_stencil_alpha(st->cso_context);
- cso_save_rasterizer(st->cso_context);
- cso_save_viewport(st->cso_context);
- cso_save_clip(st->cso_context);
- cso_save_fragment_shader(st->cso_context);
- cso_save_vertex_shader(st->cso_context);
- cso_save_vertex_elements(st->cso_context);
- cso_save_vertex_buffers(st->cso_context);
-
- /* blend state: RGBA masking */
- {
- struct pipe_blend_state blend;
- memset(&blend, 0, sizeof(blend));
- blend.rt[0].rgb_src_factor = PIPE_BLENDFACTOR_ONE;
- blend.rt[0].alpha_src_factor = PIPE_BLENDFACTOR_ONE;
- blend.rt[0].rgb_dst_factor = PIPE_BLENDFACTOR_ZERO;
- blend.rt[0].alpha_dst_factor = PIPE_BLENDFACTOR_ZERO;
- if (color) {
- if (ctx->Color.ColorMask[0][0])
- blend.rt[0].colormask |= PIPE_MASK_R;
- if (ctx->Color.ColorMask[0][1])
- blend.rt[0].colormask |= PIPE_MASK_G;
- if (ctx->Color.ColorMask[0][2])
- blend.rt[0].colormask |= PIPE_MASK_B;
- if (ctx->Color.ColorMask[0][3])
- blend.rt[0].colormask |= PIPE_MASK_A;
- if (st->ctx->Color.DitherFlag)
- blend.dither = 1;
- }
- cso_set_blend(st->cso_context, &blend);
- }
-
- /* depth_stencil state: always pass/set to ref value */
- {
- struct pipe_depth_stencil_alpha_state depth_stencil;
- memset(&depth_stencil, 0, sizeof(depth_stencil));
- if (depth) {
- depth_stencil.depth.enabled = 1;
- depth_stencil.depth.writemask = 1;
- depth_stencil.depth.func = PIPE_FUNC_ALWAYS;
- }
-
- if (stencil) {
- struct pipe_stencil_ref stencil_ref;
- memset(&stencil_ref, 0, sizeof(stencil_ref));
- depth_stencil.stencil[0].enabled = 1;
- depth_stencil.stencil[0].func = PIPE_FUNC_ALWAYS;
- depth_stencil.stencil[0].fail_op = PIPE_STENCIL_OP_REPLACE;
- depth_stencil.stencil[0].zpass_op = PIPE_STENCIL_OP_REPLACE;
- depth_stencil.stencil[0].zfail_op = PIPE_STENCIL_OP_REPLACE;
- depth_stencil.stencil[0].valuemask = 0xff;
- depth_stencil.stencil[0].writemask = ctx->Stencil.WriteMask[0] & 0xff;
- stencil_ref.ref_value[0] = ctx->Stencil.Clear;
- cso_set_stencil_ref(st->cso_context, &stencil_ref);
- }
-
- cso_set_depth_stencil_alpha(st->cso_context, &depth_stencil);
- }
-
- cso_set_vertex_elements(st->cso_context, 2, st->velems_util_draw);
-
- cso_set_rasterizer(st->cso_context, &st->clear.raster);
-
- /* viewport state: viewport matching window dims */
- {
- const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
- struct pipe_viewport_state vp;
- vp.scale[0] = 0.5f * fb_width;
- vp.scale[1] = fb_height * (invert ? -0.5f : 0.5f);
- vp.scale[2] = 1.0f;
- vp.scale[3] = 1.0f;
- vp.translate[0] = 0.5f * fb_width;
- vp.translate[1] = 0.5f * fb_height;
- vp.translate[2] = 0.0f;
- vp.translate[3] = 0.0f;
- cso_set_viewport(st->cso_context, &vp);
- }
-
- cso_set_clip(st->cso_context, &st->clear.clip);
- cso_set_fragment_shader_handle(st->cso_context, st->clear.fs);
- cso_set_vertex_shader_handle(st->cso_context, st->clear.vs);
-
- if (ctx->DrawBuffer->_ColorDrawBuffers[0]) {
- st_translate_color(ctx->Color.ClearColor,
- ctx->DrawBuffer->_ColorDrawBuffers[0]->_BaseFormat,
- clearColor);
- }
-
- /* draw quad matching scissor rect */
- draw_quad(st, x0, y0, x1, y1, (GLfloat) ctx->Depth.Clear, clearColor);
-
- /* Restore pipe state */
- cso_restore_blend(st->cso_context);
- cso_restore_stencil_ref(st->cso_context);
- cso_restore_depth_stencil_alpha(st->cso_context);
- cso_restore_rasterizer(st->cso_context);
- cso_restore_viewport(st->cso_context);
- cso_restore_clip(st->cso_context);
- cso_restore_fragment_shader(st->cso_context);
- cso_restore_vertex_shader(st->cso_context);
- cso_restore_vertex_elements(st->cso_context);
- cso_restore_vertex_buffers(st->cso_context);
-}
-
-
-/**
- * Determine if we need to clear the depth buffer by drawing a quad.
- */
-static INLINE GLboolean
-check_clear_color_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb)
-{
- if (ctx->Scissor.Enabled &&
- (ctx->Scissor.X != 0 ||
- ctx->Scissor.Y != 0 ||
- ctx->Scissor.Width < rb->Width ||
- ctx->Scissor.Height < rb->Height))
- return GL_TRUE;
-
- if (!ctx->Color.ColorMask[0][0] ||
- !ctx->Color.ColorMask[0][1] ||
- !ctx->Color.ColorMask[0][2] ||
- !ctx->Color.ColorMask[0][3])
- return GL_TRUE;
-
- return GL_FALSE;
-}
-
-
-/**
- * Determine if we need to clear the combiend depth/stencil buffer by
- * drawing a quad.
- */
-static INLINE GLboolean
-check_clear_depth_stencil_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb)
-{
- const GLuint stencilMax = 0xff;
- GLboolean maskStencil
- = (ctx->Stencil.WriteMask[0] & stencilMax) != stencilMax;
-
- assert(rb->Format == MESA_FORMAT_S8 ||
- rb->Format == MESA_FORMAT_Z24_S8 ||
- rb->Format == MESA_FORMAT_S8_Z24);
-
- if (ctx->Scissor.Enabled &&
- (ctx->Scissor.X != 0 ||
- ctx->Scissor.Y != 0 ||
- ctx->Scissor.Width < rb->Width ||
- ctx->Scissor.Height < rb->Height))
- return GL_TRUE;
-
- if (maskStencil)
- return GL_TRUE;
-
- return GL_FALSE;
-}
-
-
-/**
- * Determine if we need to clear the depth buffer by drawing a quad.
- */
-static INLINE GLboolean
-check_clear_depth_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb,
- boolean ds_separate)
-{
- const struct st_renderbuffer *strb = st_renderbuffer(rb);
- const GLboolean isDS = util_format_is_depth_and_stencil(strb->surface->format);
-
- if (ctx->Scissor.Enabled &&
- (ctx->Scissor.X != 0 ||
- ctx->Scissor.Y != 0 ||
- ctx->Scissor.Width < rb->Width ||
- ctx->Scissor.Height < rb->Height))
- return GL_TRUE;
-
- if (!ds_separate && isDS && ctx->DrawBuffer->Visual.stencilBits > 0)
- return GL_TRUE;
-
- return GL_FALSE;
-}
-
-
-/**
- * Determine if we need to clear the stencil buffer by drawing a quad.
- */
-static INLINE GLboolean
-check_clear_stencil_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb,
- boolean ds_separate)
-{
- const struct st_renderbuffer *strb = st_renderbuffer(rb);
- const GLboolean isDS = util_format_is_depth_and_stencil(strb->surface->format);
- const GLuint stencilMax = 0xff;
- const GLboolean maskStencil
- = (ctx->Stencil.WriteMask[0] & stencilMax) != stencilMax;
-
- assert(rb->Format == MESA_FORMAT_S8 ||
- rb->Format == MESA_FORMAT_Z24_S8 ||
- rb->Format == MESA_FORMAT_S8_Z24);
-
- if (maskStencil)
- return GL_TRUE;
-
- if (ctx->Scissor.Enabled &&
- (ctx->Scissor.X != 0 ||
- ctx->Scissor.Y != 0 ||
- ctx->Scissor.Width < rb->Width ||
- ctx->Scissor.Height < rb->Height))
- return GL_TRUE;
-
- /* This is correct, but it is necessary to look at the depth clear
- * value held in the surface when it comes time to issue the clear,
- * rather than taking depth and stencil clear values from the
- * current state.
- */
- if (!ds_separate && isDS && ctx->DrawBuffer->Visual.depthBits > 0)
- return GL_TRUE;
-
- return GL_FALSE;
-}
-
-
-
-/**
- * Called when we need to flush.
- */
-void
-st_flush_clear(struct st_context *st)
-{
- /* Release vertex buffer to avoid synchronous rendering if we were
- * to map it in the next frame.
- */
- pipe_resource_reference(&st->clear.vbuf, NULL);
- st->clear.vbuf_slot = 0;
-}
-
-
-
-/**
- * Called via ctx->Driver.Clear()
- */
-static void
-st_Clear(struct gl_context *ctx, GLbitfield mask)
-{
- static const GLbitfield BUFFER_BITS_DS
- = (BUFFER_BIT_DEPTH | BUFFER_BIT_STENCIL);
- struct st_context *st = st_context(ctx);
- struct gl_renderbuffer *depthRb
- = ctx->DrawBuffer->Attachment[BUFFER_DEPTH].Renderbuffer;
- struct gl_renderbuffer *stencilRb
- = ctx->DrawBuffer->Attachment[BUFFER_STENCIL].Renderbuffer;
- GLbitfield quad_buffers = 0x0;
- GLbitfield clear_buffers = 0x0;
- GLuint i;
-
- /* This makes sure the pipe has the latest scissor, etc values */
- st_validate_state( st );
-
- if (mask & BUFFER_BITS_COLOR) {
- for (i = 0; i < ctx->DrawBuffer->_NumColorDrawBuffers; i++) {
- GLuint b = ctx->DrawBuffer->_ColorDrawBufferIndexes[i];
-
- if (mask & (1 << b)) {
- struct gl_renderbuffer *rb
- = ctx->DrawBuffer->Attachment[b].Renderbuffer;
- struct st_renderbuffer *strb = st_renderbuffer(rb);
-
- if (!strb || !strb->surface)
- continue;
-
- if (check_clear_color_with_quad( ctx, rb ))
- quad_buffers |= PIPE_CLEAR_COLOR;
- else
- clear_buffers |= PIPE_CLEAR_COLOR;
- }
- }
- }
-
- if ((mask & BUFFER_BITS_DS) == BUFFER_BITS_DS && depthRb == stencilRb) {
- /* clearing combined depth + stencil */
- struct st_renderbuffer *strb = st_renderbuffer(depthRb);
-
- if (strb->surface) {
- if (check_clear_depth_stencil_with_quad(ctx, depthRb))
- quad_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
- else
- clear_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
- }
- }
- else {
- /* separate depth/stencil clears */
- /* I don't think truly separate buffers are actually possible in gallium or hw? */
- if (mask & BUFFER_BIT_DEPTH) {
- struct st_renderbuffer *strb = st_renderbuffer(depthRb);
-
- if (strb->surface) {
- if (check_clear_depth_with_quad(ctx, depthRb,
- st->clear.enable_ds_separate))
- quad_buffers |= PIPE_CLEAR_DEPTH;
- else
- clear_buffers |= PIPE_CLEAR_DEPTH;
- }
- }
- if (mask & BUFFER_BIT_STENCIL) {
- struct st_renderbuffer *strb = st_renderbuffer(stencilRb);
-
- if (strb->surface) {
- if (check_clear_stencil_with_quad(ctx, stencilRb,
- st->clear.enable_ds_separate))
- quad_buffers |= PIPE_CLEAR_STENCIL;
- else
- clear_buffers |= PIPE_CLEAR_STENCIL;
- }
- }
- }
-
- /*
- * If we're going to use clear_with_quad() for any reason, use it for
- * everything possible.
- */
- if (quad_buffers) {
- quad_buffers |= clear_buffers;
- clear_with_quad(ctx,
- quad_buffers & PIPE_CLEAR_COLOR,
- quad_buffers & PIPE_CLEAR_DEPTH,
- quad_buffers & PIPE_CLEAR_STENCIL);
- } else if (clear_buffers) {
- /* driver cannot know it can clear everything if the buffer
- * is a combined depth/stencil buffer but this wasn't actually
- * required from the visual. Hence fix this up to avoid potential
- * read-modify-write in the driver.
- */
- float clearColor[4];
-
- if ((clear_buffers & PIPE_CLEAR_DEPTHSTENCIL) &&
- ((clear_buffers & PIPE_CLEAR_DEPTHSTENCIL) != PIPE_CLEAR_DEPTHSTENCIL) &&
- (depthRb == stencilRb) &&
- (ctx->DrawBuffer->Visual.depthBits == 0 ||
- ctx->DrawBuffer->Visual.stencilBits == 0))
- clear_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
-
- if (ctx->DrawBuffer->_ColorDrawBuffers[0]) {
- st_translate_color(ctx->Color.ClearColor,
- ctx->DrawBuffer->_ColorDrawBuffers[0]->_BaseFormat,
- clearColor);
- }
-
- st->pipe->clear(st->pipe, clear_buffers, ctx->Color.ClearColor,
- ctx->Depth.Clear, ctx->Stencil.Clear);
- }
- if (mask & BUFFER_BIT_ACCUM)
- st_clear_accum_buffer(ctx,
- ctx->DrawBuffer->Attachment[BUFFER_ACCUM].Renderbuffer);
-}
-
-
-void
-st_init_clear_functions(struct dd_function_table *functions)
-{
- functions->Clear = st_Clear;
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ * Copyright 2009 VMware, Inc. 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ * Brian Paul
+ * Michel Dänzer
+ */
+
+#include "main/glheader.h"
+#include "main/formats.h"
+#include "main/macros.h"
+#include "program/prog_instruction.h"
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_cb_accum.h"
+#include "st_cb_clear.h"
+#include "st_cb_fbo.h"
+#include "st_format.h"
+#include "st_program.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_shader_tokens.h"
+#include "pipe/p_state.h"
+#include "pipe/p_defines.h"
+#include "util/u_format.h"
+#include "util/u_inlines.h"
+#include "util/u_simple_shaders.h"
+#include "util/u_draw_quad.h"
+
+#include "cso_cache/cso_context.h"
+
+
+/**
+ * Do per-context initialization for glClear.
+ */
+void
+st_init_clear(struct st_context *st)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *pscreen = st->pipe->screen;
+
+ memset(&st->clear, 0, sizeof(st->clear));
+
+ st->clear.raster.gl_rasterization_rules = 1;
+ st->clear.enable_ds_separate = pscreen->get_param(pscreen, PIPE_CAP_DEPTHSTENCIL_CLEAR_SEPARATE);
+
+ /* fragment shader state: color pass-through program */
+ st->clear.fs = util_make_fragment_passthrough_shader(pipe);
+
+ /* vertex shader state: color/position pass-through */
+ {
+ const uint semantic_names[] = { TGSI_SEMANTIC_POSITION,
+ TGSI_SEMANTIC_COLOR };
+ const uint semantic_indexes[] = { 0, 0 };
+ st->clear.vs = util_make_vertex_passthrough_shader(pipe, 2,
+ semantic_names,
+ semantic_indexes);
+ }
+}
+
+
+/**
+ * Free per-context state for glClear.
+ */
+void
+st_destroy_clear(struct st_context *st)
+{
+ if (st->clear.fs) {
+ cso_delete_fragment_shader(st->cso_context, st->clear.fs);
+ st->clear.fs = NULL;
+ }
+ if (st->clear.vs) {
+ cso_delete_vertex_shader(st->cso_context, st->clear.vs);
+ st->clear.vs = NULL;
+ }
+ if (st->clear.vbuf) {
+ pipe_resource_reference(&st->clear.vbuf, NULL);
+ st->clear.vbuf = NULL;
+ }
+}
+
+
+/**
+ * Draw a screen-aligned quadrilateral.
+ * Coords are clip coords with y=0=bottom.
+ */
+static void
+draw_quad(struct st_context *st,
+ float x0, float y0, float x1, float y1, GLfloat z,
+ const GLfloat color[4])
+{
+ struct pipe_context *pipe = st->pipe;
+
+ /* XXX: Need to improve buffer_write to allow NO_WAIT (as well as
+ * no_flush) updates to buffers where we know there is no conflict
+ * with previous data. Currently using max_slots > 1 will cause
+ * synchronous rendering if the driver flushes its command buffers
+ * between one bitmap and the next. Our flush hook below isn't
+ * sufficient to catch this as the driver doesn't tell us when it
+ * flushes its own command buffers. Until this gets fixed, pay the
+ * price of allocating a new buffer for each bitmap cache-flush to
+ * avoid synchronous rendering.
+ */
+ const GLuint max_slots = 1; /* 1024 / sizeof(st->clear.vertices); */
+ GLuint i;
+
+ if (st->clear.vbuf_slot >= max_slots) {
+ pipe_resource_reference(&st->clear.vbuf, NULL);
+ st->clear.vbuf_slot = 0;
+ }
+
+ if (!st->clear.vbuf) {
+ st->clear.vbuf = pipe_buffer_create(pipe->screen,
+ PIPE_BIND_VERTEX_BUFFER,
+ PIPE_USAGE_STREAM,
+ max_slots * sizeof(st->clear.vertices));
+ }
+
+ /* positions */
+ st->clear.vertices[0][0][0] = x0;
+ st->clear.vertices[0][0][1] = y0;
+
+ st->clear.vertices[1][0][0] = x1;
+ st->clear.vertices[1][0][1] = y0;
+
+ st->clear.vertices[2][0][0] = x1;
+ st->clear.vertices[2][0][1] = y1;
+
+ st->clear.vertices[3][0][0] = x0;
+ st->clear.vertices[3][0][1] = y1;
+
+ /* same for all verts: */
+ for (i = 0; i < 4; i++) {
+ st->clear.vertices[i][0][2] = z;
+ st->clear.vertices[i][0][3] = 1.0;
+ st->clear.vertices[i][1][0] = color[0];
+ st->clear.vertices[i][1][1] = color[1];
+ st->clear.vertices[i][1][2] = color[2];
+ st->clear.vertices[i][1][3] = color[3];
+ }
+
+ /* put vertex data into vbuf */
+ pipe_buffer_write_nooverlap(st->pipe, st->clear.vbuf,
+ st->clear.vbuf_slot
+ * sizeof(st->clear.vertices),
+ sizeof(st->clear.vertices),
+ st->clear.vertices);
+
+ /* draw */
+ util_draw_vertex_buffer(pipe,
+ st->cso_context,
+ st->clear.vbuf,
+ st->clear.vbuf_slot * sizeof(st->clear.vertices),
+ PIPE_PRIM_TRIANGLE_FAN,
+ 4, /* verts */
+ 2); /* attribs/vert */
+
+ /* Increment slot */
+ st->clear.vbuf_slot++;
+}
+
+
+
+/**
+ * Do glClear by drawing a quadrilateral.
+ * The vertices of the quad will be computed from the
+ * ctx->DrawBuffer->_X/Ymin/max fields.
+ */
+static void
+clear_with_quad(struct gl_context *ctx,
+ GLboolean color, GLboolean depth, GLboolean stencil)
+{
+ struct st_context *st = st_context(ctx);
+ const struct gl_framebuffer *fb = ctx->DrawBuffer;
+ const GLfloat fb_width = (GLfloat) fb->Width;
+ const GLfloat fb_height = (GLfloat) fb->Height;
+ const GLfloat x0 = (GLfloat) ctx->DrawBuffer->_Xmin / fb_width * 2.0f - 1.0f;
+ const GLfloat x1 = (GLfloat) ctx->DrawBuffer->_Xmax / fb_width * 2.0f - 1.0f;
+ const GLfloat y0 = (GLfloat) ctx->DrawBuffer->_Ymin / fb_height * 2.0f - 1.0f;
+ const GLfloat y1 = (GLfloat) ctx->DrawBuffer->_Ymax / fb_height * 2.0f - 1.0f;
+ float clearColor[4];
+
+ /*
+ printf("%s %s%s%s %f,%f %f,%f\n", __FUNCTION__,
+ color ? "color, " : "",
+ depth ? "depth, " : "",
+ stencil ? "stencil" : "",
+ x0, y0,
+ x1, y1);
+ */
+
+ cso_save_blend(st->cso_context);
+ cso_save_stencil_ref(st->cso_context);
+ cso_save_depth_stencil_alpha(st->cso_context);
+ cso_save_rasterizer(st->cso_context);
+ cso_save_viewport(st->cso_context);
+ cso_save_clip(st->cso_context);
+ cso_save_fragment_shader(st->cso_context);
+ cso_save_vertex_shader(st->cso_context);
+ cso_save_vertex_elements(st->cso_context);
+ cso_save_vertex_buffers(st->cso_context);
+
+ /* blend state: RGBA masking */
+ {
+ struct pipe_blend_state blend;
+ memset(&blend, 0, sizeof(blend));
+ blend.rt[0].rgb_src_factor = PIPE_BLENDFACTOR_ONE;
+ blend.rt[0].alpha_src_factor = PIPE_BLENDFACTOR_ONE;
+ blend.rt[0].rgb_dst_factor = PIPE_BLENDFACTOR_ZERO;
+ blend.rt[0].alpha_dst_factor = PIPE_BLENDFACTOR_ZERO;
+ if (color) {
+ if (ctx->Color.ColorMask[0][0])
+ blend.rt[0].colormask |= PIPE_MASK_R;
+ if (ctx->Color.ColorMask[0][1])
+ blend.rt[0].colormask |= PIPE_MASK_G;
+ if (ctx->Color.ColorMask[0][2])
+ blend.rt[0].colormask |= PIPE_MASK_B;
+ if (ctx->Color.ColorMask[0][3])
+ blend.rt[0].colormask |= PIPE_MASK_A;
+ if (st->ctx->Color.DitherFlag)
+ blend.dither = 1;
+ }
+ cso_set_blend(st->cso_context, &blend);
+ }
+
+ /* depth_stencil state: always pass/set to ref value */
+ {
+ struct pipe_depth_stencil_alpha_state depth_stencil;
+ memset(&depth_stencil, 0, sizeof(depth_stencil));
+ if (depth) {
+ depth_stencil.depth.enabled = 1;
+ depth_stencil.depth.writemask = 1;
+ depth_stencil.depth.func = PIPE_FUNC_ALWAYS;
+ }
+
+ if (stencil) {
+ struct pipe_stencil_ref stencil_ref;
+ memset(&stencil_ref, 0, sizeof(stencil_ref));
+ depth_stencil.stencil[0].enabled = 1;
+ depth_stencil.stencil[0].func = PIPE_FUNC_ALWAYS;
+ depth_stencil.stencil[0].fail_op = PIPE_STENCIL_OP_REPLACE;
+ depth_stencil.stencil[0].zpass_op = PIPE_STENCIL_OP_REPLACE;
+ depth_stencil.stencil[0].zfail_op = PIPE_STENCIL_OP_REPLACE;
+ depth_stencil.stencil[0].valuemask = 0xff;
+ depth_stencil.stencil[0].writemask = ctx->Stencil.WriteMask[0] & 0xff;
+ stencil_ref.ref_value[0] = ctx->Stencil.Clear;
+ cso_set_stencil_ref(st->cso_context, &stencil_ref);
+ }
+
+ cso_set_depth_stencil_alpha(st->cso_context, &depth_stencil);
+ }
+
+ cso_set_vertex_elements(st->cso_context, 2, st->velems_util_draw);
+
+ cso_set_rasterizer(st->cso_context, &st->clear.raster);
+
+ /* viewport state: viewport matching window dims */
+ {
+ const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
+ struct pipe_viewport_state vp;
+ vp.scale[0] = 0.5f * fb_width;
+ vp.scale[1] = fb_height * (invert ? -0.5f : 0.5f);
+ vp.scale[2] = 1.0f;
+ vp.scale[3] = 1.0f;
+ vp.translate[0] = 0.5f * fb_width;
+ vp.translate[1] = 0.5f * fb_height;
+ vp.translate[2] = 0.0f;
+ vp.translate[3] = 0.0f;
+ cso_set_viewport(st->cso_context, &vp);
+ }
+
+ cso_set_clip(st->cso_context, &st->clear.clip);
+ cso_set_fragment_shader_handle(st->cso_context, st->clear.fs);
+ cso_set_vertex_shader_handle(st->cso_context, st->clear.vs);
+
+ if (ctx->DrawBuffer->_ColorDrawBuffers[0]) {
+ st_translate_color(ctx->Color.ClearColor,
+ ctx->DrawBuffer->_ColorDrawBuffers[0]->_BaseFormat,
+ clearColor);
+ }
+
+ /* draw quad matching scissor rect */
+ draw_quad(st, x0, y0, x1, y1, (GLfloat) ctx->Depth.Clear, clearColor);
+
+ /* Restore pipe state */
+ cso_restore_blend(st->cso_context);
+ cso_restore_stencil_ref(st->cso_context);
+ cso_restore_depth_stencil_alpha(st->cso_context);
+ cso_restore_rasterizer(st->cso_context);
+ cso_restore_viewport(st->cso_context);
+ cso_restore_clip(st->cso_context);
+ cso_restore_fragment_shader(st->cso_context);
+ cso_restore_vertex_shader(st->cso_context);
+ cso_restore_vertex_elements(st->cso_context);
+ cso_restore_vertex_buffers(st->cso_context);
+}
+
+
+/**
+ * Determine if we need to clear the depth buffer by drawing a quad.
+ */
+static INLINE GLboolean
+check_clear_color_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb)
+{
+ if (ctx->Scissor.Enabled &&
+ (ctx->Scissor.X != 0 ||
+ ctx->Scissor.Y != 0 ||
+ ctx->Scissor.Width < rb->Width ||
+ ctx->Scissor.Height < rb->Height))
+ return GL_TRUE;
+
+ if (!ctx->Color.ColorMask[0][0] ||
+ !ctx->Color.ColorMask[0][1] ||
+ !ctx->Color.ColorMask[0][2] ||
+ !ctx->Color.ColorMask[0][3])
+ return GL_TRUE;
+
+ return GL_FALSE;
+}
+
+
+/**
+ * Determine if we need to clear the combiend depth/stencil buffer by
+ * drawing a quad.
+ */
+static INLINE GLboolean
+check_clear_depth_stencil_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb)
+{
+ const GLuint stencilMax = 0xff;
+ GLboolean maskStencil
+ = (ctx->Stencil.WriteMask[0] & stencilMax) != stencilMax;
+
+ assert(rb->Format == MESA_FORMAT_S8 ||
+ rb->Format == MESA_FORMAT_Z24_S8 ||
+ rb->Format == MESA_FORMAT_S8_Z24);
+
+ if (ctx->Scissor.Enabled &&
+ (ctx->Scissor.X != 0 ||
+ ctx->Scissor.Y != 0 ||
+ ctx->Scissor.Width < rb->Width ||
+ ctx->Scissor.Height < rb->Height))
+ return GL_TRUE;
+
+ if (maskStencil)
+ return GL_TRUE;
+
+ return GL_FALSE;
+}
+
+
+/**
+ * Determine if we need to clear the depth buffer by drawing a quad.
+ */
+static INLINE GLboolean
+check_clear_depth_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb,
+ boolean ds_separate)
+{
+ const struct st_renderbuffer *strb = st_renderbuffer(rb);
+ const GLboolean isDS = util_format_is_depth_and_stencil(strb->surface->format);
+
+ if (ctx->Scissor.Enabled &&
+ (ctx->Scissor.X != 0 ||
+ ctx->Scissor.Y != 0 ||
+ ctx->Scissor.Width < rb->Width ||
+ ctx->Scissor.Height < rb->Height))
+ return GL_TRUE;
+
+ if (!ds_separate && isDS && ctx->DrawBuffer->Visual.stencilBits > 0)
+ return GL_TRUE;
+
+ return GL_FALSE;
+}
+
+
+/**
+ * Determine if we need to clear the stencil buffer by drawing a quad.
+ */
+static INLINE GLboolean
+check_clear_stencil_with_quad(struct gl_context *ctx, struct gl_renderbuffer *rb,
+ boolean ds_separate)
+{
+ const struct st_renderbuffer *strb = st_renderbuffer(rb);
+ const GLboolean isDS = util_format_is_depth_and_stencil(strb->surface->format);
+ const GLuint stencilMax = 0xff;
+ const GLboolean maskStencil
+ = (ctx->Stencil.WriteMask[0] & stencilMax) != stencilMax;
+
+ assert(rb->Format == MESA_FORMAT_S8 ||
+ rb->Format == MESA_FORMAT_Z24_S8 ||
+ rb->Format == MESA_FORMAT_S8_Z24);
+
+ if (maskStencil)
+ return GL_TRUE;
+
+ if (ctx->Scissor.Enabled &&
+ (ctx->Scissor.X != 0 ||
+ ctx->Scissor.Y != 0 ||
+ ctx->Scissor.Width < rb->Width ||
+ ctx->Scissor.Height < rb->Height))
+ return GL_TRUE;
+
+ /* This is correct, but it is necessary to look at the depth clear
+ * value held in the surface when it comes time to issue the clear,
+ * rather than taking depth and stencil clear values from the
+ * current state.
+ */
+ if (!ds_separate && isDS && ctx->DrawBuffer->Visual.depthBits > 0)
+ return GL_TRUE;
+
+ return GL_FALSE;
+}
+
+
+
+/**
+ * Called when we need to flush.
+ */
+void
+st_flush_clear(struct st_context *st)
+{
+ /* Release vertex buffer to avoid synchronous rendering if we were
+ * to map it in the next frame.
+ */
+ pipe_resource_reference(&st->clear.vbuf, NULL);
+ st->clear.vbuf_slot = 0;
+}
+
+
+
+/**
+ * Called via ctx->Driver.Clear()
+ */
+static void
+st_Clear(struct gl_context *ctx, GLbitfield mask)
+{
+ static const GLbitfield BUFFER_BITS_DS
+ = (BUFFER_BIT_DEPTH | BUFFER_BIT_STENCIL);
+ struct st_context *st = st_context(ctx);
+ struct gl_renderbuffer *depthRb
+ = ctx->DrawBuffer->Attachment[BUFFER_DEPTH].Renderbuffer;
+ struct gl_renderbuffer *stencilRb
+ = ctx->DrawBuffer->Attachment[BUFFER_STENCIL].Renderbuffer;
+ GLbitfield quad_buffers = 0x0;
+ GLbitfield clear_buffers = 0x0;
+ GLuint i;
+
+ /* This makes sure the pipe has the latest scissor, etc values */
+ st_validate_state( st );
+
+ if (mask & BUFFER_BITS_COLOR) {
+ for (i = 0; i < ctx->DrawBuffer->_NumColorDrawBuffers; i++) {
+ GLuint b = ctx->DrawBuffer->_ColorDrawBufferIndexes[i];
+
+ if (mask & (1 << b)) {
+ struct gl_renderbuffer *rb
+ = ctx->DrawBuffer->Attachment[b].Renderbuffer;
+ struct st_renderbuffer *strb = st_renderbuffer(rb);
+
+ if (!strb || !strb->surface)
+ continue;
+
+ if (check_clear_color_with_quad( ctx, rb ))
+ quad_buffers |= PIPE_CLEAR_COLOR;
+ else
+ clear_buffers |= PIPE_CLEAR_COLOR;
+ }
+ }
+ }
+
+ if ((mask & BUFFER_BITS_DS) == BUFFER_BITS_DS && depthRb == stencilRb) {
+ /* clearing combined depth + stencil */
+ struct st_renderbuffer *strb = st_renderbuffer(depthRb);
+
+ if (strb->surface) {
+ if (check_clear_depth_stencil_with_quad(ctx, depthRb))
+ quad_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
+ else
+ clear_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
+ }
+ }
+ else {
+ /* separate depth/stencil clears */
+ /* I don't think truly separate buffers are actually possible in gallium or hw? */
+ if (mask & BUFFER_BIT_DEPTH) {
+ struct st_renderbuffer *strb = st_renderbuffer(depthRb);
+
+ if (strb->surface) {
+ if (check_clear_depth_with_quad(ctx, depthRb,
+ st->clear.enable_ds_separate))
+ quad_buffers |= PIPE_CLEAR_DEPTH;
+ else
+ clear_buffers |= PIPE_CLEAR_DEPTH;
+ }
+ }
+ if (mask & BUFFER_BIT_STENCIL) {
+ struct st_renderbuffer *strb = st_renderbuffer(stencilRb);
+
+ if (strb->surface) {
+ if (check_clear_stencil_with_quad(ctx, stencilRb,
+ st->clear.enable_ds_separate))
+ quad_buffers |= PIPE_CLEAR_STENCIL;
+ else
+ clear_buffers |= PIPE_CLEAR_STENCIL;
+ }
+ }
+ }
+
+ /*
+ * If we're going to use clear_with_quad() for any reason, use it for
+ * everything possible.
+ */
+ if (quad_buffers) {
+ quad_buffers |= clear_buffers;
+ clear_with_quad(ctx,
+ quad_buffers & PIPE_CLEAR_COLOR,
+ quad_buffers & PIPE_CLEAR_DEPTH,
+ quad_buffers & PIPE_CLEAR_STENCIL);
+ } else if (clear_buffers) {
+ /* driver cannot know it can clear everything if the buffer
+ * is a combined depth/stencil buffer but this wasn't actually
+ * required from the visual. Hence fix this up to avoid potential
+ * read-modify-write in the driver.
+ */
+ float clearColor[4];
+
+ if ((clear_buffers & PIPE_CLEAR_DEPTHSTENCIL) &&
+ ((clear_buffers & PIPE_CLEAR_DEPTHSTENCIL) != PIPE_CLEAR_DEPTHSTENCIL) &&
+ (depthRb == stencilRb) &&
+ (ctx->DrawBuffer->Visual.depthBits == 0 ||
+ ctx->DrawBuffer->Visual.stencilBits == 0))
+ clear_buffers |= PIPE_CLEAR_DEPTHSTENCIL;
+
+ if (ctx->DrawBuffer->_ColorDrawBuffers[0]) {
+ st_translate_color(ctx->Color.ClearColor,
+ ctx->DrawBuffer->_ColorDrawBuffers[0]->_BaseFormat,
+ clearColor);
+ }
+
+ st->pipe->clear(st->pipe, clear_buffers, ctx->Color.ClearColor,
+ ctx->Depth.Clear, ctx->Stencil.Clear);
+ }
+ if (mask & BUFFER_BIT_ACCUM)
+ st_clear_accum_buffer(ctx,
+ ctx->DrawBuffer->Attachment[BUFFER_ACCUM].Renderbuffer);
+}
+
+
+void
+st_init_clear_functions(struct dd_function_table *functions)
+{
+ functions->Clear = st_Clear;
+}
diff --git a/mesalib/src/mesa/state_tracker/st_cb_drawtex.c b/mesalib/src/mesa/state_tracker/st_cb_drawtex.c
index 86ceb9d78..db299eb8d 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_drawtex.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_drawtex.c
@@ -1,307 +1,307 @@
-/**************************************************************************
- *
- * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
- * All Rights Reserved.
- *
- **************************************************************************/
-
-
-/**
- * Implementation of glDrawTex() for GL_OES_draw_tex
- */
-
-
-
-#include "main/imports.h"
-#include "main/image.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-#include "program/program.h"
-#include "program/prog_print.h"
-
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_cb_drawtex.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-#include "pipe/p_shader_tokens.h"
-#include "util/u_draw_quad.h"
-#include "util/u_simple_shaders.h"
-
-#include "cso_cache/cso_context.h"
-
-
-#if FEATURE_OES_draw_texture
-
-
-struct cached_shader
-{
- void *handle;
-
- uint num_attribs;
- uint semantic_names[2 + MAX_TEXTURE_UNITS];
- uint semantic_indexes[2 + MAX_TEXTURE_UNITS];
-};
-
-#define MAX_SHADERS (2 * MAX_TEXTURE_UNITS)
-
-/**
- * Simple linear list cache.
- * Most of the time there'll only be one cached shader.
- */
-static struct cached_shader CachedShaders[MAX_SHADERS];
-static GLuint NumCachedShaders = 0;
-
-
-static void *
-lookup_shader(struct pipe_context *pipe,
- uint num_attribs,
- const uint *semantic_names,
- const uint *semantic_indexes)
-{
- GLuint i, j;
-
- /* look for existing shader with same attributes */
- for (i = 0; i < NumCachedShaders; i++) {
- if (CachedShaders[i].num_attribs == num_attribs) {
- GLboolean match = GL_TRUE;
- for (j = 0; j < num_attribs; j++) {
- if (semantic_names[j] != CachedShaders[i].semantic_names[j] ||
- semantic_indexes[j] != CachedShaders[i].semantic_indexes[j]) {
- match = GL_FALSE;
- break;
- }
- }
- if (match)
- return CachedShaders[i].handle;
- }
- }
-
- /* not found - create new one now */
- if (NumCachedShaders >= MAX_SHADERS) {
- return NULL;
- }
-
- CachedShaders[i].num_attribs = num_attribs;
- for (j = 0; j < num_attribs; j++) {
- CachedShaders[i].semantic_names[j] = semantic_names[j];
- CachedShaders[i].semantic_indexes[j] = semantic_indexes[j];
- }
-
- CachedShaders[i].handle =
- util_make_vertex_passthrough_shader(pipe,
- num_attribs,
- semantic_names,
- semantic_indexes);
- NumCachedShaders++;
-
- return CachedShaders[i].handle;
-}
-
-static void
-st_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
- GLfloat width, GLfloat height)
-{
- struct st_context *st = ctx->st;
- struct pipe_context *pipe = st->pipe;
- struct cso_context *cso = ctx->st->cso_context;
- struct pipe_resource *vbuffer;
- struct pipe_transfer *vbuffer_transfer;
- GLuint i, numTexCoords, numAttribs;
- GLboolean emitColor;
- uint semantic_names[2 + MAX_TEXTURE_UNITS];
- uint semantic_indexes[2 + MAX_TEXTURE_UNITS];
- struct pipe_vertex_element velements[2 + MAX_TEXTURE_UNITS];
- GLbitfield inputs = VERT_BIT_POS;
-
- st_validate_state(st);
-
- /* determine if we need vertex color */
- if (ctx->FragmentProgram._Current->Base.InputsRead & FRAG_BIT_COL0)
- emitColor = GL_TRUE;
- else
- emitColor = GL_FALSE;
-
- /* determine how many enabled sets of texcoords */
- numTexCoords = 0;
- for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
- if (ctx->Texture.Unit[i]._ReallyEnabled & TEXTURE_2D_BIT) {
- inputs |= VERT_BIT_TEX(i);
- numTexCoords++;
- }
- }
-
- /* total number of attributes per vertex */
- numAttribs = 1 + emitColor + numTexCoords;
-
-
- /* create the vertex buffer */
- vbuffer = pipe_buffer_create(pipe->screen, PIPE_BIND_VERTEX_BUFFER,
- PIPE_USAGE_STREAM,
- numAttribs * 4 * 4 * sizeof(GLfloat));
-
- /* load vertex buffer */
- {
-#define SET_ATTRIB(VERT, ATTR, X, Y, Z, W) \
- do { \
- GLuint k = (((VERT) * numAttribs + (ATTR)) * 4); \
- assert(k < 4 * 4 * numAttribs); \
- vbuf[k + 0] = X; \
- vbuf[k + 1] = Y; \
- vbuf[k + 2] = Z; \
- vbuf[k + 3] = W; \
- } while (0)
-
- const GLfloat x0 = x, y0 = y, x1 = x + width, y1 = y + height;
- GLfloat *vbuf = (GLfloat *) pipe_buffer_map(pipe, vbuffer,
- PIPE_TRANSFER_WRITE,
- &vbuffer_transfer);
- GLuint attr;
-
- z = CLAMP(z, 0.0f, 1.0f);
-
- /* positions (in clip coords) */
- {
- const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
- const GLfloat fb_width = (GLfloat)fb->Width;
- const GLfloat fb_height = (GLfloat)fb->Height;
-
- const GLfloat clip_x0 = (GLfloat)(x0 / fb_width * 2.0 - 1.0);
- const GLfloat clip_y0 = (GLfloat)(y0 / fb_height * 2.0 - 1.0);
- const GLfloat clip_x1 = (GLfloat)(x1 / fb_width * 2.0 - 1.0);
- const GLfloat clip_y1 = (GLfloat)(y1 / fb_height * 2.0 - 1.0);
-
- SET_ATTRIB(0, 0, clip_x0, clip_y0, z, 1.0f); /* lower left */
- SET_ATTRIB(1, 0, clip_x1, clip_y0, z, 1.0f); /* lower right */
- SET_ATTRIB(2, 0, clip_x1, clip_y1, z, 1.0f); /* upper right */
- SET_ATTRIB(3, 0, clip_x0, clip_y1, z, 1.0f); /* upper left */
-
- semantic_names[0] = TGSI_SEMANTIC_POSITION;
- semantic_indexes[0] = 0;
- }
-
- /* colors */
- if (emitColor) {
- const GLfloat *c = ctx->Current.Attrib[VERT_ATTRIB_COLOR0];
- SET_ATTRIB(0, 1, c[0], c[1], c[2], c[3]);
- SET_ATTRIB(1, 1, c[0], c[1], c[2], c[3]);
- SET_ATTRIB(2, 1, c[0], c[1], c[2], c[3]);
- SET_ATTRIB(3, 1, c[0], c[1], c[2], c[3]);
- semantic_names[1] = TGSI_SEMANTIC_COLOR;
- semantic_indexes[1] = 0;
- attr = 2;
- }
- else {
- attr = 1;
- }
-
- /* texcoords */
- for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
- if (ctx->Texture.Unit[i]._ReallyEnabled & TEXTURE_2D_BIT) {
- struct gl_texture_object *obj = ctx->Texture.Unit[i]._Current;
- struct gl_texture_image *img = obj->Image[0][obj->BaseLevel];
- const GLfloat wt = (GLfloat) img->Width;
- const GLfloat ht = (GLfloat) img->Height;
- const GLfloat s0 = obj->CropRect[0] / wt;
- const GLfloat t0 = obj->CropRect[1] / ht;
- const GLfloat s1 = (obj->CropRect[0] + obj->CropRect[2]) / wt;
- const GLfloat t1 = (obj->CropRect[1] + obj->CropRect[3]) / ht;
-
- /*printf("crop texcoords: %g, %g .. %g, %g\n", s0, t0, s1, t1);*/
- SET_ATTRIB(0, attr, s0, t0, 0.0f, 1.0f); /* lower left */
- SET_ATTRIB(1, attr, s1, t0, 0.0f, 1.0f); /* lower right */
- SET_ATTRIB(2, attr, s1, t1, 0.0f, 1.0f); /* upper right */
- SET_ATTRIB(3, attr, s0, t1, 0.0f, 1.0f); /* upper left */
-
- semantic_names[attr] = TGSI_SEMANTIC_GENERIC;
- semantic_indexes[attr] = 0;
-
- attr++;
- }
- }
-
- pipe_buffer_unmap(pipe, vbuffer_transfer);
-
-#undef SET_ATTRIB
- }
-
-
- cso_save_viewport(cso);
- cso_save_vertex_shader(cso);
- cso_save_vertex_elements(cso);
- cso_save_vertex_buffers(cso);
-
- {
- void *vs = lookup_shader(pipe, numAttribs,
- semantic_names, semantic_indexes);
- cso_set_vertex_shader_handle(cso, vs);
- }
-
- for (i = 0; i < numAttribs; i++) {
- velements[i].src_offset = i * 4 * sizeof(float);
- velements[i].instance_divisor = 0;
- velements[i].vertex_buffer_index = 0;
- velements[i].src_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
- }
- cso_set_vertex_elements(cso, numAttribs, velements);
-
- /* viewport state: viewport matching window dims */
- {
- const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
- const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
- const GLfloat width = (GLfloat)fb->Width;
- const GLfloat height = (GLfloat)fb->Height;
- struct pipe_viewport_state vp;
- vp.scale[0] = 0.5f * width;
- vp.scale[1] = height * (invert ? -0.5f : 0.5f);
- vp.scale[2] = 1.0f;
- vp.scale[3] = 1.0f;
- vp.translate[0] = 0.5f * width;
- vp.translate[1] = 0.5f * height;
- vp.translate[2] = 0.0f;
- vp.translate[3] = 0.0f;
- cso_set_viewport(cso, &vp);
- }
-
-
- util_draw_vertex_buffer(pipe, cso, vbuffer,
- 0, /* offset */
- PIPE_PRIM_TRIANGLE_FAN,
- 4, /* verts */
- numAttribs); /* attribs/vert */
-
-
- pipe_resource_reference(&vbuffer, NULL);
-
- /* restore state */
- cso_restore_viewport(cso);
- cso_restore_vertex_shader(cso);
- cso_restore_vertex_elements(cso);
- cso_restore_vertex_buffers(cso);
-}
-
-
-void
-st_init_drawtex_functions(struct dd_function_table *functions)
-{
- functions->DrawTex = st_DrawTex;
-}
-
-
-/**
- * Free any cached shaders
- */
-void
-st_destroy_drawtex(struct st_context *st)
-{
- GLuint i;
- for (i = 0; i < NumCachedShaders; i++) {
- cso_delete_vertex_shader(st->cso_context, CachedShaders[i].handle);
- }
- NumCachedShaders = 0;
-}
-
-
-#endif /* FEATURE_OES_draw_texture */
+/**************************************************************************
+ *
+ * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * All Rights Reserved.
+ *
+ **************************************************************************/
+
+
+/**
+ * Implementation of glDrawTex() for GL_OES_draw_tex
+ */
+
+
+
+#include "main/imports.h"
+#include "main/image.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+#include "program/program.h"
+#include "program/prog_print.h"
+
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_cb_drawtex.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+#include "pipe/p_shader_tokens.h"
+#include "util/u_draw_quad.h"
+#include "util/u_simple_shaders.h"
+
+#include "cso_cache/cso_context.h"
+
+
+#if FEATURE_OES_draw_texture
+
+
+struct cached_shader
+{
+ void *handle;
+
+ uint num_attribs;
+ uint semantic_names[2 + MAX_TEXTURE_UNITS];
+ uint semantic_indexes[2 + MAX_TEXTURE_UNITS];
+};
+
+#define MAX_SHADERS (2 * MAX_TEXTURE_UNITS)
+
+/**
+ * Simple linear list cache.
+ * Most of the time there'll only be one cached shader.
+ */
+static struct cached_shader CachedShaders[MAX_SHADERS];
+static GLuint NumCachedShaders = 0;
+
+
+static void *
+lookup_shader(struct pipe_context *pipe,
+ uint num_attribs,
+ const uint *semantic_names,
+ const uint *semantic_indexes)
+{
+ GLuint i, j;
+
+ /* look for existing shader with same attributes */
+ for (i = 0; i < NumCachedShaders; i++) {
+ if (CachedShaders[i].num_attribs == num_attribs) {
+ GLboolean match = GL_TRUE;
+ for (j = 0; j < num_attribs; j++) {
+ if (semantic_names[j] != CachedShaders[i].semantic_names[j] ||
+ semantic_indexes[j] != CachedShaders[i].semantic_indexes[j]) {
+ match = GL_FALSE;
+ break;
+ }
+ }
+ if (match)
+ return CachedShaders[i].handle;
+ }
+ }
+
+ /* not found - create new one now */
+ if (NumCachedShaders >= MAX_SHADERS) {
+ return NULL;
+ }
+
+ CachedShaders[i].num_attribs = num_attribs;
+ for (j = 0; j < num_attribs; j++) {
+ CachedShaders[i].semantic_names[j] = semantic_names[j];
+ CachedShaders[i].semantic_indexes[j] = semantic_indexes[j];
+ }
+
+ CachedShaders[i].handle =
+ util_make_vertex_passthrough_shader(pipe,
+ num_attribs,
+ semantic_names,
+ semantic_indexes);
+ NumCachedShaders++;
+
+ return CachedShaders[i].handle;
+}
+
+static void
+st_DrawTex(struct gl_context *ctx, GLfloat x, GLfloat y, GLfloat z,
+ GLfloat width, GLfloat height)
+{
+ struct st_context *st = ctx->st;
+ struct pipe_context *pipe = st->pipe;
+ struct cso_context *cso = ctx->st->cso_context;
+ struct pipe_resource *vbuffer;
+ struct pipe_transfer *vbuffer_transfer;
+ GLuint i, numTexCoords, numAttribs;
+ GLboolean emitColor;
+ uint semantic_names[2 + MAX_TEXTURE_UNITS];
+ uint semantic_indexes[2 + MAX_TEXTURE_UNITS];
+ struct pipe_vertex_element velements[2 + MAX_TEXTURE_UNITS];
+ GLbitfield inputs = VERT_BIT_POS;
+
+ st_validate_state(st);
+
+ /* determine if we need vertex color */
+ if (ctx->FragmentProgram._Current->Base.InputsRead & FRAG_BIT_COL0)
+ emitColor = GL_TRUE;
+ else
+ emitColor = GL_FALSE;
+
+ /* determine how many enabled sets of texcoords */
+ numTexCoords = 0;
+ for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
+ if (ctx->Texture.Unit[i]._ReallyEnabled & TEXTURE_2D_BIT) {
+ inputs |= VERT_BIT_TEX(i);
+ numTexCoords++;
+ }
+ }
+
+ /* total number of attributes per vertex */
+ numAttribs = 1 + emitColor + numTexCoords;
+
+
+ /* create the vertex buffer */
+ vbuffer = pipe_buffer_create(pipe->screen, PIPE_BIND_VERTEX_BUFFER,
+ PIPE_USAGE_STREAM,
+ numAttribs * 4 * 4 * sizeof(GLfloat));
+
+ /* load vertex buffer */
+ {
+#define SET_ATTRIB(VERT, ATTR, X, Y, Z, W) \
+ do { \
+ GLuint k = (((VERT) * numAttribs + (ATTR)) * 4); \
+ assert(k < 4 * 4 * numAttribs); \
+ vbuf[k + 0] = X; \
+ vbuf[k + 1] = Y; \
+ vbuf[k + 2] = Z; \
+ vbuf[k + 3] = W; \
+ } while (0)
+
+ const GLfloat x0 = x, y0 = y, x1 = x + width, y1 = y + height;
+ GLfloat *vbuf = (GLfloat *) pipe_buffer_map(pipe, vbuffer,
+ PIPE_TRANSFER_WRITE,
+ &vbuffer_transfer);
+ GLuint attr;
+
+ z = CLAMP(z, 0.0f, 1.0f);
+
+ /* positions (in clip coords) */
+ {
+ const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
+ const GLfloat fb_width = (GLfloat)fb->Width;
+ const GLfloat fb_height = (GLfloat)fb->Height;
+
+ const GLfloat clip_x0 = (GLfloat)(x0 / fb_width * 2.0 - 1.0);
+ const GLfloat clip_y0 = (GLfloat)(y0 / fb_height * 2.0 - 1.0);
+ const GLfloat clip_x1 = (GLfloat)(x1 / fb_width * 2.0 - 1.0);
+ const GLfloat clip_y1 = (GLfloat)(y1 / fb_height * 2.0 - 1.0);
+
+ SET_ATTRIB(0, 0, clip_x0, clip_y0, z, 1.0f); /* lower left */
+ SET_ATTRIB(1, 0, clip_x1, clip_y0, z, 1.0f); /* lower right */
+ SET_ATTRIB(2, 0, clip_x1, clip_y1, z, 1.0f); /* upper right */
+ SET_ATTRIB(3, 0, clip_x0, clip_y1, z, 1.0f); /* upper left */
+
+ semantic_names[0] = TGSI_SEMANTIC_POSITION;
+ semantic_indexes[0] = 0;
+ }
+
+ /* colors */
+ if (emitColor) {
+ const GLfloat *c = ctx->Current.Attrib[VERT_ATTRIB_COLOR0];
+ SET_ATTRIB(0, 1, c[0], c[1], c[2], c[3]);
+ SET_ATTRIB(1, 1, c[0], c[1], c[2], c[3]);
+ SET_ATTRIB(2, 1, c[0], c[1], c[2], c[3]);
+ SET_ATTRIB(3, 1, c[0], c[1], c[2], c[3]);
+ semantic_names[1] = TGSI_SEMANTIC_COLOR;
+ semantic_indexes[1] = 0;
+ attr = 2;
+ }
+ else {
+ attr = 1;
+ }
+
+ /* texcoords */
+ for (i = 0; i < ctx->Const.MaxTextureUnits; i++) {
+ if (ctx->Texture.Unit[i]._ReallyEnabled & TEXTURE_2D_BIT) {
+ struct gl_texture_object *obj = ctx->Texture.Unit[i]._Current;
+ struct gl_texture_image *img = obj->Image[0][obj->BaseLevel];
+ const GLfloat wt = (GLfloat) img->Width;
+ const GLfloat ht = (GLfloat) img->Height;
+ const GLfloat s0 = obj->CropRect[0] / wt;
+ const GLfloat t0 = obj->CropRect[1] / ht;
+ const GLfloat s1 = (obj->CropRect[0] + obj->CropRect[2]) / wt;
+ const GLfloat t1 = (obj->CropRect[1] + obj->CropRect[3]) / ht;
+
+ /*printf("crop texcoords: %g, %g .. %g, %g\n", s0, t0, s1, t1);*/
+ SET_ATTRIB(0, attr, s0, t0, 0.0f, 1.0f); /* lower left */
+ SET_ATTRIB(1, attr, s1, t0, 0.0f, 1.0f); /* lower right */
+ SET_ATTRIB(2, attr, s1, t1, 0.0f, 1.0f); /* upper right */
+ SET_ATTRIB(3, attr, s0, t1, 0.0f, 1.0f); /* upper left */
+
+ semantic_names[attr] = TGSI_SEMANTIC_GENERIC;
+ semantic_indexes[attr] = 0;
+
+ attr++;
+ }
+ }
+
+ pipe_buffer_unmap(pipe, vbuffer_transfer);
+
+#undef SET_ATTRIB
+ }
+
+
+ cso_save_viewport(cso);
+ cso_save_vertex_shader(cso);
+ cso_save_vertex_elements(cso);
+ cso_save_vertex_buffers(cso);
+
+ {
+ void *vs = lookup_shader(pipe, numAttribs,
+ semantic_names, semantic_indexes);
+ cso_set_vertex_shader_handle(cso, vs);
+ }
+
+ for (i = 0; i < numAttribs; i++) {
+ velements[i].src_offset = i * 4 * sizeof(float);
+ velements[i].instance_divisor = 0;
+ velements[i].vertex_buffer_index = 0;
+ velements[i].src_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
+ }
+ cso_set_vertex_elements(cso, numAttribs, velements);
+
+ /* viewport state: viewport matching window dims */
+ {
+ const struct gl_framebuffer *fb = st->ctx->DrawBuffer;
+ const GLboolean invert = (st_fb_orientation(fb) == Y_0_TOP);
+ const GLfloat width = (GLfloat)fb->Width;
+ const GLfloat height = (GLfloat)fb->Height;
+ struct pipe_viewport_state vp;
+ vp.scale[0] = 0.5f * width;
+ vp.scale[1] = height * (invert ? -0.5f : 0.5f);
+ vp.scale[2] = 1.0f;
+ vp.scale[3] = 1.0f;
+ vp.translate[0] = 0.5f * width;
+ vp.translate[1] = 0.5f * height;
+ vp.translate[2] = 0.0f;
+ vp.translate[3] = 0.0f;
+ cso_set_viewport(cso, &vp);
+ }
+
+
+ util_draw_vertex_buffer(pipe, cso, vbuffer,
+ 0, /* offset */
+ PIPE_PRIM_TRIANGLE_FAN,
+ 4, /* verts */
+ numAttribs); /* attribs/vert */
+
+
+ pipe_resource_reference(&vbuffer, NULL);
+
+ /* restore state */
+ cso_restore_viewport(cso);
+ cso_restore_vertex_shader(cso);
+ cso_restore_vertex_elements(cso);
+ cso_restore_vertex_buffers(cso);
+}
+
+
+void
+st_init_drawtex_functions(struct dd_function_table *functions)
+{
+ functions->DrawTex = st_DrawTex;
+}
+
+
+/**
+ * Free any cached shaders
+ */
+void
+st_destroy_drawtex(struct st_context *st)
+{
+ GLuint i;
+ for (i = 0; i < NumCachedShaders; i++) {
+ cso_delete_vertex_shader(st->cso_context, CachedShaders[i].handle);
+ }
+ NumCachedShaders = 0;
+}
+
+
+#endif /* FEATURE_OES_draw_texture */
diff --git a/mesalib/src/mesa/state_tracker/st_cb_texture.c b/mesalib/src/mesa/state_tracker/st_cb_texture.c
index a40a79bb8..708aa1290 100644
--- a/mesalib/src/mesa/state_tracker/st_cb_texture.c
+++ b/mesalib/src/mesa/state_tracker/st_cb_texture.c
@@ -1,1918 +1,1918 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-#include "main/mfeatures.h"
-#include "main/bufferobj.h"
-#include "main/enums.h"
-#include "main/fbobject.h"
-#include "main/formats.h"
-#include "main/image.h"
-#include "main/imports.h"
-#include "main/macros.h"
-#include "main/mipmap.h"
-#include "main/pack.h"
-#include "main/pixeltransfer.h"
-#include "main/texcompress.h"
-#include "main/texfetch.h"
-#include "main/texgetimage.h"
-#include "main/teximage.h"
-#include "main/texobj.h"
-#include "main/texstore.h"
-
-#include "state_tracker/st_debug.h"
-#include "state_tracker/st_context.h"
-#include "state_tracker/st_cb_fbo.h"
-#include "state_tracker/st_cb_flush.h"
-#include "state_tracker/st_cb_texture.h"
-#include "state_tracker/st_format.h"
-#include "state_tracker/st_texture.h"
-#include "state_tracker/st_gen_mipmap.h"
-#include "state_tracker/st_atom.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-#include "pipe/p_shader_tokens.h"
-#include "util/u_tile.h"
-#include "util/u_blit.h"
-#include "util/u_format.h"
-#include "util/u_surface.h"
-#include "util/u_sampler.h"
-#include "util/u_math.h"
-#include "util/u_box.h"
-
-#define DBG if (0) printf
-
-
-static enum pipe_texture_target
-gl_target_to_pipe(GLenum target)
-{
- switch (target) {
- case GL_TEXTURE_1D:
- return PIPE_TEXTURE_1D;
- case GL_TEXTURE_2D:
- return PIPE_TEXTURE_2D;
- case GL_TEXTURE_RECTANGLE_NV:
- return PIPE_TEXTURE_RECT;
- case GL_TEXTURE_3D:
- return PIPE_TEXTURE_3D;
- case GL_TEXTURE_CUBE_MAP_ARB:
- return PIPE_TEXTURE_CUBE;
- case GL_TEXTURE_1D_ARRAY_EXT:
- return PIPE_TEXTURE_1D_ARRAY;
- case GL_TEXTURE_2D_ARRAY_EXT:
- return PIPE_TEXTURE_2D_ARRAY;
- default:
- assert(0);
- return 0;
- }
-}
-
-
-/** called via ctx->Driver.NewTextureImage() */
-static struct gl_texture_image *
-st_NewTextureImage(struct gl_context * ctx)
-{
- DBG("%s\n", __FUNCTION__);
- (void) ctx;
- return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
-}
-
-
-/** called via ctx->Driver.NewTextureObject() */
-static struct gl_texture_object *
-st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
-{
- struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
-
- DBG("%s\n", __FUNCTION__);
- _mesa_initialize_texture_object(&obj->base, name, target);
-
- return &obj->base;
-}
-
-/** called via ctx->Driver.DeleteTextureObject() */
-static void
-st_DeleteTextureObject(struct gl_context *ctx,
- struct gl_texture_object *texObj)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(texObj);
- if (stObj->pt)
- pipe_resource_reference(&stObj->pt, NULL);
- if (stObj->sampler_view) {
- if (stObj->sampler_view->context != st->pipe) {
- /* Take "ownership" of this texture sampler view by setting
- * its context pointer to this context. This avoids potential
- * crashes when the texture object is shared among contexts
- * and the original/owner context has already been destroyed.
- */
- stObj->sampler_view->context = st->pipe;
- }
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
- _mesa_delete_texture_object(ctx, texObj);
-}
-
-
-/** called via ctx->Driver.FreeTexImageData() */
-static void
-st_FreeTextureImageData(struct gl_context * ctx, struct gl_texture_image *texImage)
-{
- struct st_texture_image *stImage = st_texture_image(texImage);
-
- DBG("%s\n", __FUNCTION__);
-
- if (stImage->pt) {
- pipe_resource_reference(&stImage->pt, NULL);
- }
-
- if (texImage->Data) {
- _mesa_align_free(texImage->Data);
- texImage->Data = NULL;
- }
-}
-
-
-/**
- * From linux kernel i386 header files, copes with odd sizes better
- * than COPY_DWORDS would:
- * XXX Put this in src/mesa/main/imports.h ???
- */
-#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
-static INLINE void *
-__memcpy(void *to, const void *from, size_t n)
-{
- int d0, d1, d2;
- __asm__ __volatile__("rep ; movsl\n\t"
- "testb $2,%b4\n\t"
- "je 1f\n\t"
- "movsw\n"
- "1:\ttestb $1,%b4\n\t"
- "je 2f\n\t"
- "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
- :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
- :"memory");
- return (to);
-}
-#else
-#define __memcpy(a,b,c) memcpy(a,b,c)
-#endif
-
-
-/**
- * The system memcpy (at least on ubuntu 5.10) has problems copying
- * to agp (writecombined) memory from a source which isn't 64-byte
- * aligned - there is a 4x performance falloff.
- *
- * The x86 __memcpy is immune to this but is slightly slower
- * (10%-ish) than the system memcpy.
- *
- * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
- * isn't much faster than x86_memcpy for agp copies.
- *
- * TODO: switch dynamically.
- */
-static void *
-do_memcpy(void *dest, const void *src, size_t n)
-{
- if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
- return __memcpy(dest, src, n);
- }
- else
- return memcpy(dest, src, n);
-}
-
-
-/**
- * Return default texture resource binding bitmask for the given format.
- */
-static GLuint
-default_bindings(struct st_context *st, enum pipe_format format)
-{
- struct pipe_screen *screen = st->pipe->screen;
- const unsigned target = PIPE_TEXTURE_2D;
- const unsigned geom = 0x0;
- unsigned bindings;
-
- if (util_format_is_depth_or_stencil(format))
- bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
- else
- bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
-
- if (screen->is_format_supported(screen, format, target, 0, bindings, geom))
- return bindings;
- else
- return PIPE_BIND_SAMPLER_VIEW;
-}
-
-
-/** Return number of image dimensions (1, 2 or 3) for a texture target. */
-static GLuint
-get_texture_dims(GLenum target)
-{
- switch (target) {
- case GL_TEXTURE_1D:
- case GL_TEXTURE_1D_ARRAY_EXT:
- return 1;
- case GL_TEXTURE_2D:
- case GL_TEXTURE_CUBE_MAP_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB:
- case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB:
- case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB:
- case GL_TEXTURE_RECTANGLE_NV:
- case GL_TEXTURE_2D_ARRAY_EXT:
- return 2;
- case GL_TEXTURE_3D:
- return 3;
- default:
- assert(0 && "invalid texture target in get_texture_dims()");
- return 1;
- }
-}
-
-
-/**
- * Given the size of a mipmap image, try to compute the size of the level=0
- * mipmap image.
- *
- * Note that this isn't always accurate for odd-sized, non-POW textures.
- * For example, if level=1 and width=40 then the level=0 width may be 80 or 81.
- *
- * \return GL_TRUE for success, GL_FALSE for failure
- */
-static GLboolean
-guess_base_level_size(GLenum target,
- GLuint width, GLuint height, GLuint depth, GLuint level,
- GLuint *width0, GLuint *height0, GLuint *depth0)
-{
- const GLuint dims = get_texture_dims(target);
-
- assert(width >= 1);
- assert(height >= 1);
- assert(depth >= 1);
-
- if (level > 0) {
- /* Depending on the image's size, we can't always make a guess here */
- if ((dims >= 1 && width == 1) ||
- (dims >= 2 && height == 1) ||
- (dims >= 3 && depth == 1)) {
- /* we can't determine the image size at level=0 */
- return GL_FALSE;
- }
-
- /* grow the image size until we hit level = 0 */
- while (level > 0) {
- if (width > 1)
- width <<= 1;
- if (height > 1)
- height <<= 1;
- if (depth > 1)
- depth <<= 1;
- level--;
- }
- }
-
- *width0 = width;
- *height0 = height;
- *depth0 = depth;
-
- return GL_TRUE;
-}
-
-
-/**
- * Try to allocate a pipe_resource object for the given st_texture_object.
- *
- * We use the given st_texture_image as a clue to determine the size of the
- * mipmap image at level=0.
- *
- * \return GL_TRUE for success, GL_FALSE if out of memory.
- */
-static GLboolean
-guess_and_alloc_texture(struct st_context *st,
- struct st_texture_object *stObj,
- const struct st_texture_image *stImage)
-{
- GLuint lastLevel, width, height, depth;
- GLuint bindings;
- GLuint ptWidth, ptHeight, ptDepth, ptLayers;
- enum pipe_format fmt;
-
- DBG("%s\n", __FUNCTION__);
-
- assert(!stObj->pt);
-
- if (!guess_base_level_size(stObj->base.Target,
- stImage->base.Width2,
- stImage->base.Height2,
- stImage->base.Depth2,
- stImage->level,
- &width, &height, &depth)) {
- /* we can't determine the image size at level=0 */
- stObj->width0 = stObj->height0 = stObj->depth0 = 0;
- /* this is not an out of memory error */
- return GL_TRUE;
- }
-
- /* At this point, (width x height x depth) is the expected size of
- * the level=0 mipmap image.
- */
-
- /* Guess a reasonable value for lastLevel. With OpenGL we have no
- * idea how many mipmap levels will be in a texture until we start
- * to render with it. Make an educated guess here but be prepared
- * to re-allocating a texture buffer with space for more (or fewer)
- * mipmap levels later.
- */
- if ((stObj->base.MinFilter == GL_NEAREST ||
- stObj->base.MinFilter == GL_LINEAR ||
- stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
- stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
- !stObj->base.GenerateMipmap &&
- stImage->level == 0) {
- /* only alloc space for a single mipmap level */
- lastLevel = 0;
- }
- else {
- /* alloc space for a full mipmap */
- GLuint l2width = util_logbase2(width);
- GLuint l2height = util_logbase2(height);
- GLuint l2depth = util_logbase2(depth);
- lastLevel = MAX2(MAX2(l2width, l2height), l2depth);
- }
-
- /* Save the level=0 dimensions */
- stObj->width0 = width;
- stObj->height0 = height;
- stObj->depth0 = depth;
-
- fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
-
- bindings = default_bindings(st, fmt);
-
- st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
- width, height, depth,
- &ptWidth, &ptHeight, &ptDepth, &ptLayers);
-
- stObj->pt = st_texture_create(st,
- gl_target_to_pipe(stObj->base.Target),
- fmt,
- lastLevel,
- ptWidth,
- ptHeight,
- ptDepth,
- ptLayers,
- bindings);
-
- DBG("%s returning %d\n", __FUNCTION__, (stObj->pt != NULL));
-
- return stObj->pt != NULL;
-}
-
-
-/**
- * Adjust pixel unpack params and image dimensions to strip off the
- * texture border.
- * Gallium doesn't support texture borders. They've seldem been used
- * and seldom been implemented correctly anyway.
- * \param unpackNew returns the new pixel unpack parameters
- */
-static void
-strip_texture_border(GLint border,
- GLint *width, GLint *height, GLint *depth,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_pixelstore_attrib *unpackNew)
-{
- assert(border > 0); /* sanity check */
-
- *unpackNew = *unpack;
-
- if (unpackNew->RowLength == 0)
- unpackNew->RowLength = *width;
-
- if (depth && unpackNew->ImageHeight == 0)
- unpackNew->ImageHeight = *height;
-
- unpackNew->SkipPixels += border;
- if (height)
- unpackNew->SkipRows += border;
- if (depth)
- unpackNew->SkipImages += border;
-
- assert(*width >= 3);
- *width = *width - 2 * border;
- if (height && *height >= 3)
- *height = *height - 2 * border;
- if (depth && *depth >= 3)
- *depth = *depth - 2 * border;
-}
-
-
-/**
- * Do glTexImage1/2/3D().
- */
-static void
-st_TexImage(struct gl_context * ctx,
- GLint dims,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint depth,
- GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage,
- GLsizei imageSize, GLboolean compressed_src)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(texObj);
- struct st_texture_image *stImage = st_texture_image(texImage);
- GLuint dstRowStride = 0;
- struct gl_pixelstore_attrib unpackNB;
- enum pipe_transfer_usage transfer_usage = 0;
-
- DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
- _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
-
- /* switch to "normal" */
- if (stObj->surface_based) {
- gl_format texFormat;
-
- _mesa_clear_texture_object(ctx, texObj);
- pipe_resource_reference(&stObj->pt, NULL);
-
- /* oops, need to init this image again */
- texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
- internalFormat, format, type);
-
- _mesa_init_teximage_fields(ctx, target, texImage,
- width, height, depth, border,
- internalFormat, texFormat);
-
- stObj->surface_based = GL_FALSE;
- }
-
- /* gallium does not support texture borders, strip it off */
- if (border) {
- strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
- unpack = &unpackNB;
- texImage->Width = width;
- texImage->Height = height;
- texImage->Depth = depth;
- texImage->Border = 0;
- border = 0;
- }
- else {
- assert(texImage->Width == width);
- assert(texImage->Height == height);
- assert(texImage->Depth == depth);
- }
-
- stImage->face = _mesa_tex_target_to_face(target);
- stImage->level = level;
-
- _mesa_set_fetch_functions(texImage, dims);
-
- /* Release the reference to a potentially orphaned buffer.
- * Release any old malloced memory.
- */
- if (stImage->pt) {
- pipe_resource_reference(&stImage->pt, NULL);
- assert(!texImage->Data);
- }
- else if (texImage->Data) {
- _mesa_align_free(texImage->Data);
- }
-
- /*
- * See if the new image is somehow incompatible with the existing
- * mipmap. If so, free the old mipmap.
- */
- if (stObj->pt) {
- if (level > (GLint) stObj->pt->last_level ||
- !st_texture_match_image(stObj->pt, &stImage->base,
- stImage->face, stImage->level)) {
- DBG("release it\n");
- pipe_resource_reference(&stObj->pt, NULL);
- assert(!stObj->pt);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
- }
-
- if (width == 0 || height == 0 || depth == 0) {
- /* stop after freeing old image */
- return;
- }
-
- if (!stObj->pt) {
- if (!guess_and_alloc_texture(st, stObj, stImage)) {
- /* Probably out of memory.
- * Try flushing any pending rendering, then retry.
- */
- st_finish(st);
- if (!guess_and_alloc_texture(st, stObj, stImage)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return;
- }
- }
- }
-
- assert(!stImage->pt);
-
- /* Check if this texture image can live inside the texture object's buffer.
- * If so, store the image there. Otherwise the image will temporarily live
- * in its own buffer.
- */
- if (stObj->pt &&
- st_texture_match_image(stObj->pt, &stImage->base,
- stImage->face, stImage->level)) {
-
- pipe_resource_reference(&stImage->pt, stObj->pt);
- assert(stImage->pt);
- }
-
- if (!stImage->pt)
- DBG("XXX: Image did not fit into texture - storing in local memory!\n");
-
- /* Pixel data may come from regular user memory or a PBO. For the later,
- * do bounds checking and map the PBO to read pixels data from it.
- *
- * XXX we should try to use a GPU-accelerated path to copy the image data
- * from the PBO to the texture.
- */
- if (compressed_src) {
- pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
- unpack,
- "glCompressedTexImage");
- }
- else {
- pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
- format, type,
- pixels, unpack, "glTexImage");
- }
-
- /*
- * Prepare to store the texture data. Either map the gallium texture buffer
- * memory or malloc space for it.
- */
- if (stImage->pt) {
- /* Store the image in the gallium texture memory buffer */
- if (format == GL_DEPTH_COMPONENT &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- texImage->Data = st_texture_image_map(st, stImage, 0,
- transfer_usage, 0, 0, width, height);
- if(stImage->transfer)
- dstRowStride = stImage->transfer->stride;
- }
- else {
- /* Allocate regular memory and store the image there temporarily. */
- GLuint imageSize = _mesa_format_image_size(texImage->TexFormat,
- width, height, depth);
- dstRowStride = _mesa_format_row_stride(texImage->TexFormat, width);
-
- texImage->Data = _mesa_align_malloc(imageSize, 16);
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return;
- }
-
- if (!pixels) {
- /* We've allocated texture memory, but have no pixel data - all done. */
- goto done;
- }
-
- DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
- width, height, depth, width, dstRowStride);
-
- /* Copy user texture image into the texture buffer.
- */
- if (compressed_src) {
- const GLuint srcRowStride =
- _mesa_format_row_stride(texImage->TexFormat, width);
- if (dstRowStride == srcRowStride) {
- memcpy(texImage->Data, pixels, imageSize);
- }
- else {
- char *dst = texImage->Data;
- const char *src = pixels;
- GLuint i, bw, bh, lines;
- _mesa_get_format_block_size(texImage->TexFormat, &bw, &bh);
- lines = (height + bh - 1) / bh;
-
- for (i = 0; i < lines; ++i) {
- memcpy(dst, src, srcRowStride);
- dst += dstRowStride;
- src += srcRowStride;
- }
- }
- }
- else {
- const GLuint srcImageStride =
- _mesa_image_image_stride(unpack, width, height, format, type);
- GLint i;
- const GLubyte *src = (const GLubyte *) pixels;
-
- for (i = 0; i < depth; i++) {
- if (!_mesa_texstore(ctx, dims,
- texImage->_BaseFormat,
- texImage->TexFormat,
- texImage->Data,
- 0, 0, 0, /* dstX/Y/Zoffset */
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- format, type, src, unpack)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage, i + 1,
- transfer_usage, 0, 0,
- width, height);
- src += srcImageStride;
- }
- }
- }
-
-done:
- _mesa_unmap_teximage_pbo(ctx, unpack);
-
- if (stImage->pt && texImage->Data) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_TexImage3D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint depth,
- GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
- border, format, type, pixels, unpack, texObj, texImage,
- 0, GL_FALSE);
-}
-
-
-static void
-st_TexImage2D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
- format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
-}
-
-
-static void
-st_TexImage1D(struct gl_context * ctx,
- GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint border,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *unpack,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
- format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
-}
-
-
-static void
-st_CompressedTexImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint internalFormat,
- GLint width, GLint height, GLint border,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
- 0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
-}
-
-
-
-/**
- * glGetTexImage() helper: decompress a compressed texture by rendering
- * a textured quad. Store the results in the user's buffer.
- */
-static void
-decompress_with_blit(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid *pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct st_texture_image *stImage = st_texture_image(texImage);
- struct st_texture_object *stObj = st_texture_object(texObj);
- struct pipe_sampler_view *src_view =
- st_get_texture_sampler_view(stObj, pipe);
- const GLuint width = texImage->Width;
- const GLuint height = texImage->Height;
- struct pipe_surface *dst_surface;
- struct pipe_resource *dst_texture;
- struct pipe_transfer *tex_xfer;
- unsigned bind = (PIPE_BIND_RENDER_TARGET | /* util_blit may choose to render */
- PIPE_BIND_TRANSFER_READ);
-
- /* create temp / dest surface */
- if (!util_create_rgba_surface(pipe, width, height, bind,
- &dst_texture, &dst_surface)) {
- _mesa_problem(ctx, "util_create_rgba_surface() failed "
- "in decompress_with_blit()");
- return;
- }
-
- /* blit/render/decompress */
- util_blit_pixels_tex(st->blit,
- src_view, /* pipe_resource (src) */
- 0, 0, /* src x0, y0 */
- width, height, /* src x1, y1 */
- dst_surface, /* pipe_surface (dst) */
- 0, 0, /* dst x0, y0 */
- width, height, /* dst x1, y1 */
- 0.0, /* z */
- PIPE_TEX_MIPFILTER_NEAREST);
-
- /* map the dst_surface so we can read from it */
- tex_xfer = pipe_get_transfer(st_context(ctx)->pipe,
- dst_texture, 0, 0,
- PIPE_TRANSFER_READ,
- 0, 0, width, height);
-
- pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
-
- /* copy/pack data into user buffer */
- if (st_equal_formats(stImage->pt->format, format, type)) {
- /* memcpy */
- const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
- ubyte *map = pipe_transfer_map(pipe, tex_xfer);
- GLuint row;
- for (row = 0; row < height; row++) {
- GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
- height, format, type, row, 0);
- memcpy(dest, map, bytesPerRow);
- map += tex_xfer->stride;
- }
- pipe_transfer_unmap(pipe, tex_xfer);
- }
- else {
- /* format translation via floats */
- GLuint row;
- enum pipe_format format = util_format_linear(dst_texture->format);
- for (row = 0; row < height; row++) {
- const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
- GLfloat rgba[4 * MAX_WIDTH];
- GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
- height, format, type, row, 0);
-
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s: fallback format translation\n", __FUNCTION__);
-
- /* get float[4] rgba row from surface */
- pipe_get_tile_rgba_format(pipe, tex_xfer, 0, row, width, 1,
- format, rgba);
-
- _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
- type, dest, &ctx->Pack, transferOps);
- }
- }
-
- _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
-
- pipe->transfer_destroy(pipe, tex_xfer);
-
- /* destroy the temp / dest surface */
- util_destroy_rgba_surface(dst_texture, dst_surface);
-}
-
-
-
-/**
- * Need to map texture image into memory before copying image data,
- * then unmap it.
- */
-static void
-st_get_tex_image(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid * pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage, GLboolean compressed_dst)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_image *stImage = st_texture_image(texImage);
- const GLuint dstImageStride =
- _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
- format, type);
- GLuint depth, i;
- GLubyte *dest;
-
- if (stImage->pt &&
- util_format_is_s3tc(stImage->pt->format) &&
- !compressed_dst) {
- /* Need to decompress the texture.
- * We'll do this by rendering a textured quad.
- * Note that we only expect RGBA formats (no Z/depth formats).
- */
- decompress_with_blit(ctx, target, level, format, type, pixels,
- texObj, texImage);
- return;
- }
-
- /* Map */
- if (stImage->pt) {
- /* Image is stored in hardware format in a buffer managed by the
- * kernel. Need to explicitly map and unmap it.
- */
- texImage->Data = st_texture_image_map(st, stImage, 0,
- PIPE_TRANSFER_READ, 0, 0,
- stImage->base.Width,
- stImage->base.Height);
- /* compute stride in texels from stride in bytes */
- texImage->RowStride = stImage->transfer->stride
- * util_format_get_blockwidth(stImage->pt->format)
- / util_format_get_blocksize(stImage->pt->format);
- }
- else {
- /* Otherwise, the image should actually be stored in
- * texImage->Data. This is pretty confusing for
- * everybody, I'd much prefer to separate the two functions of
- * texImage->Data - storage for texture images in main memory
- * and access (ie mappings) of images. In other words, we'd
- * create a new texImage->Map field and leave Data simply for
- * storage.
- */
- assert(texImage->Data);
- }
-
- depth = texImage->Depth;
- texImage->Depth = 1;
-
- dest = (GLubyte *) pixels;
-
- _mesa_set_fetch_functions(texImage, get_texture_dims(target));
-
- for (i = 0; i < depth; i++) {
- if (compressed_dst) {
- _mesa_get_compressed_teximage(ctx, target, level, dest,
- texObj, texImage);
- }
- else {
- _mesa_get_teximage(ctx, target, level, format, type, dest,
- texObj, texImage);
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage, i + 1,
- PIPE_TRANSFER_READ, 0, 0,
- stImage->base.Width,
- stImage->base.Height);
- dest += dstImageStride;
- }
- }
-
- texImage->Depth = depth;
-
- /* Unmap */
- if (stImage->pt) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_GetTexImage(struct gl_context * ctx, GLenum target, GLint level,
- GLenum format, GLenum type, GLvoid * pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
- GL_FALSE);
-}
-
-
-static void
-st_GetCompressedTexImage(struct gl_context *ctx, GLenum target, GLint level,
- GLvoid *pixels,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
- GL_TRUE);
-}
-
-
-
-static void
-st_TexSubimage(struct gl_context *ctx, GLint dims, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint width, GLint height, GLint depth,
- GLenum format, GLenum type, const void *pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_image *stImage = st_texture_image(texImage);
- GLuint dstRowStride;
- const GLuint srcImageStride =
- _mesa_image_image_stride(packing, width, height, format, type);
- GLint i;
- const GLubyte *src;
- /* init to silence warning only: */
- enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
-
- DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
- _mesa_lookup_enum_by_nr(target),
- level, xoffset, yoffset, width, height);
-
- pixels =
- _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
- type, pixels, packing, "glTexSubImage2D");
- if (!pixels)
- return;
-
- /* Map buffer if necessary. Need to lock to prevent other contexts
- * from uploading the buffer under us.
- */
- if (stImage->pt) {
- if (format == GL_DEPTH_COMPONENT &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- texImage->Data = st_texture_image_map(st, stImage, zoffset,
- transfer_usage,
- xoffset, yoffset,
- width, height);
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- goto done;
- }
-
- src = (const GLubyte *) pixels;
- dstRowStride = stImage->transfer->stride;
-
- for (i = 0; i < depth; i++) {
- if (!_mesa_texstore(ctx, dims, texImage->_BaseFormat,
- texImage->TexFormat,
- texImage->Data,
- 0, 0, 0,
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- format, type, src, packing)) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- }
-
- if (stImage->pt && i + 1 < depth) {
- /* unmap this slice */
- st_texture_image_unmap(st, stImage);
- /* map next slice of 3D texture */
- texImage->Data = st_texture_image_map(st, stImage,
- zoffset + i + 1,
- transfer_usage,
- xoffset, yoffset,
- width, height);
- src += srcImageStride;
- }
- }
-
-done:
- _mesa_unmap_teximage_pbo(ctx, packing);
-
- if (stImage->pt && texImage->Data) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-
-static void
-st_TexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLsizei width, GLsizei height, GLsizei depth,
- GLenum format, GLenum type, const GLvoid *pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
- width, height, depth, format, type,
- pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_TexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLsizei width, GLsizei height,
- GLenum format, GLenum type, const GLvoid * pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
- width, height, 1, format, type,
- pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_TexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLsizei width, GLenum format, GLenum type,
- const GLvoid * pixels,
- const struct gl_pixelstore_attrib *packing,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
- format, type, pixels, packing, texObj, texImage);
-}
-
-
-static void
-st_CompressedTexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLsizei width,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- assert(0);
-}
-
-
-static void
-st_CompressedTexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLsizei width, GLint height,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_image *stImage = st_texture_image(texImage);
- int srcBlockStride;
- int dstBlockStride;
- int y;
- enum pipe_format pformat;
-
- if (stImage->pt) {
- pformat = stImage->pt->format;
-
- texImage->Data = st_texture_image_map(st, stImage, 0,
- PIPE_TRANSFER_WRITE,
- xoffset, yoffset,
- width, height);
-
- srcBlockStride = util_format_get_stride(pformat, width);
- dstBlockStride = stImage->transfer->stride;
- } else {
- assert(stImage->pt);
- /* TODO find good values for block and strides */
- /* TODO also adjust texImage->data for yoffset/xoffset */
- return;
- }
-
- if (!texImage->Data) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
- return;
- }
-
- assert(xoffset % util_format_get_blockwidth(pformat) == 0);
- assert(yoffset % util_format_get_blockheight(pformat) == 0);
-
- for (y = 0; y < height; y += util_format_get_blockheight(pformat)) {
- /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
- const char *src = (const char*)data + srcBlockStride * util_format_get_nblocksy(pformat, y);
- char *dst = (char*)texImage->Data + dstBlockStride * util_format_get_nblocksy(pformat, y);
- memcpy(dst, src, util_format_get_stride(pformat, width));
- }
-
- if (stImage->pt) {
- st_texture_image_unmap(st, stImage);
- texImage->Data = NULL;
- }
-}
-
-
-static void
-st_CompressedTexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLsizei width, GLint height, GLint depth,
- GLenum format,
- GLsizei imageSize, const GLvoid *data,
- struct gl_texture_object *texObj,
- struct gl_texture_image *texImage)
-{
- assert(0);
-}
-
-
-
-/**
- * Do a CopyTexSubImage operation using a read transfer from the source,
- * a write transfer to the destination and get_tile()/put_tile() to access
- * the pixels/texels.
- *
- * Note: srcY=0=TOP of renderbuffer
- */
-static void
-fallback_copy_texsubimage(struct gl_context *ctx, GLenum target, GLint level,
- struct st_renderbuffer *strb,
- struct st_texture_image *stImage,
- GLenum baseFormat,
- GLint destX, GLint destY, GLint destZ,
- GLint srcX, GLint srcY,
- GLsizei width, GLsizei height)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_transfer *src_trans;
- GLvoid *texDest;
- enum pipe_transfer_usage transfer_usage;
-
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s: fallback processing\n", __FUNCTION__);
-
- assert(width <= MAX_WIDTH);
-
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- srcY = strb->Base.Height - srcY - height;
- }
-
- src_trans = pipe_get_transfer(st_context(ctx)->pipe,
- strb->texture,
- 0, 0,
- PIPE_TRANSFER_READ,
- srcX, srcY,
- width, height);
-
- if ((baseFormat == GL_DEPTH_COMPONENT ||
- baseFormat == GL_DEPTH_STENCIL) &&
- util_format_is_depth_and_stencil(stImage->pt->format))
- transfer_usage = PIPE_TRANSFER_READ_WRITE;
- else
- transfer_usage = PIPE_TRANSFER_WRITE;
-
- /* XXX this used to ignore destZ param */
- texDest = st_texture_image_map(st, stImage, destZ, transfer_usage,
- destX, destY, width, height);
-
- if (baseFormat == GL_DEPTH_COMPONENT ||
- baseFormat == GL_DEPTH_STENCIL) {
- const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
- ctx->Pixel.DepthBias != 0.0F);
- GLint row, yStep;
-
- /* determine bottom-to-top vs. top-to-bottom order for src buffer */
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- srcY = height - 1;
- yStep = -1;
- }
- else {
- srcY = 0;
- yStep = 1;
- }
-
- /* To avoid a large temp memory allocation, do copy row by row */
- for (row = 0; row < height; row++, srcY += yStep) {
- uint data[MAX_WIDTH];
- pipe_get_tile_z(pipe, src_trans, 0, srcY, width, 1, data);
- if (scaleOrBias) {
- _mesa_scale_and_bias_depth_uint(ctx, width, data);
- }
- pipe_put_tile_z(pipe, stImage->transfer, 0, row, width, 1, data);
- }
- }
- else {
- /* RGBA format */
- GLfloat *tempSrc =
- (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
-
- if (tempSrc && texDest) {
- const GLint dims = 2;
- const GLint dstRowStride = stImage->transfer->stride;
- struct gl_texture_image *texImage = &stImage->base;
- struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
-
- if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
- unpack.Invert = GL_TRUE;
- }
-
- /* get float/RGBA image from framebuffer */
- /* XXX this usually involves a lot of int/float conversion.
- * try to avoid that someday.
- */
- pipe_get_tile_rgba_format(pipe, src_trans, 0, 0, width, height,
- util_format_linear(strb->texture->format),
- tempSrc);
-
- /* Store into texture memory.
- * Note that this does some special things such as pixel transfer
- * ops and format conversion. In particular, if the dest tex format
- * is actually RGBA but the user created the texture as GL_RGB we
- * need to fill-in/override the alpha channel with 1.0.
- */
- _mesa_texstore(ctx, dims,
- texImage->_BaseFormat,
- texImage->TexFormat,
- texDest,
- 0, 0, 0,
- dstRowStride,
- texImage->ImageOffsets,
- width, height, 1,
- GL_RGBA, GL_FLOAT, tempSrc, /* src */
- &unpack);
- }
- else {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
- }
-
- if (tempSrc)
- free(tempSrc);
- }
-
- st_texture_image_unmap(st, stImage);
- pipe->transfer_destroy(pipe, src_trans);
-}
-
-
-
-/**
- * If the format of the src renderbuffer and the format of the dest
- * texture are compatible (in terms of blitting), return a TGSI writemask
- * to be used during the blit.
- * If the src/dest are incompatible, return 0.
- */
-static unsigned
-compatible_src_dst_formats(struct gl_context *ctx,
- const struct gl_renderbuffer *src,
- const struct gl_texture_image *dst)
-{
- /* Get logical base formats for the src and dest.
- * That is, use the user-requested formats and not the actual, device-
- * chosen formats.
- * For example, the user may have requested an A8 texture but the
- * driver may actually be using an RGBA texture format. When we
- * copy/blit to that texture, we only want to copy the Alpha channel
- * and not the RGB channels.
- *
- * Similarly, when the src FBO was created an RGB format may have been
- * requested but the driver actually chose an RGBA format. In that case,
- * we don't want to copy the undefined Alpha channel to the dest texture
- * (it should be 1.0).
- */
- const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
- const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
-
- /**
- * XXX when we have red-only and red/green renderbuffers we'll need
- * to add more cases here (or implement a general-purpose routine that
- * queries the existance of the R,G,B,A channels in the src and dest).
- */
- if (srcFormat == dstFormat) {
- /* This is the same as matching_base_formats, which should
- * always pass, as it did previously.
- */
- return TGSI_WRITEMASK_XYZW;
- }
- else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
- /* Make sure that A in the dest is 1. The actual src format
- * may be RGBA and have undefined A values.
- */
- return TGSI_WRITEMASK_XYZ;
- }
- else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
- /* Make sure that A in the dest is 1. The actual dst format
- * may be RGBA and will need A=1 to provide proper alpha values
- * when sampled later.
- */
- return TGSI_WRITEMASK_XYZ;
- }
- else {
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s failed for src %s, dst %s\n",
- __FUNCTION__,
- _mesa_lookup_enum_by_nr(srcFormat),
- _mesa_lookup_enum_by_nr(dstFormat));
-
- /* Otherwise fail.
- */
- return 0;
- }
-}
-
-
-
-/**
- * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
- * Note that the region to copy has already been clipped so we know we
- * won't read from outside the source renderbuffer's bounds.
- *
- * Note: srcY=0=Bottom of renderbuffer (GL convention)
- */
-static void
-st_copy_texsubimage(struct gl_context *ctx,
- GLenum target, GLint level,
- GLint destX, GLint destY, GLint destZ,
- GLint srcX, GLint srcY,
- GLsizei width, GLsizei height)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
- struct st_texture_image *stImage = st_texture_image(texImage);
- const GLenum texBaseFormat = texImage->_BaseFormat;
- struct gl_framebuffer *fb = ctx->ReadBuffer;
- struct st_renderbuffer *strb;
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *screen = pipe->screen;
- enum pipe_format dest_format, src_format;
- GLboolean use_fallback = GL_TRUE;
- GLboolean matching_base_formats;
- GLuint format_writemask, sample_count;
- struct pipe_surface *dest_surface = NULL;
- GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
-
- /* make sure finalize_textures has been called?
- */
- if (0) st_validate_state(st);
-
- /* determine if copying depth or color data */
- if (texBaseFormat == GL_DEPTH_COMPONENT ||
- texBaseFormat == GL_DEPTH_STENCIL) {
- strb = st_renderbuffer(fb->_DepthBuffer);
- if (strb->Base.Wrapped) {
- strb = st_renderbuffer(strb->Base.Wrapped);
- }
- }
- else {
- /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
- strb = st_renderbuffer(fb->_ColorReadBuffer);
- }
-
- if (!strb || !strb->surface || !stImage->pt) {
- debug_printf("%s: null strb or stImage\n", __FUNCTION__);
- return;
- }
-
- sample_count = strb->surface->texture->nr_samples;
- /* I believe this would be legal, presumably would need to do a resolve
- for color, and for depth/stencil spec says to just use one of the
- depth/stencil samples per pixel? Need some transfer clarifications. */
- assert(sample_count < 2);
-
- if (srcX < 0) {
- width -= -srcX;
- destX += -srcX;
- srcX = 0;
- }
-
- if (srcY < 0) {
- height -= -srcY;
- destY += -srcY;
- srcY = 0;
- }
-
- if (destX < 0) {
- width -= -destX;
- srcX += -destX;
- destX = 0;
- }
-
- if (destY < 0) {
- height -= -destY;
- srcY += -destY;
- destY = 0;
- }
-
- if (width < 0 || height < 0)
- return;
-
-
- assert(strb);
- assert(strb->surface);
- assert(stImage->pt);
-
- src_format = strb->surface->format;
- dest_format = stImage->pt->format;
-
- /*
- * Determine if the src framebuffer and dest texture have the same
- * base format. We need this to detect a case such as the framebuffer
- * being GL_RGBA but the texture being GL_RGB. If the actual hardware
- * texture format stores RGBA we need to set A=1 (overriding the
- * framebuffer's alpha values). We can't do that with the blit or
- * textured-quad paths.
- */
- matching_base_formats =
- (_mesa_get_format_base_format(strb->Base.Format) ==
- _mesa_get_format_base_format(texImage->TexFormat));
- format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
-
- if (ctx->_ImageTransferState == 0x0) {
-
- if (matching_base_formats &&
- src_format == dest_format &&
- !do_flip)
- {
- /* use surface_copy() / blit */
- struct pipe_box src_box;
- u_box_2d_zslice(srcX, srcY, strb->surface->u.tex.first_layer,
- width, height, &src_box);
-
- /* for resource_copy_region(), y=0=top, always */
- pipe->resource_copy_region(pipe,
- /* dest */
- stImage->pt,
- stImage->level,
- destX, destY, destZ + stImage->face,
- /* src */
- strb->texture,
- strb->surface->u.tex.level,
- &src_box);
- use_fallback = GL_FALSE;
- }
- else if (format_writemask &&
- texBaseFormat != GL_DEPTH_COMPONENT &&
- texBaseFormat != GL_DEPTH_STENCIL &&
- screen->is_format_supported(screen, src_format,
- PIPE_TEXTURE_2D, sample_count,
- PIPE_BIND_SAMPLER_VIEW,
- 0) &&
- screen->is_format_supported(screen, dest_format,
- PIPE_TEXTURE_2D, 0,
- PIPE_BIND_RENDER_TARGET,
- 0)) {
- /* draw textured quad to do the copy */
- GLint srcY0, srcY1;
- struct pipe_surface surf_tmpl;
- memset(&surf_tmpl, 0, sizeof(surf_tmpl));
- surf_tmpl.format = stImage->pt->format;
- surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
- surf_tmpl.u.tex.level = stImage->level;
- surf_tmpl.u.tex.first_layer = stImage->face + destZ;
- surf_tmpl.u.tex.last_layer = stImage->face + destZ;
-
- dest_surface = pipe->create_surface(pipe, stImage->pt,
- &surf_tmpl);
-
- if (do_flip) {
- srcY1 = strb->Base.Height - srcY - height;
- srcY0 = srcY1 + height;
- }
- else {
- srcY0 = srcY;
- srcY1 = srcY0 + height;
- }
-
- util_blit_pixels_writemask(st->blit,
- strb->texture,
- strb->surface->u.tex.level,
- srcX, srcY0,
- srcX + width, srcY1,
- strb->surface->u.tex.first_layer,
- dest_surface,
- destX, destY,
- destX + width, destY + height,
- 0.0, PIPE_TEX_MIPFILTER_NEAREST,
- format_writemask);
- use_fallback = GL_FALSE;
- }
-
- if (dest_surface)
- pipe_surface_reference(&dest_surface, NULL);
- }
-
- if (use_fallback) {
- /* software fallback */
- fallback_copy_texsubimage(ctx, target, level,
- strb, stImage, texBaseFormat,
- destX, destY, destZ,
- srcX, srcY, width, height);
- }
-}
-
-
-
-static void
-st_CopyTexImage1D(struct gl_context * ctx, GLenum target, GLint level,
- GLenum internalFormat,
- GLint x, GLint y, GLsizei width, GLint border)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
-
- /* Setup or redefine the texture object, texture and texture
- * image. Don't populate yet.
- */
- ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
- width, border,
- GL_RGBA, CHAN_TYPE, NULL,
- &ctx->DefaultPacking, texObj, texImage);
-
- st_copy_texsubimage(ctx, target, level,
- 0, 0, 0, /* destX,Y,Z */
- x, y, width, 1); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexImage2D(struct gl_context * ctx, GLenum target, GLint level,
- GLenum internalFormat,
- GLint x, GLint y, GLsizei width, GLsizei height,
- GLint border)
-{
- struct gl_texture_unit *texUnit =
- &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
- struct gl_texture_object *texObj =
- _mesa_select_tex_object(ctx, texUnit, target);
- struct gl_texture_image *texImage =
- _mesa_select_tex_image(ctx, texObj, target, level);
-
- /* Setup or redefine the texture object, texture and texture
- * image. Don't populate yet.
- */
- ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
- width, height, border,
- GL_RGBA, CHAN_TYPE, NULL,
- &ctx->DefaultPacking, texObj, texImage);
-
- st_copy_texsubimage(ctx, target, level,
- 0, 0, 0, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage1D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint x, GLint y, GLsizei width)
-{
- const GLint yoffset = 0, zoffset = 0;
- const GLsizei height = 1;
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage2D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset,
- GLint x, GLint y, GLsizei width, GLsizei height)
-{
- const GLint zoffset = 0;
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-static void
-st_CopyTexSubImage3D(struct gl_context * ctx, GLenum target, GLint level,
- GLint xoffset, GLint yoffset, GLint zoffset,
- GLint x, GLint y, GLsizei width, GLsizei height)
-{
- st_copy_texsubimage(ctx, target, level,
- xoffset, yoffset, zoffset, /* destX,Y,Z */
- x, y, width, height); /* src X, Y, size */
-}
-
-
-/**
- * Copy image data from stImage into the texture object 'stObj' at level
- * 'dstLevel'.
- */
-static void
-copy_image_data_to_texture(struct st_context *st,
- struct st_texture_object *stObj,
- GLuint dstLevel,
- struct st_texture_image *stImage)
-{
- /* debug checks */
- {
- const struct gl_texture_image *dstImage =
- stObj->base.Image[stImage->face][stImage->level];
- assert(dstImage);
- assert(dstImage->Width == stImage->base.Width);
- assert(dstImage->Height == stImage->base.Height);
- assert(dstImage->Depth == stImage->base.Depth);
- }
-
- if (stImage->pt) {
- /* Copy potentially with the blitter:
- */
- st_texture_image_copy(st->pipe,
- stObj->pt, dstLevel, /* dest texture, level */
- stImage->pt, stImage->level, /* src texture, level */
- stImage->face);
-
- pipe_resource_reference(&stImage->pt, NULL);
- }
- else if (stImage->base.Data) {
- st_texture_image_data(st,
- stObj->pt,
- stImage->face,
- dstLevel,
- stImage->base.Data,
- stImage->base.RowStride *
- util_format_get_blocksize(stObj->pt->format),
- stImage->base.RowStride *
- stImage->base.Height *
- util_format_get_blocksize(stObj->pt->format));
- _mesa_align_free(stImage->base.Data);
- stImage->base.Data = NULL;
- }
-
- pipe_resource_reference(&stImage->pt, stObj->pt);
-}
-
-
-/**
- * Called during state validation. When this function is finished,
- * the texture object should be ready for rendering.
- * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
- */
-GLboolean
-st_finalize_texture(struct gl_context *ctx,
- struct pipe_context *pipe,
- struct gl_texture_object *tObj)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(tObj);
- const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
- GLuint face;
- struct st_texture_image *firstImage;
- enum pipe_format firstImageFormat;
- GLuint ptWidth, ptHeight, ptDepth, ptLayers;
-
- if (stObj->base._Complete) {
- /* The texture is complete and we know exactly how many mipmap levels
- * are present/needed. This is conditional because we may be called
- * from the st_generate_mipmap() function when the texture object is
- * incomplete. In that case, we'll have set stObj->lastLevel before
- * we get here.
- */
- if (stObj->base.MinFilter == GL_LINEAR ||
- stObj->base.MinFilter == GL_NEAREST)
- stObj->lastLevel = stObj->base.BaseLevel;
- else
- stObj->lastLevel = stObj->base._MaxLevel;
- }
-
- firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
- assert(firstImage);
-
- /* If both firstImage and stObj point to a texture which can contain
- * all active images, favour firstImage. Note that because of the
- * completeness requirement, we know that the image dimensions
- * will match.
- */
- if (firstImage->pt &&
- firstImage->pt != stObj->pt &&
- (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
- pipe_resource_reference(&stObj->pt, firstImage->pt);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
-
- /* Find gallium format for the Mesa texture */
- firstImageFormat = st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
-
- /* Find size of level=0 Gallium mipmap image, plus number of texture layers */
- {
- GLuint width, height, depth;
- if (!guess_base_level_size(stObj->base.Target,
- firstImage->base.Width2,
- firstImage->base.Height2,
- firstImage->base.Depth2,
- stObj->base.BaseLevel,
- &width, &height, &depth)) {
- width = stObj->width0;
- height = stObj->height0;
- depth = stObj->depth0;
- }
- /* convert GL dims to Gallium dims */
- st_gl_texture_dims_to_pipe_dims(stObj->base.Target, width, height, depth,
- &ptWidth, &ptHeight, &ptDepth, &ptLayers);
- }
-
- /* If we already have a gallium texture, check that it matches the texture
- * object's format, target, size, num_levels, etc.
- */
- if (stObj->pt) {
- if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
- !st_sampler_compat_formats(stObj->pt->format, firstImageFormat) ||
- stObj->pt->last_level < stObj->lastLevel ||
- stObj->pt->width0 != ptWidth ||
- stObj->pt->height0 != ptHeight ||
- stObj->pt->depth0 != ptDepth ||
- stObj->pt->array_size != ptLayers)
- {
- /* The gallium texture does not match the Mesa texture so delete the
- * gallium texture now. We'll make a new one below.
- */
- pipe_resource_reference(&stObj->pt, NULL);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- st->dirty.st |= ST_NEW_FRAMEBUFFER;
- }
- }
-
- /* May need to create a new gallium texture:
- */
- if (!stObj->pt) {
- GLuint bindings = default_bindings(st, firstImageFormat);
-
- stObj->pt = st_texture_create(st,
- gl_target_to_pipe(stObj->base.Target),
- firstImageFormat,
- stObj->lastLevel,
- ptWidth,
- ptHeight,
- ptDepth,
- ptLayers,
- bindings);
-
- if (!stObj->pt) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
- return GL_FALSE;
- }
- }
-
- /* Pull in any images not in the object's texture:
- */
- for (face = 0; face < nr_faces; face++) {
- GLuint level;
- for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
- struct st_texture_image *stImage =
- st_texture_image(stObj->base.Image[face][level]);
-
- /* Need to import images in main memory or held in other textures.
- */
- if (stImage && stObj->pt != stImage->pt) {
- copy_image_data_to_texture(st, stObj, level, stImage);
- }
- }
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Returns pointer to a default/dummy texture.
- * This is typically used when the current shader has tex/sample instructions
- * but the user has not provided a (any) texture(s).
- */
-struct gl_texture_object *
-st_get_default_texture(struct st_context *st)
-{
- if (!st->default_texture) {
- static const GLenum target = GL_TEXTURE_2D;
- GLubyte pixels[16][16][4];
- struct gl_texture_object *texObj;
- struct gl_texture_image *texImg;
- GLuint i, j;
-
- /* The ARB_fragment_program spec says (0,0,0,1) should be returned
- * when attempting to sample incomplete textures.
- */
- for (i = 0; i < 16; i++) {
- for (j = 0; j < 16; j++) {
- pixels[i][j][0] = 0;
- pixels[i][j][1] = 0;
- pixels[i][j][2] = 0;
- pixels[i][j][3] = 255;
- }
- }
-
- texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
-
- texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
-
- _mesa_init_teximage_fields(st->ctx, target, texImg,
- 16, 16, 1, 0, /* w, h, d, border */
- GL_RGBA, MESA_FORMAT_RGBA8888);
-
- st_TexImage(st->ctx, 2, target,
- 0, GL_RGBA, /* level, intformat */
- 16, 16, 1, 0, /* w, h, d, border */
- GL_RGBA, GL_UNSIGNED_BYTE, pixels,
- &st->ctx->DefaultPacking,
- texObj, texImg,
- 0, 0);
-
- texObj->MinFilter = GL_NEAREST;
- texObj->MagFilter = GL_NEAREST;
- texObj->_Complete = GL_TRUE;
-
- st->default_texture = texObj;
- }
- return st->default_texture;
-}
-
-
-void
-st_init_texture_functions(struct dd_function_table *functions)
-{
- functions->ChooseTextureFormat = st_ChooseTextureFormat;
- functions->TexImage1D = st_TexImage1D;
- functions->TexImage2D = st_TexImage2D;
- functions->TexImage3D = st_TexImage3D;
- functions->TexSubImage1D = st_TexSubImage1D;
- functions->TexSubImage2D = st_TexSubImage2D;
- functions->TexSubImage3D = st_TexSubImage3D;
- functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
- functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
- functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
- functions->CopyTexImage1D = st_CopyTexImage1D;
- functions->CopyTexImage2D = st_CopyTexImage2D;
- functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
- functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
- functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
- functions->GenerateMipmap = st_generate_mipmap;
-
- functions->GetTexImage = st_GetTexImage;
-
- /* compressed texture functions */
- functions->CompressedTexImage2D = st_CompressedTexImage2D;
- functions->GetCompressedTexImage = st_GetCompressedTexImage;
-
- functions->NewTextureObject = st_NewTextureObject;
- functions->NewTextureImage = st_NewTextureImage;
- functions->DeleteTexture = st_DeleteTextureObject;
- functions->FreeTexImageData = st_FreeTextureImageData;
-
- functions->TextureMemCpy = do_memcpy;
-
- /* XXX Temporary until we can query pipe's texture sizes */
- functions->TestProxyTexImage = _mesa_test_proxy_teximage;
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+#include "main/mfeatures.h"
+#include "main/bufferobj.h"
+#include "main/enums.h"
+#include "main/fbobject.h"
+#include "main/formats.h"
+#include "main/image.h"
+#include "main/imports.h"
+#include "main/macros.h"
+#include "main/mipmap.h"
+#include "main/pack.h"
+#include "main/pixeltransfer.h"
+#include "main/texcompress.h"
+#include "main/texfetch.h"
+#include "main/texgetimage.h"
+#include "main/teximage.h"
+#include "main/texobj.h"
+#include "main/texstore.h"
+
+#include "state_tracker/st_debug.h"
+#include "state_tracker/st_context.h"
+#include "state_tracker/st_cb_fbo.h"
+#include "state_tracker/st_cb_flush.h"
+#include "state_tracker/st_cb_texture.h"
+#include "state_tracker/st_format.h"
+#include "state_tracker/st_texture.h"
+#include "state_tracker/st_gen_mipmap.h"
+#include "state_tracker/st_atom.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+#include "pipe/p_shader_tokens.h"
+#include "util/u_tile.h"
+#include "util/u_blit.h"
+#include "util/u_format.h"
+#include "util/u_surface.h"
+#include "util/u_sampler.h"
+#include "util/u_math.h"
+#include "util/u_box.h"
+
+#define DBG if (0) printf
+
+
+static enum pipe_texture_target
+gl_target_to_pipe(GLenum target)
+{
+ switch (target) {
+ case GL_TEXTURE_1D:
+ return PIPE_TEXTURE_1D;
+ case GL_TEXTURE_2D:
+ return PIPE_TEXTURE_2D;
+ case GL_TEXTURE_RECTANGLE_NV:
+ return PIPE_TEXTURE_RECT;
+ case GL_TEXTURE_3D:
+ return PIPE_TEXTURE_3D;
+ case GL_TEXTURE_CUBE_MAP_ARB:
+ return PIPE_TEXTURE_CUBE;
+ case GL_TEXTURE_1D_ARRAY_EXT:
+ return PIPE_TEXTURE_1D_ARRAY;
+ case GL_TEXTURE_2D_ARRAY_EXT:
+ return PIPE_TEXTURE_2D_ARRAY;
+ default:
+ assert(0);
+ return 0;
+ }
+}
+
+
+/** called via ctx->Driver.NewTextureImage() */
+static struct gl_texture_image *
+st_NewTextureImage(struct gl_context * ctx)
+{
+ DBG("%s\n", __FUNCTION__);
+ (void) ctx;
+ return (struct gl_texture_image *) ST_CALLOC_STRUCT(st_texture_image);
+}
+
+
+/** called via ctx->Driver.NewTextureObject() */
+static struct gl_texture_object *
+st_NewTextureObject(struct gl_context * ctx, GLuint name, GLenum target)
+{
+ struct st_texture_object *obj = ST_CALLOC_STRUCT(st_texture_object);
+
+ DBG("%s\n", __FUNCTION__);
+ _mesa_initialize_texture_object(&obj->base, name, target);
+
+ return &obj->base;
+}
+
+/** called via ctx->Driver.DeleteTextureObject() */
+static void
+st_DeleteTextureObject(struct gl_context *ctx,
+ struct gl_texture_object *texObj)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ if (stObj->pt)
+ pipe_resource_reference(&stObj->pt, NULL);
+ if (stObj->sampler_view) {
+ if (stObj->sampler_view->context != st->pipe) {
+ /* Take "ownership" of this texture sampler view by setting
+ * its context pointer to this context. This avoids potential
+ * crashes when the texture object is shared among contexts
+ * and the original/owner context has already been destroyed.
+ */
+ stObj->sampler_view->context = st->pipe;
+ }
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+ _mesa_delete_texture_object(ctx, texObj);
+}
+
+
+/** called via ctx->Driver.FreeTexImageData() */
+static void
+st_FreeTextureImageData(struct gl_context * ctx, struct gl_texture_image *texImage)
+{
+ struct st_texture_image *stImage = st_texture_image(texImage);
+
+ DBG("%s\n", __FUNCTION__);
+
+ if (stImage->pt) {
+ pipe_resource_reference(&stImage->pt, NULL);
+ }
+
+ if (texImage->Data) {
+ _mesa_align_free(texImage->Data);
+ texImage->Data = NULL;
+ }
+}
+
+
+/**
+ * From linux kernel i386 header files, copes with odd sizes better
+ * than COPY_DWORDS would:
+ * XXX Put this in src/mesa/main/imports.h ???
+ */
+#if defined(PIPE_CC_GCC) && defined(PIPE_ARCH_X86)
+static INLINE void *
+__memcpy(void *to, const void *from, size_t n)
+{
+ int d0, d1, d2;
+ __asm__ __volatile__("rep ; movsl\n\t"
+ "testb $2,%b4\n\t"
+ "je 1f\n\t"
+ "movsw\n"
+ "1:\ttestb $1,%b4\n\t"
+ "je 2f\n\t"
+ "movsb\n" "2:":"=&c"(d0), "=&D"(d1), "=&S"(d2)
+ :"0"(n / 4), "q"(n), "1"((long) to), "2"((long) from)
+ :"memory");
+ return (to);
+}
+#else
+#define __memcpy(a,b,c) memcpy(a,b,c)
+#endif
+
+
+/**
+ * The system memcpy (at least on ubuntu 5.10) has problems copying
+ * to agp (writecombined) memory from a source which isn't 64-byte
+ * aligned - there is a 4x performance falloff.
+ *
+ * The x86 __memcpy is immune to this but is slightly slower
+ * (10%-ish) than the system memcpy.
+ *
+ * The sse_memcpy seems to have a slight cliff at 64/32 bytes, but
+ * isn't much faster than x86_memcpy for agp copies.
+ *
+ * TODO: switch dynamically.
+ */
+static void *
+do_memcpy(void *dest, const void *src, size_t n)
+{
+ if ((((unsigned long) src) & 63) || (((unsigned long) dest) & 63)) {
+ return __memcpy(dest, src, n);
+ }
+ else
+ return memcpy(dest, src, n);
+}
+
+
+/**
+ * Return default texture resource binding bitmask for the given format.
+ */
+static GLuint
+default_bindings(struct st_context *st, enum pipe_format format)
+{
+ struct pipe_screen *screen = st->pipe->screen;
+ const unsigned target = PIPE_TEXTURE_2D;
+ const unsigned geom = 0x0;
+ unsigned bindings;
+
+ if (util_format_is_depth_or_stencil(format))
+ bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_DEPTH_STENCIL;
+ else
+ bindings = PIPE_BIND_SAMPLER_VIEW | PIPE_BIND_RENDER_TARGET;
+
+ if (screen->is_format_supported(screen, format, target, 0, bindings, geom))
+ return bindings;
+ else
+ return PIPE_BIND_SAMPLER_VIEW;
+}
+
+
+/** Return number of image dimensions (1, 2 or 3) for a texture target. */
+static GLuint
+get_texture_dims(GLenum target)
+{
+ switch (target) {
+ case GL_TEXTURE_1D:
+ case GL_TEXTURE_1D_ARRAY_EXT:
+ return 1;
+ case GL_TEXTURE_2D:
+ case GL_TEXTURE_CUBE_MAP_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB:
+ case GL_TEXTURE_RECTANGLE_NV:
+ case GL_TEXTURE_2D_ARRAY_EXT:
+ return 2;
+ case GL_TEXTURE_3D:
+ return 3;
+ default:
+ assert(0 && "invalid texture target in get_texture_dims()");
+ return 1;
+ }
+}
+
+
+/**
+ * Given the size of a mipmap image, try to compute the size of the level=0
+ * mipmap image.
+ *
+ * Note that this isn't always accurate for odd-sized, non-POW textures.
+ * For example, if level=1 and width=40 then the level=0 width may be 80 or 81.
+ *
+ * \return GL_TRUE for success, GL_FALSE for failure
+ */
+static GLboolean
+guess_base_level_size(GLenum target,
+ GLuint width, GLuint height, GLuint depth, GLuint level,
+ GLuint *width0, GLuint *height0, GLuint *depth0)
+{
+ const GLuint dims = get_texture_dims(target);
+
+ assert(width >= 1);
+ assert(height >= 1);
+ assert(depth >= 1);
+
+ if (level > 0) {
+ /* Depending on the image's size, we can't always make a guess here */
+ if ((dims >= 1 && width == 1) ||
+ (dims >= 2 && height == 1) ||
+ (dims >= 3 && depth == 1)) {
+ /* we can't determine the image size at level=0 */
+ return GL_FALSE;
+ }
+
+ /* grow the image size until we hit level = 0 */
+ while (level > 0) {
+ if (width > 1)
+ width <<= 1;
+ if (height > 1)
+ height <<= 1;
+ if (depth > 1)
+ depth <<= 1;
+ level--;
+ }
+ }
+
+ *width0 = width;
+ *height0 = height;
+ *depth0 = depth;
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Try to allocate a pipe_resource object for the given st_texture_object.
+ *
+ * We use the given st_texture_image as a clue to determine the size of the
+ * mipmap image at level=0.
+ *
+ * \return GL_TRUE for success, GL_FALSE if out of memory.
+ */
+static GLboolean
+guess_and_alloc_texture(struct st_context *st,
+ struct st_texture_object *stObj,
+ const struct st_texture_image *stImage)
+{
+ GLuint lastLevel, width, height, depth;
+ GLuint bindings;
+ GLuint ptWidth, ptHeight, ptDepth, ptLayers;
+ enum pipe_format fmt;
+
+ DBG("%s\n", __FUNCTION__);
+
+ assert(!stObj->pt);
+
+ if (!guess_base_level_size(stObj->base.Target,
+ stImage->base.Width2,
+ stImage->base.Height2,
+ stImage->base.Depth2,
+ stImage->level,
+ &width, &height, &depth)) {
+ /* we can't determine the image size at level=0 */
+ stObj->width0 = stObj->height0 = stObj->depth0 = 0;
+ /* this is not an out of memory error */
+ return GL_TRUE;
+ }
+
+ /* At this point, (width x height x depth) is the expected size of
+ * the level=0 mipmap image.
+ */
+
+ /* Guess a reasonable value for lastLevel. With OpenGL we have no
+ * idea how many mipmap levels will be in a texture until we start
+ * to render with it. Make an educated guess here but be prepared
+ * to re-allocating a texture buffer with space for more (or fewer)
+ * mipmap levels later.
+ */
+ if ((stObj->base.MinFilter == GL_NEAREST ||
+ stObj->base.MinFilter == GL_LINEAR ||
+ stImage->base._BaseFormat == GL_DEPTH_COMPONENT ||
+ stImage->base._BaseFormat == GL_DEPTH_STENCIL_EXT) &&
+ !stObj->base.GenerateMipmap &&
+ stImage->level == 0) {
+ /* only alloc space for a single mipmap level */
+ lastLevel = 0;
+ }
+ else {
+ /* alloc space for a full mipmap */
+ GLuint l2width = util_logbase2(width);
+ GLuint l2height = util_logbase2(height);
+ GLuint l2depth = util_logbase2(depth);
+ lastLevel = MAX2(MAX2(l2width, l2height), l2depth);
+ }
+
+ /* Save the level=0 dimensions */
+ stObj->width0 = width;
+ stObj->height0 = height;
+ stObj->depth0 = depth;
+
+ fmt = st_mesa_format_to_pipe_format(stImage->base.TexFormat);
+
+ bindings = default_bindings(st, fmt);
+
+ st_gl_texture_dims_to_pipe_dims(stObj->base.Target,
+ width, height, depth,
+ &ptWidth, &ptHeight, &ptDepth, &ptLayers);
+
+ stObj->pt = st_texture_create(st,
+ gl_target_to_pipe(stObj->base.Target),
+ fmt,
+ lastLevel,
+ ptWidth,
+ ptHeight,
+ ptDepth,
+ ptLayers,
+ bindings);
+
+ DBG("%s returning %d\n", __FUNCTION__, (stObj->pt != NULL));
+
+ return stObj->pt != NULL;
+}
+
+
+/**
+ * Adjust pixel unpack params and image dimensions to strip off the
+ * texture border.
+ * Gallium doesn't support texture borders. They've seldem been used
+ * and seldom been implemented correctly anyway.
+ * \param unpackNew returns the new pixel unpack parameters
+ */
+static void
+strip_texture_border(GLint border,
+ GLint *width, GLint *height, GLint *depth,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_pixelstore_attrib *unpackNew)
+{
+ assert(border > 0); /* sanity check */
+
+ *unpackNew = *unpack;
+
+ if (unpackNew->RowLength == 0)
+ unpackNew->RowLength = *width;
+
+ if (depth && unpackNew->ImageHeight == 0)
+ unpackNew->ImageHeight = *height;
+
+ unpackNew->SkipPixels += border;
+ if (height)
+ unpackNew->SkipRows += border;
+ if (depth)
+ unpackNew->SkipImages += border;
+
+ assert(*width >= 3);
+ *width = *width - 2 * border;
+ if (height && *height >= 3)
+ *height = *height - 2 * border;
+ if (depth && *depth >= 3)
+ *depth = *depth - 2 * border;
+}
+
+
+/**
+ * Do glTexImage1/2/3D().
+ */
+static void
+st_TexImage(struct gl_context * ctx,
+ GLint dims,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint depth,
+ GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage,
+ GLsizei imageSize, GLboolean compressed_src)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ GLuint dstRowStride = 0;
+ struct gl_pixelstore_attrib unpackNB;
+ enum pipe_transfer_usage transfer_usage = 0;
+
+ DBG("%s target %s level %d %dx%dx%d border %d\n", __FUNCTION__,
+ _mesa_lookup_enum_by_nr(target), level, width, height, depth, border);
+
+ /* switch to "normal" */
+ if (stObj->surface_based) {
+ gl_format texFormat;
+
+ _mesa_clear_texture_object(ctx, texObj);
+ pipe_resource_reference(&stObj->pt, NULL);
+
+ /* oops, need to init this image again */
+ texFormat = _mesa_choose_texture_format(ctx, texObj, target, level,
+ internalFormat, format, type);
+
+ _mesa_init_teximage_fields(ctx, target, texImage,
+ width, height, depth, border,
+ internalFormat, texFormat);
+
+ stObj->surface_based = GL_FALSE;
+ }
+
+ /* gallium does not support texture borders, strip it off */
+ if (border) {
+ strip_texture_border(border, &width, &height, &depth, unpack, &unpackNB);
+ unpack = &unpackNB;
+ texImage->Width = width;
+ texImage->Height = height;
+ texImage->Depth = depth;
+ texImage->Border = 0;
+ border = 0;
+ }
+ else {
+ assert(texImage->Width == width);
+ assert(texImage->Height == height);
+ assert(texImage->Depth == depth);
+ }
+
+ stImage->face = _mesa_tex_target_to_face(target);
+ stImage->level = level;
+
+ _mesa_set_fetch_functions(texImage, dims);
+
+ /* Release the reference to a potentially orphaned buffer.
+ * Release any old malloced memory.
+ */
+ if (stImage->pt) {
+ pipe_resource_reference(&stImage->pt, NULL);
+ assert(!texImage->Data);
+ }
+ else if (texImage->Data) {
+ _mesa_align_free(texImage->Data);
+ }
+
+ /*
+ * See if the new image is somehow incompatible with the existing
+ * mipmap. If so, free the old mipmap.
+ */
+ if (stObj->pt) {
+ if (level > (GLint) stObj->pt->last_level ||
+ !st_texture_match_image(stObj->pt, &stImage->base,
+ stImage->face, stImage->level)) {
+ DBG("release it\n");
+ pipe_resource_reference(&stObj->pt, NULL);
+ assert(!stObj->pt);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+ }
+
+ if (width == 0 || height == 0 || depth == 0) {
+ /* stop after freeing old image */
+ return;
+ }
+
+ if (!stObj->pt) {
+ if (!guess_and_alloc_texture(st, stObj, stImage)) {
+ /* Probably out of memory.
+ * Try flushing any pending rendering, then retry.
+ */
+ st_finish(st);
+ if (!guess_and_alloc_texture(st, stObj, stImage)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return;
+ }
+ }
+ }
+
+ assert(!stImage->pt);
+
+ /* Check if this texture image can live inside the texture object's buffer.
+ * If so, store the image there. Otherwise the image will temporarily live
+ * in its own buffer.
+ */
+ if (stObj->pt &&
+ st_texture_match_image(stObj->pt, &stImage->base,
+ stImage->face, stImage->level)) {
+
+ pipe_resource_reference(&stImage->pt, stObj->pt);
+ assert(stImage->pt);
+ }
+
+ if (!stImage->pt)
+ DBG("XXX: Image did not fit into texture - storing in local memory!\n");
+
+ /* Pixel data may come from regular user memory or a PBO. For the later,
+ * do bounds checking and map the PBO to read pixels data from it.
+ *
+ * XXX we should try to use a GPU-accelerated path to copy the image data
+ * from the PBO to the texture.
+ */
+ if (compressed_src) {
+ pixels = _mesa_validate_pbo_compressed_teximage(ctx, imageSize, pixels,
+ unpack,
+ "glCompressedTexImage");
+ }
+ else {
+ pixels = _mesa_validate_pbo_teximage(ctx, dims, width, height, 1,
+ format, type,
+ pixels, unpack, "glTexImage");
+ }
+
+ /*
+ * Prepare to store the texture data. Either map the gallium texture buffer
+ * memory or malloc space for it.
+ */
+ if (stImage->pt) {
+ /* Store the image in the gallium texture memory buffer */
+ if (format == GL_DEPTH_COMPONENT &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ transfer_usage, 0, 0, width, height);
+ if(stImage->transfer)
+ dstRowStride = stImage->transfer->stride;
+ }
+ else {
+ /* Allocate regular memory and store the image there temporarily. */
+ GLuint imageSize = _mesa_format_image_size(texImage->TexFormat,
+ width, height, depth);
+ dstRowStride = _mesa_format_row_stride(texImage->TexFormat, width);
+
+ texImage->Data = _mesa_align_malloc(imageSize, 16);
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return;
+ }
+
+ if (!pixels) {
+ /* We've allocated texture memory, but have no pixel data - all done. */
+ goto done;
+ }
+
+ DBG("Upload image %dx%dx%d row_len %x pitch %x\n",
+ width, height, depth, width, dstRowStride);
+
+ /* Copy user texture image into the texture buffer.
+ */
+ if (compressed_src) {
+ const GLuint srcRowStride =
+ _mesa_format_row_stride(texImage->TexFormat, width);
+ if (dstRowStride == srcRowStride) {
+ memcpy(texImage->Data, pixels, imageSize);
+ }
+ else {
+ char *dst = texImage->Data;
+ const char *src = pixels;
+ GLuint i, bw, bh, lines;
+ _mesa_get_format_block_size(texImage->TexFormat, &bw, &bh);
+ lines = (height + bh - 1) / bh;
+
+ for (i = 0; i < lines; ++i) {
+ memcpy(dst, src, srcRowStride);
+ dst += dstRowStride;
+ src += srcRowStride;
+ }
+ }
+ }
+ else {
+ const GLuint srcImageStride =
+ _mesa_image_image_stride(unpack, width, height, format, type);
+ GLint i;
+ const GLubyte *src = (const GLubyte *) pixels;
+
+ for (i = 0; i < depth; i++) {
+ if (!_mesa_texstore(ctx, dims,
+ texImage->_BaseFormat,
+ texImage->TexFormat,
+ texImage->Data,
+ 0, 0, 0, /* dstX/Y/Zoffset */
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ format, type, src, unpack)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage, i + 1,
+ transfer_usage, 0, 0,
+ width, height);
+ src += srcImageStride;
+ }
+ }
+ }
+
+done:
+ _mesa_unmap_teximage_pbo(ctx, unpack);
+
+ if (stImage->pt && texImage->Data) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_TexImage3D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint depth,
+ GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 3, target, level, internalFormat, width, height, depth,
+ border, format, type, pixels, unpack, texObj, texImage,
+ 0, GL_FALSE);
+}
+
+
+static void
+st_TexImage2D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
+ format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
+}
+
+
+static void
+st_TexImage1D(struct gl_context * ctx,
+ GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint border,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *unpack,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 1, target, level, internalFormat, width, 1, 1, border,
+ format, type, pixels, unpack, texObj, texImage, 0, GL_FALSE);
+}
+
+
+static void
+st_CompressedTexImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint internalFormat,
+ GLint width, GLint height, GLint border,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexImage(ctx, 2, target, level, internalFormat, width, height, 1, border,
+ 0, 0, data, &ctx->Unpack, texObj, texImage, imageSize, GL_TRUE);
+}
+
+
+
+/**
+ * glGetTexImage() helper: decompress a compressed texture by rendering
+ * a textured quad. Store the results in the user's buffer.
+ */
+static void
+decompress_with_blit(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid *pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ struct pipe_sampler_view *src_view =
+ st_get_texture_sampler_view(stObj, pipe);
+ const GLuint width = texImage->Width;
+ const GLuint height = texImage->Height;
+ struct pipe_surface *dst_surface;
+ struct pipe_resource *dst_texture;
+ struct pipe_transfer *tex_xfer;
+ unsigned bind = (PIPE_BIND_RENDER_TARGET | /* util_blit may choose to render */
+ PIPE_BIND_TRANSFER_READ);
+
+ /* create temp / dest surface */
+ if (!util_create_rgba_surface(pipe, width, height, bind,
+ &dst_texture, &dst_surface)) {
+ _mesa_problem(ctx, "util_create_rgba_surface() failed "
+ "in decompress_with_blit()");
+ return;
+ }
+
+ /* blit/render/decompress */
+ util_blit_pixels_tex(st->blit,
+ src_view, /* pipe_resource (src) */
+ 0, 0, /* src x0, y0 */
+ width, height, /* src x1, y1 */
+ dst_surface, /* pipe_surface (dst) */
+ 0, 0, /* dst x0, y0 */
+ width, height, /* dst x1, y1 */
+ 0.0, /* z */
+ PIPE_TEX_MIPFILTER_NEAREST);
+
+ /* map the dst_surface so we can read from it */
+ tex_xfer = pipe_get_transfer(st_context(ctx)->pipe,
+ dst_texture, 0, 0,
+ PIPE_TRANSFER_READ,
+ 0, 0, width, height);
+
+ pixels = _mesa_map_pbo_dest(ctx, &ctx->Pack, pixels);
+
+ /* copy/pack data into user buffer */
+ if (st_equal_formats(stImage->pt->format, format, type)) {
+ /* memcpy */
+ const uint bytesPerRow = width * util_format_get_blocksize(stImage->pt->format);
+ ubyte *map = pipe_transfer_map(pipe, tex_xfer);
+ GLuint row;
+ for (row = 0; row < height; row++) {
+ GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
+ height, format, type, row, 0);
+ memcpy(dest, map, bytesPerRow);
+ map += tex_xfer->stride;
+ }
+ pipe_transfer_unmap(pipe, tex_xfer);
+ }
+ else {
+ /* format translation via floats */
+ GLuint row;
+ enum pipe_format format = util_format_linear(dst_texture->format);
+ for (row = 0; row < height; row++) {
+ const GLbitfield transferOps = 0x0; /* bypassed for glGetTexImage() */
+ GLfloat rgba[4 * MAX_WIDTH];
+ GLvoid *dest = _mesa_image_address2d(&ctx->Pack, pixels, width,
+ height, format, type, row, 0);
+
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s: fallback format translation\n", __FUNCTION__);
+
+ /* get float[4] rgba row from surface */
+ pipe_get_tile_rgba_format(pipe, tex_xfer, 0, row, width, 1,
+ format, rgba);
+
+ _mesa_pack_rgba_span_float(ctx, width, (GLfloat (*)[4]) rgba, format,
+ type, dest, &ctx->Pack, transferOps);
+ }
+ }
+
+ _mesa_unmap_pbo_dest(ctx, &ctx->Pack);
+
+ pipe->transfer_destroy(pipe, tex_xfer);
+
+ /* destroy the temp / dest surface */
+ util_destroy_rgba_surface(dst_texture, dst_surface);
+}
+
+
+
+/**
+ * Need to map texture image into memory before copying image data,
+ * then unmap it.
+ */
+static void
+st_get_tex_image(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid * pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage, GLboolean compressed_dst)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ const GLuint dstImageStride =
+ _mesa_image_image_stride(&ctx->Pack, texImage->Width, texImage->Height,
+ format, type);
+ GLuint depth, i;
+ GLubyte *dest;
+
+ if (stImage->pt &&
+ util_format_is_s3tc(stImage->pt->format) &&
+ !compressed_dst) {
+ /* Need to decompress the texture.
+ * We'll do this by rendering a textured quad.
+ * Note that we only expect RGBA formats (no Z/depth formats).
+ */
+ decompress_with_blit(ctx, target, level, format, type, pixels,
+ texObj, texImage);
+ return;
+ }
+
+ /* Map */
+ if (stImage->pt) {
+ /* Image is stored in hardware format in a buffer managed by the
+ * kernel. Need to explicitly map and unmap it.
+ */
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ PIPE_TRANSFER_READ, 0, 0,
+ stImage->base.Width,
+ stImage->base.Height);
+ /* compute stride in texels from stride in bytes */
+ texImage->RowStride = stImage->transfer->stride
+ * util_format_get_blockwidth(stImage->pt->format)
+ / util_format_get_blocksize(stImage->pt->format);
+ }
+ else {
+ /* Otherwise, the image should actually be stored in
+ * texImage->Data. This is pretty confusing for
+ * everybody, I'd much prefer to separate the two functions of
+ * texImage->Data - storage for texture images in main memory
+ * and access (ie mappings) of images. In other words, we'd
+ * create a new texImage->Map field and leave Data simply for
+ * storage.
+ */
+ assert(texImage->Data);
+ }
+
+ depth = texImage->Depth;
+ texImage->Depth = 1;
+
+ dest = (GLubyte *) pixels;
+
+ _mesa_set_fetch_functions(texImage, get_texture_dims(target));
+
+ for (i = 0; i < depth; i++) {
+ if (compressed_dst) {
+ _mesa_get_compressed_teximage(ctx, target, level, dest,
+ texObj, texImage);
+ }
+ else {
+ _mesa_get_teximage(ctx, target, level, format, type, dest,
+ texObj, texImage);
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage, i + 1,
+ PIPE_TRANSFER_READ, 0, 0,
+ stImage->base.Width,
+ stImage->base.Height);
+ dest += dstImageStride;
+ }
+ }
+
+ texImage->Depth = depth;
+
+ /* Unmap */
+ if (stImage->pt) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_GetTexImage(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum format, GLenum type, GLvoid * pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_get_tex_image(ctx, target, level, format, type, pixels, texObj, texImage,
+ GL_FALSE);
+}
+
+
+static void
+st_GetCompressedTexImage(struct gl_context *ctx, GLenum target, GLint level,
+ GLvoid *pixels,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_get_tex_image(ctx, target, level, 0, 0, pixels, texObj, texImage,
+ GL_TRUE);
+}
+
+
+
+static void
+st_TexSubimage(struct gl_context *ctx, GLint dims, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint width, GLint height, GLint depth,
+ GLenum format, GLenum type, const void *pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ GLuint dstRowStride;
+ const GLuint srcImageStride =
+ _mesa_image_image_stride(packing, width, height, format, type);
+ GLint i;
+ const GLubyte *src;
+ /* init to silence warning only: */
+ enum pipe_transfer_usage transfer_usage = PIPE_TRANSFER_WRITE;
+
+ DBG("%s target %s level %d offset %d,%d %dx%d\n", __FUNCTION__,
+ _mesa_lookup_enum_by_nr(target),
+ level, xoffset, yoffset, width, height);
+
+ pixels =
+ _mesa_validate_pbo_teximage(ctx, dims, width, height, depth, format,
+ type, pixels, packing, "glTexSubImage2D");
+ if (!pixels)
+ return;
+
+ /* Map buffer if necessary. Need to lock to prevent other contexts
+ * from uploading the buffer under us.
+ */
+ if (stImage->pt) {
+ if (format == GL_DEPTH_COMPONENT &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ texImage->Data = st_texture_image_map(st, stImage, zoffset,
+ transfer_usage,
+ xoffset, yoffset,
+ width, height);
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ goto done;
+ }
+
+ src = (const GLubyte *) pixels;
+ dstRowStride = stImage->transfer->stride;
+
+ for (i = 0; i < depth; i++) {
+ if (!_mesa_texstore(ctx, dims, texImage->_BaseFormat,
+ texImage->TexFormat,
+ texImage->Data,
+ 0, 0, 0,
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ format, type, src, packing)) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ }
+
+ if (stImage->pt && i + 1 < depth) {
+ /* unmap this slice */
+ st_texture_image_unmap(st, stImage);
+ /* map next slice of 3D texture */
+ texImage->Data = st_texture_image_map(st, stImage,
+ zoffset + i + 1,
+ transfer_usage,
+ xoffset, yoffset,
+ width, height);
+ src += srcImageStride;
+ }
+ }
+
+done:
+ _mesa_unmap_teximage_pbo(ctx, packing);
+
+ if (stImage->pt && texImage->Data) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+
+static void
+st_TexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLsizei width, GLsizei height, GLsizei depth,
+ GLenum format, GLenum type, const GLvoid *pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 3, target, level, xoffset, yoffset, zoffset,
+ width, height, depth, format, type,
+ pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_TexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLsizei width, GLsizei height,
+ GLenum format, GLenum type, const GLvoid * pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 2, target, level, xoffset, yoffset, 0,
+ width, height, 1, format, type,
+ pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_TexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLsizei width, GLenum format, GLenum type,
+ const GLvoid * pixels,
+ const struct gl_pixelstore_attrib *packing,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ st_TexSubimage(ctx, 1, target, level, xoffset, 0, 0, width, 1, 1,
+ format, type, pixels, packing, texObj, texImage);
+}
+
+
+static void
+st_CompressedTexSubImage1D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLsizei width,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ assert(0);
+}
+
+
+static void
+st_CompressedTexSubImage2D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLsizei width, GLint height,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ int srcBlockStride;
+ int dstBlockStride;
+ int y;
+ enum pipe_format pformat;
+
+ if (stImage->pt) {
+ pformat = stImage->pt->format;
+
+ texImage->Data = st_texture_image_map(st, stImage, 0,
+ PIPE_TRANSFER_WRITE,
+ xoffset, yoffset,
+ width, height);
+
+ srcBlockStride = util_format_get_stride(pformat, width);
+ dstBlockStride = stImage->transfer->stride;
+ } else {
+ assert(stImage->pt);
+ /* TODO find good values for block and strides */
+ /* TODO also adjust texImage->data for yoffset/xoffset */
+ return;
+ }
+
+ if (!texImage->Data) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCompressedTexSubImage");
+ return;
+ }
+
+ assert(xoffset % util_format_get_blockwidth(pformat) == 0);
+ assert(yoffset % util_format_get_blockheight(pformat) == 0);
+
+ for (y = 0; y < height; y += util_format_get_blockheight(pformat)) {
+ /* don't need to adjust for xoffset and yoffset as st_texture_image_map does that */
+ const char *src = (const char*)data + srcBlockStride * util_format_get_nblocksy(pformat, y);
+ char *dst = (char*)texImage->Data + dstBlockStride * util_format_get_nblocksy(pformat, y);
+ memcpy(dst, src, util_format_get_stride(pformat, width));
+ }
+
+ if (stImage->pt) {
+ st_texture_image_unmap(st, stImage);
+ texImage->Data = NULL;
+ }
+}
+
+
+static void
+st_CompressedTexSubImage3D(struct gl_context *ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLsizei width, GLint height, GLint depth,
+ GLenum format,
+ GLsizei imageSize, const GLvoid *data,
+ struct gl_texture_object *texObj,
+ struct gl_texture_image *texImage)
+{
+ assert(0);
+}
+
+
+
+/**
+ * Do a CopyTexSubImage operation using a read transfer from the source,
+ * a write transfer to the destination and get_tile()/put_tile() to access
+ * the pixels/texels.
+ *
+ * Note: srcY=0=TOP of renderbuffer
+ */
+static void
+fallback_copy_texsubimage(struct gl_context *ctx, GLenum target, GLint level,
+ struct st_renderbuffer *strb,
+ struct st_texture_image *stImage,
+ GLenum baseFormat,
+ GLint destX, GLint destY, GLint destZ,
+ GLint srcX, GLint srcY,
+ GLsizei width, GLsizei height)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_transfer *src_trans;
+ GLvoid *texDest;
+ enum pipe_transfer_usage transfer_usage;
+
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s: fallback processing\n", __FUNCTION__);
+
+ assert(width <= MAX_WIDTH);
+
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ srcY = strb->Base.Height - srcY - height;
+ }
+
+ src_trans = pipe_get_transfer(st_context(ctx)->pipe,
+ strb->texture,
+ 0, 0,
+ PIPE_TRANSFER_READ,
+ srcX, srcY,
+ width, height);
+
+ if ((baseFormat == GL_DEPTH_COMPONENT ||
+ baseFormat == GL_DEPTH_STENCIL) &&
+ util_format_is_depth_and_stencil(stImage->pt->format))
+ transfer_usage = PIPE_TRANSFER_READ_WRITE;
+ else
+ transfer_usage = PIPE_TRANSFER_WRITE;
+
+ /* XXX this used to ignore destZ param */
+ texDest = st_texture_image_map(st, stImage, destZ, transfer_usage,
+ destX, destY, width, height);
+
+ if (baseFormat == GL_DEPTH_COMPONENT ||
+ baseFormat == GL_DEPTH_STENCIL) {
+ const GLboolean scaleOrBias = (ctx->Pixel.DepthScale != 1.0F ||
+ ctx->Pixel.DepthBias != 0.0F);
+ GLint row, yStep;
+
+ /* determine bottom-to-top vs. top-to-bottom order for src buffer */
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ srcY = height - 1;
+ yStep = -1;
+ }
+ else {
+ srcY = 0;
+ yStep = 1;
+ }
+
+ /* To avoid a large temp memory allocation, do copy row by row */
+ for (row = 0; row < height; row++, srcY += yStep) {
+ uint data[MAX_WIDTH];
+ pipe_get_tile_z(pipe, src_trans, 0, srcY, width, 1, data);
+ if (scaleOrBias) {
+ _mesa_scale_and_bias_depth_uint(ctx, width, data);
+ }
+ pipe_put_tile_z(pipe, stImage->transfer, 0, row, width, 1, data);
+ }
+ }
+ else {
+ /* RGBA format */
+ GLfloat *tempSrc =
+ (GLfloat *) malloc(width * height * 4 * sizeof(GLfloat));
+
+ if (tempSrc && texDest) {
+ const GLint dims = 2;
+ const GLint dstRowStride = stImage->transfer->stride;
+ struct gl_texture_image *texImage = &stImage->base;
+ struct gl_pixelstore_attrib unpack = ctx->DefaultPacking;
+
+ if (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP) {
+ unpack.Invert = GL_TRUE;
+ }
+
+ /* get float/RGBA image from framebuffer */
+ /* XXX this usually involves a lot of int/float conversion.
+ * try to avoid that someday.
+ */
+ pipe_get_tile_rgba_format(pipe, src_trans, 0, 0, width, height,
+ util_format_linear(strb->texture->format),
+ tempSrc);
+
+ /* Store into texture memory.
+ * Note that this does some special things such as pixel transfer
+ * ops and format conversion. In particular, if the dest tex format
+ * is actually RGBA but the user created the texture as GL_RGB we
+ * need to fill-in/override the alpha channel with 1.0.
+ */
+ _mesa_texstore(ctx, dims,
+ texImage->_BaseFormat,
+ texImage->TexFormat,
+ texDest,
+ 0, 0, 0,
+ dstRowStride,
+ texImage->ImageOffsets,
+ width, height, 1,
+ GL_RGBA, GL_FLOAT, tempSrc, /* src */
+ &unpack);
+ }
+ else {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexSubImage");
+ }
+
+ if (tempSrc)
+ free(tempSrc);
+ }
+
+ st_texture_image_unmap(st, stImage);
+ pipe->transfer_destroy(pipe, src_trans);
+}
+
+
+
+/**
+ * If the format of the src renderbuffer and the format of the dest
+ * texture are compatible (in terms of blitting), return a TGSI writemask
+ * to be used during the blit.
+ * If the src/dest are incompatible, return 0.
+ */
+static unsigned
+compatible_src_dst_formats(struct gl_context *ctx,
+ const struct gl_renderbuffer *src,
+ const struct gl_texture_image *dst)
+{
+ /* Get logical base formats for the src and dest.
+ * That is, use the user-requested formats and not the actual, device-
+ * chosen formats.
+ * For example, the user may have requested an A8 texture but the
+ * driver may actually be using an RGBA texture format. When we
+ * copy/blit to that texture, we only want to copy the Alpha channel
+ * and not the RGB channels.
+ *
+ * Similarly, when the src FBO was created an RGB format may have been
+ * requested but the driver actually chose an RGBA format. In that case,
+ * we don't want to copy the undefined Alpha channel to the dest texture
+ * (it should be 1.0).
+ */
+ const GLenum srcFormat = _mesa_base_fbo_format(ctx, src->InternalFormat);
+ const GLenum dstFormat = _mesa_base_tex_format(ctx, dst->InternalFormat);
+
+ /**
+ * XXX when we have red-only and red/green renderbuffers we'll need
+ * to add more cases here (or implement a general-purpose routine that
+ * queries the existance of the R,G,B,A channels in the src and dest).
+ */
+ if (srcFormat == dstFormat) {
+ /* This is the same as matching_base_formats, which should
+ * always pass, as it did previously.
+ */
+ return TGSI_WRITEMASK_XYZW;
+ }
+ else if (srcFormat == GL_RGB && dstFormat == GL_RGBA) {
+ /* Make sure that A in the dest is 1. The actual src format
+ * may be RGBA and have undefined A values.
+ */
+ return TGSI_WRITEMASK_XYZ;
+ }
+ else if (srcFormat == GL_RGBA && dstFormat == GL_RGB) {
+ /* Make sure that A in the dest is 1. The actual dst format
+ * may be RGBA and will need A=1 to provide proper alpha values
+ * when sampled later.
+ */
+ return TGSI_WRITEMASK_XYZ;
+ }
+ else {
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s failed for src %s, dst %s\n",
+ __FUNCTION__,
+ _mesa_lookup_enum_by_nr(srcFormat),
+ _mesa_lookup_enum_by_nr(dstFormat));
+
+ /* Otherwise fail.
+ */
+ return 0;
+ }
+}
+
+
+
+/**
+ * Do a CopyTex[Sub]Image1/2/3D() using a hardware (blit) path if possible.
+ * Note that the region to copy has already been clipped so we know we
+ * won't read from outside the source renderbuffer's bounds.
+ *
+ * Note: srcY=0=Bottom of renderbuffer (GL convention)
+ */
+static void
+st_copy_texsubimage(struct gl_context *ctx,
+ GLenum target, GLint level,
+ GLint destX, GLint destY, GLint destZ,
+ GLint srcX, GLint srcY,
+ GLsizei width, GLsizei height)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+ struct st_texture_image *stImage = st_texture_image(texImage);
+ const GLenum texBaseFormat = texImage->_BaseFormat;
+ struct gl_framebuffer *fb = ctx->ReadBuffer;
+ struct st_renderbuffer *strb;
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *screen = pipe->screen;
+ enum pipe_format dest_format, src_format;
+ GLboolean use_fallback = GL_TRUE;
+ GLboolean matching_base_formats;
+ GLuint format_writemask, sample_count;
+ struct pipe_surface *dest_surface = NULL;
+ GLboolean do_flip = (st_fb_orientation(ctx->ReadBuffer) == Y_0_TOP);
+
+ /* make sure finalize_textures has been called?
+ */
+ if (0) st_validate_state(st);
+
+ /* determine if copying depth or color data */
+ if (texBaseFormat == GL_DEPTH_COMPONENT ||
+ texBaseFormat == GL_DEPTH_STENCIL) {
+ strb = st_renderbuffer(fb->_DepthBuffer);
+ if (strb->Base.Wrapped) {
+ strb = st_renderbuffer(strb->Base.Wrapped);
+ }
+ }
+ else {
+ /* texBaseFormat == GL_RGB, GL_RGBA, GL_ALPHA, etc */
+ strb = st_renderbuffer(fb->_ColorReadBuffer);
+ }
+
+ if (!strb || !strb->surface || !stImage->pt) {
+ debug_printf("%s: null strb or stImage\n", __FUNCTION__);
+ return;
+ }
+
+ sample_count = strb->surface->texture->nr_samples;
+ /* I believe this would be legal, presumably would need to do a resolve
+ for color, and for depth/stencil spec says to just use one of the
+ depth/stencil samples per pixel? Need some transfer clarifications. */
+ assert(sample_count < 2);
+
+ if (srcX < 0) {
+ width -= -srcX;
+ destX += -srcX;
+ srcX = 0;
+ }
+
+ if (srcY < 0) {
+ height -= -srcY;
+ destY += -srcY;
+ srcY = 0;
+ }
+
+ if (destX < 0) {
+ width -= -destX;
+ srcX += -destX;
+ destX = 0;
+ }
+
+ if (destY < 0) {
+ height -= -destY;
+ srcY += -destY;
+ destY = 0;
+ }
+
+ if (width < 0 || height < 0)
+ return;
+
+
+ assert(strb);
+ assert(strb->surface);
+ assert(stImage->pt);
+
+ src_format = strb->surface->format;
+ dest_format = stImage->pt->format;
+
+ /*
+ * Determine if the src framebuffer and dest texture have the same
+ * base format. We need this to detect a case such as the framebuffer
+ * being GL_RGBA but the texture being GL_RGB. If the actual hardware
+ * texture format stores RGBA we need to set A=1 (overriding the
+ * framebuffer's alpha values). We can't do that with the blit or
+ * textured-quad paths.
+ */
+ matching_base_formats =
+ (_mesa_get_format_base_format(strb->Base.Format) ==
+ _mesa_get_format_base_format(texImage->TexFormat));
+ format_writemask = compatible_src_dst_formats(ctx, &strb->Base, texImage);
+
+ if (ctx->_ImageTransferState == 0x0) {
+
+ if (matching_base_formats &&
+ src_format == dest_format &&
+ !do_flip)
+ {
+ /* use surface_copy() / blit */
+ struct pipe_box src_box;
+ u_box_2d_zslice(srcX, srcY, strb->surface->u.tex.first_layer,
+ width, height, &src_box);
+
+ /* for resource_copy_region(), y=0=top, always */
+ pipe->resource_copy_region(pipe,
+ /* dest */
+ stImage->pt,
+ stImage->level,
+ destX, destY, destZ + stImage->face,
+ /* src */
+ strb->texture,
+ strb->surface->u.tex.level,
+ &src_box);
+ use_fallback = GL_FALSE;
+ }
+ else if (format_writemask &&
+ texBaseFormat != GL_DEPTH_COMPONENT &&
+ texBaseFormat != GL_DEPTH_STENCIL &&
+ screen->is_format_supported(screen, src_format,
+ PIPE_TEXTURE_2D, sample_count,
+ PIPE_BIND_SAMPLER_VIEW,
+ 0) &&
+ screen->is_format_supported(screen, dest_format,
+ PIPE_TEXTURE_2D, 0,
+ PIPE_BIND_RENDER_TARGET,
+ 0)) {
+ /* draw textured quad to do the copy */
+ GLint srcY0, srcY1;
+ struct pipe_surface surf_tmpl;
+ memset(&surf_tmpl, 0, sizeof(surf_tmpl));
+ surf_tmpl.format = stImage->pt->format;
+ surf_tmpl.usage = PIPE_BIND_RENDER_TARGET;
+ surf_tmpl.u.tex.level = stImage->level;
+ surf_tmpl.u.tex.first_layer = stImage->face + destZ;
+ surf_tmpl.u.tex.last_layer = stImage->face + destZ;
+
+ dest_surface = pipe->create_surface(pipe, stImage->pt,
+ &surf_tmpl);
+
+ if (do_flip) {
+ srcY1 = strb->Base.Height - srcY - height;
+ srcY0 = srcY1 + height;
+ }
+ else {
+ srcY0 = srcY;
+ srcY1 = srcY0 + height;
+ }
+
+ util_blit_pixels_writemask(st->blit,
+ strb->texture,
+ strb->surface->u.tex.level,
+ srcX, srcY0,
+ srcX + width, srcY1,
+ strb->surface->u.tex.first_layer,
+ dest_surface,
+ destX, destY,
+ destX + width, destY + height,
+ 0.0, PIPE_TEX_MIPFILTER_NEAREST,
+ format_writemask);
+ use_fallback = GL_FALSE;
+ }
+
+ if (dest_surface)
+ pipe_surface_reference(&dest_surface, NULL);
+ }
+
+ if (use_fallback) {
+ /* software fallback */
+ fallback_copy_texsubimage(ctx, target, level,
+ strb, stImage, texBaseFormat,
+ destX, destY, destZ,
+ srcX, srcY, width, height);
+ }
+}
+
+
+
+static void
+st_CopyTexImage1D(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum internalFormat,
+ GLint x, GLint y, GLsizei width, GLint border)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+
+ /* Setup or redefine the texture object, texture and texture
+ * image. Don't populate yet.
+ */
+ ctx->Driver.TexImage1D(ctx, target, level, internalFormat,
+ width, border,
+ GL_RGBA, CHAN_TYPE, NULL,
+ &ctx->DefaultPacking, texObj, texImage);
+
+ st_copy_texsubimage(ctx, target, level,
+ 0, 0, 0, /* destX,Y,Z */
+ x, y, width, 1); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexImage2D(struct gl_context * ctx, GLenum target, GLint level,
+ GLenum internalFormat,
+ GLint x, GLint y, GLsizei width, GLsizei height,
+ GLint border)
+{
+ struct gl_texture_unit *texUnit =
+ &ctx->Texture.Unit[ctx->Texture.CurrentUnit];
+ struct gl_texture_object *texObj =
+ _mesa_select_tex_object(ctx, texUnit, target);
+ struct gl_texture_image *texImage =
+ _mesa_select_tex_image(ctx, texObj, target, level);
+
+ /* Setup or redefine the texture object, texture and texture
+ * image. Don't populate yet.
+ */
+ ctx->Driver.TexImage2D(ctx, target, level, internalFormat,
+ width, height, border,
+ GL_RGBA, CHAN_TYPE, NULL,
+ &ctx->DefaultPacking, texObj, texImage);
+
+ st_copy_texsubimage(ctx, target, level,
+ 0, 0, 0, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage1D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint x, GLint y, GLsizei width)
+{
+ const GLint yoffset = 0, zoffset = 0;
+ const GLsizei height = 1;
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage2D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset,
+ GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ const GLint zoffset = 0;
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+static void
+st_CopyTexSubImage3D(struct gl_context * ctx, GLenum target, GLint level,
+ GLint xoffset, GLint yoffset, GLint zoffset,
+ GLint x, GLint y, GLsizei width, GLsizei height)
+{
+ st_copy_texsubimage(ctx, target, level,
+ xoffset, yoffset, zoffset, /* destX,Y,Z */
+ x, y, width, height); /* src X, Y, size */
+}
+
+
+/**
+ * Copy image data from stImage into the texture object 'stObj' at level
+ * 'dstLevel'.
+ */
+static void
+copy_image_data_to_texture(struct st_context *st,
+ struct st_texture_object *stObj,
+ GLuint dstLevel,
+ struct st_texture_image *stImage)
+{
+ /* debug checks */
+ {
+ const struct gl_texture_image *dstImage =
+ stObj->base.Image[stImage->face][stImage->level];
+ assert(dstImage);
+ assert(dstImage->Width == stImage->base.Width);
+ assert(dstImage->Height == stImage->base.Height);
+ assert(dstImage->Depth == stImage->base.Depth);
+ }
+
+ if (stImage->pt) {
+ /* Copy potentially with the blitter:
+ */
+ st_texture_image_copy(st->pipe,
+ stObj->pt, dstLevel, /* dest texture, level */
+ stImage->pt, stImage->level, /* src texture, level */
+ stImage->face);
+
+ pipe_resource_reference(&stImage->pt, NULL);
+ }
+ else if (stImage->base.Data) {
+ st_texture_image_data(st,
+ stObj->pt,
+ stImage->face,
+ dstLevel,
+ stImage->base.Data,
+ stImage->base.RowStride *
+ util_format_get_blocksize(stObj->pt->format),
+ stImage->base.RowStride *
+ stImage->base.Height *
+ util_format_get_blocksize(stObj->pt->format));
+ _mesa_align_free(stImage->base.Data);
+ stImage->base.Data = NULL;
+ }
+
+ pipe_resource_reference(&stImage->pt, stObj->pt);
+}
+
+
+/**
+ * Called during state validation. When this function is finished,
+ * the texture object should be ready for rendering.
+ * \return GL_TRUE for success, GL_FALSE for failure (out of mem)
+ */
+GLboolean
+st_finalize_texture(struct gl_context *ctx,
+ struct pipe_context *pipe,
+ struct gl_texture_object *tObj)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(tObj);
+ const GLuint nr_faces = (stObj->base.Target == GL_TEXTURE_CUBE_MAP) ? 6 : 1;
+ GLuint face;
+ struct st_texture_image *firstImage;
+ enum pipe_format firstImageFormat;
+ GLuint ptWidth, ptHeight, ptDepth, ptLayers;
+
+ if (stObj->base._Complete) {
+ /* The texture is complete and we know exactly how many mipmap levels
+ * are present/needed. This is conditional because we may be called
+ * from the st_generate_mipmap() function when the texture object is
+ * incomplete. In that case, we'll have set stObj->lastLevel before
+ * we get here.
+ */
+ if (stObj->base.MinFilter == GL_LINEAR ||
+ stObj->base.MinFilter == GL_NEAREST)
+ stObj->lastLevel = stObj->base.BaseLevel;
+ else
+ stObj->lastLevel = stObj->base._MaxLevel;
+ }
+
+ firstImage = st_texture_image(stObj->base.Image[0][stObj->base.BaseLevel]);
+ assert(firstImage);
+
+ /* If both firstImage and stObj point to a texture which can contain
+ * all active images, favour firstImage. Note that because of the
+ * completeness requirement, we know that the image dimensions
+ * will match.
+ */
+ if (firstImage->pt &&
+ firstImage->pt != stObj->pt &&
+ (!stObj->pt || firstImage->pt->last_level >= stObj->pt->last_level)) {
+ pipe_resource_reference(&stObj->pt, firstImage->pt);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+
+ /* Find gallium format for the Mesa texture */
+ firstImageFormat = st_mesa_format_to_pipe_format(firstImage->base.TexFormat);
+
+ /* Find size of level=0 Gallium mipmap image, plus number of texture layers */
+ {
+ GLuint width, height, depth;
+ if (!guess_base_level_size(stObj->base.Target,
+ firstImage->base.Width2,
+ firstImage->base.Height2,
+ firstImage->base.Depth2,
+ stObj->base.BaseLevel,
+ &width, &height, &depth)) {
+ width = stObj->width0;
+ height = stObj->height0;
+ depth = stObj->depth0;
+ }
+ /* convert GL dims to Gallium dims */
+ st_gl_texture_dims_to_pipe_dims(stObj->base.Target, width, height, depth,
+ &ptWidth, &ptHeight, &ptDepth, &ptLayers);
+ }
+
+ /* If we already have a gallium texture, check that it matches the texture
+ * object's format, target, size, num_levels, etc.
+ */
+ if (stObj->pt) {
+ if (stObj->pt->target != gl_target_to_pipe(stObj->base.Target) ||
+ !st_sampler_compat_formats(stObj->pt->format, firstImageFormat) ||
+ stObj->pt->last_level < stObj->lastLevel ||
+ stObj->pt->width0 != ptWidth ||
+ stObj->pt->height0 != ptHeight ||
+ stObj->pt->depth0 != ptDepth ||
+ stObj->pt->array_size != ptLayers)
+ {
+ /* The gallium texture does not match the Mesa texture so delete the
+ * gallium texture now. We'll make a new one below.
+ */
+ pipe_resource_reference(&stObj->pt, NULL);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ st->dirty.st |= ST_NEW_FRAMEBUFFER;
+ }
+ }
+
+ /* May need to create a new gallium texture:
+ */
+ if (!stObj->pt) {
+ GLuint bindings = default_bindings(st, firstImageFormat);
+
+ stObj->pt = st_texture_create(st,
+ gl_target_to_pipe(stObj->base.Target),
+ firstImageFormat,
+ stObj->lastLevel,
+ ptWidth,
+ ptHeight,
+ ptDepth,
+ ptLayers,
+ bindings);
+
+ if (!stObj->pt) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glTexImage");
+ return GL_FALSE;
+ }
+ }
+
+ /* Pull in any images not in the object's texture:
+ */
+ for (face = 0; face < nr_faces; face++) {
+ GLuint level;
+ for (level = stObj->base.BaseLevel; level <= stObj->lastLevel; level++) {
+ struct st_texture_image *stImage =
+ st_texture_image(stObj->base.Image[face][level]);
+
+ /* Need to import images in main memory or held in other textures.
+ */
+ if (stImage && stObj->pt != stImage->pt) {
+ copy_image_data_to_texture(st, stObj, level, stImage);
+ }
+ }
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Returns pointer to a default/dummy texture.
+ * This is typically used when the current shader has tex/sample instructions
+ * but the user has not provided a (any) texture(s).
+ */
+struct gl_texture_object *
+st_get_default_texture(struct st_context *st)
+{
+ if (!st->default_texture) {
+ static const GLenum target = GL_TEXTURE_2D;
+ GLubyte pixels[16][16][4];
+ struct gl_texture_object *texObj;
+ struct gl_texture_image *texImg;
+ GLuint i, j;
+
+ /* The ARB_fragment_program spec says (0,0,0,1) should be returned
+ * when attempting to sample incomplete textures.
+ */
+ for (i = 0; i < 16; i++) {
+ for (j = 0; j < 16; j++) {
+ pixels[i][j][0] = 0;
+ pixels[i][j][1] = 0;
+ pixels[i][j][2] = 0;
+ pixels[i][j][3] = 255;
+ }
+ }
+
+ texObj = st->ctx->Driver.NewTextureObject(st->ctx, 0, target);
+
+ texImg = _mesa_get_tex_image(st->ctx, texObj, target, 0);
+
+ _mesa_init_teximage_fields(st->ctx, target, texImg,
+ 16, 16, 1, 0, /* w, h, d, border */
+ GL_RGBA, MESA_FORMAT_RGBA8888);
+
+ st_TexImage(st->ctx, 2, target,
+ 0, GL_RGBA, /* level, intformat */
+ 16, 16, 1, 0, /* w, h, d, border */
+ GL_RGBA, GL_UNSIGNED_BYTE, pixels,
+ &st->ctx->DefaultPacking,
+ texObj, texImg,
+ 0, 0);
+
+ texObj->MinFilter = GL_NEAREST;
+ texObj->MagFilter = GL_NEAREST;
+ texObj->_Complete = GL_TRUE;
+
+ st->default_texture = texObj;
+ }
+ return st->default_texture;
+}
+
+
+void
+st_init_texture_functions(struct dd_function_table *functions)
+{
+ functions->ChooseTextureFormat = st_ChooseTextureFormat;
+ functions->TexImage1D = st_TexImage1D;
+ functions->TexImage2D = st_TexImage2D;
+ functions->TexImage3D = st_TexImage3D;
+ functions->TexSubImage1D = st_TexSubImage1D;
+ functions->TexSubImage2D = st_TexSubImage2D;
+ functions->TexSubImage3D = st_TexSubImage3D;
+ functions->CompressedTexSubImage1D = st_CompressedTexSubImage1D;
+ functions->CompressedTexSubImage2D = st_CompressedTexSubImage2D;
+ functions->CompressedTexSubImage3D = st_CompressedTexSubImage3D;
+ functions->CopyTexImage1D = st_CopyTexImage1D;
+ functions->CopyTexImage2D = st_CopyTexImage2D;
+ functions->CopyTexSubImage1D = st_CopyTexSubImage1D;
+ functions->CopyTexSubImage2D = st_CopyTexSubImage2D;
+ functions->CopyTexSubImage3D = st_CopyTexSubImage3D;
+ functions->GenerateMipmap = st_generate_mipmap;
+
+ functions->GetTexImage = st_GetTexImage;
+
+ /* compressed texture functions */
+ functions->CompressedTexImage2D = st_CompressedTexImage2D;
+ functions->GetCompressedTexImage = st_GetCompressedTexImage;
+
+ functions->NewTextureObject = st_NewTextureObject;
+ functions->NewTextureImage = st_NewTextureImage;
+ functions->DeleteTexture = st_DeleteTextureObject;
+ functions->FreeTexImageData = st_FreeTextureImageData;
+
+ functions->TextureMemCpy = do_memcpy;
+
+ /* XXX Temporary until we can query pipe's texture sizes */
+ functions->TestProxyTexImage = _mesa_test_proxy_teximage;
+}
diff --git a/mesalib/src/mesa/state_tracker/st_context.c b/mesalib/src/mesa/state_tracker/st_context.c
index 7a19f35bb..8f3a7415d 100644
--- a/mesalib/src/mesa/state_tracker/st_context.c
+++ b/mesalib/src/mesa/state_tracker/st_context.c
@@ -1,297 +1,297 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-#include "main/imports.h"
-#include "main/context.h"
-#include "main/shaderobj.h"
-#include "program/prog_cache.h"
-#include "vbo/vbo.h"
-#include "glapi/glapi.h"
-#include "st_context.h"
-#include "st_debug.h"
-#include "st_cb_accum.h"
-#include "st_cb_bitmap.h"
-#include "st_cb_blit.h"
-#include "st_cb_bufferobjects.h"
-#include "st_cb_clear.h"
-#include "st_cb_condrender.h"
-#include "st_cb_drawpixels.h"
-#include "st_cb_rasterpos.h"
-#include "st_cb_drawtex.h"
-#include "st_cb_eglimage.h"
-#include "st_cb_fbo.h"
-#include "st_cb_feedback.h"
-#include "st_cb_program.h"
-#include "st_cb_queryobj.h"
-#include "st_cb_readpixels.h"
-#include "st_cb_texture.h"
-#include "st_cb_xformfb.h"
-#include "st_cb_flush.h"
-#include "st_cb_strings.h"
-#include "st_cb_viewport.h"
-#include "st_atom.h"
-#include "st_draw.h"
-#include "st_extensions.h"
-#include "st_gen_mipmap.h"
-#include "st_program.h"
-#include "pipe/p_context.h"
-#include "util/u_inlines.h"
-#include "cso_cache/cso_context.h"
-
-
-DEBUG_GET_ONCE_BOOL_OPTION(mesa_mvp_dp4, "MESA_MVP_DP4", FALSE)
-
-
-/**
- * Called via ctx->Driver.UpdateState()
- */
-void st_invalidate_state(struct gl_context * ctx, GLuint new_state)
-{
- struct st_context *st = st_context(ctx);
-
- st->dirty.mesa |= new_state;
- st->dirty.st |= ST_NEW_MESA;
-
- /* This is the only core Mesa module we depend upon.
- * No longer use swrast, swsetup, tnl.
- */
- _vbo_InvalidateState(ctx, new_state);
-}
-
-
-/**
- * Check for multisample env var override.
- */
-int
-st_get_msaa(void)
-{
- const char *msaa = _mesa_getenv("__GL_FSAA_MODE");
- if (msaa)
- return atoi(msaa);
- return 0;
-}
-
-
-static struct st_context *
-st_create_context_priv( struct gl_context *ctx, struct pipe_context *pipe )
-{
- uint i;
- struct st_context *st = ST_CALLOC_STRUCT( st_context );
-
- ctx->st = st;
-
- st->ctx = ctx;
- st->pipe = pipe;
-
- /* XXX: this is one-off, per-screen init: */
- st_debug_init();
-
- /* state tracker needs the VBO module */
- _vbo_CreateContext(ctx);
-
- st->dirty.mesa = ~0;
- st->dirty.st = ~0;
-
- st->cso_context = cso_create_context(pipe);
-
- st_init_atoms( st );
- st_init_bitmap(st);
- st_init_clear(st);
- st_init_draw( st );
- st_init_generate_mipmap(st);
- st_init_blit(st);
-
- if(pipe->screen->get_param(pipe->screen, PIPE_CAP_NPOT_TEXTURES))
- st->internal_target = PIPE_TEXTURE_2D;
- else
- st->internal_target = PIPE_TEXTURE_RECT;
-
- for (i = 0; i < PIPE_MAX_SAMPLERS; i++)
- st->state.sampler_list[i] = &st->state.samplers[i];
-
- for (i = 0; i < 3; i++) {
- memset(&st->velems_util_draw[i], 0, sizeof(struct pipe_vertex_element));
- st->velems_util_draw[i].src_offset = i * 4 * sizeof(float);
- st->velems_util_draw[i].instance_divisor = 0;
- st->velems_util_draw[i].vertex_buffer_index = 0;
- st->velems_util_draw[i].src_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
- }
-
- /* we want all vertex data to be placed in buffer objects */
- vbo_use_buffer_objects(ctx);
-
- /* Need these flags:
- */
- st->ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
-
- st->ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
-
- st->pixel_xfer.cache = _mesa_new_program_cache();
-
- st->force_msaa = st_get_msaa();
-
- /* GL limits and extensions */
- st_init_limits(st);
- st_init_extensions(st);
-
- return st;
-}
-
-
-struct st_context *st_create_context(gl_api api, struct pipe_context *pipe,
- const struct gl_config *visual,
- struct st_context *share)
-{
- struct gl_context *ctx;
- struct gl_context *shareCtx = share ? share->ctx : NULL;
- struct dd_function_table funcs;
-
- /* Sanity checks */
- assert(MESA_SHADER_VERTEX == PIPE_SHADER_VERTEX);
- assert(MESA_SHADER_FRAGMENT == PIPE_SHADER_FRAGMENT);
- assert(MESA_SHADER_GEOMETRY == PIPE_SHADER_GEOMETRY);
-
- memset(&funcs, 0, sizeof(funcs));
- st_init_driver_functions(&funcs);
-
- ctx = _mesa_create_context(api, visual, shareCtx, &funcs, NULL);
-
- /* XXX: need a capability bit in gallium to query if the pipe
- * driver prefers DP4 or MUL/MAD for vertex transformation.
- */
- if (debug_get_option_mesa_mvp_dp4())
- _mesa_set_mvp_with_dp4( ctx, GL_TRUE );
-
- return st_create_context_priv(ctx, pipe);
-}
-
-
-static void st_destroy_context_priv( struct st_context *st )
-{
- uint i;
-
- st_destroy_atoms( st );
- st_destroy_draw( st );
- st_destroy_generate_mipmap(st);
- st_destroy_blit(st);
- st_destroy_clear(st);
- st_destroy_bitmap(st);
- st_destroy_drawpix(st);
- st_destroy_drawtex(st);
-
- /* Unreference any user vertex buffers. */
- for (i = 0; i < st->num_user_vbs; i++) {
- pipe_resource_reference(&st->user_vb[i], NULL);
- }
-
- for (i = 0; i < Elements(st->state.sampler_views); i++) {
- pipe_sampler_view_reference(&st->state.sampler_views[i], NULL);
- }
-
- if (st->default_texture) {
- st->ctx->Driver.DeleteTexture(st->ctx, st->default_texture);
- st->default_texture = NULL;
- }
-
- free( st );
-}
-
-
-void st_destroy_context( struct st_context *st )
-{
- struct pipe_context *pipe = st->pipe;
- struct cso_context *cso = st->cso_context;
- struct gl_context *ctx = st->ctx;
- GLuint i;
-
- /* need to unbind and destroy CSO objects before anything else */
- cso_release_all(st->cso_context);
-
- st_reference_fragprog(st, &st->fp, NULL);
- st_reference_vertprog(st, &st->vp, NULL);
-
- /* release framebuffer surfaces */
- for (i = 0; i < PIPE_MAX_COLOR_BUFS; i++) {
- pipe_surface_reference(&st->state.framebuffer.cbufs[i], NULL);
- }
- pipe_surface_reference(&st->state.framebuffer.zsbuf, NULL);
-
- pipe->set_index_buffer(pipe, NULL);
-
- for (i = 0; i < PIPE_SHADER_TYPES; i++) {
- pipe->set_constant_buffer(pipe, i, 0, NULL);
- }
-
- _mesa_delete_program_cache(st->ctx, st->pixel_xfer.cache);
-
- _vbo_DestroyContext(st->ctx);
-
- st_destroy_program_variants(st);
-
- _mesa_free_context_data(ctx);
-
- st_destroy_context_priv(st);
-
- cso_destroy_context(cso);
-
- pipe->destroy( pipe );
-
- free(ctx);
-}
-
-
-void st_init_driver_functions(struct dd_function_table *functions)
-{
- _mesa_init_shader_object_functions(functions);
-
- st_init_accum_functions(functions);
- st_init_blit_functions(functions);
- st_init_bufferobject_functions(functions);
- st_init_clear_functions(functions);
- st_init_bitmap_functions(functions);
- st_init_drawpixels_functions(functions);
- st_init_rasterpos_functions(functions);
-
- st_init_drawtex_functions(functions);
-
- st_init_eglimage_functions(functions);
-
- st_init_fbo_functions(functions);
- st_init_feedback_functions(functions);
- st_init_program_functions(functions);
- st_init_query_functions(functions);
- st_init_cond_render_functions(functions);
- st_init_readpixels_functions(functions);
- st_init_texture_functions(functions);
- st_init_flush_functions(functions);
- st_init_string_functions(functions);
- st_init_viewport_functions(functions);
-
- st_init_xformfb_functions(functions);
-
- functions->UpdateState = st_invalidate_state;
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+#include "main/imports.h"
+#include "main/context.h"
+#include "main/shaderobj.h"
+#include "program/prog_cache.h"
+#include "vbo/vbo.h"
+#include "glapi/glapi.h"
+#include "st_context.h"
+#include "st_debug.h"
+#include "st_cb_accum.h"
+#include "st_cb_bitmap.h"
+#include "st_cb_blit.h"
+#include "st_cb_bufferobjects.h"
+#include "st_cb_clear.h"
+#include "st_cb_condrender.h"
+#include "st_cb_drawpixels.h"
+#include "st_cb_rasterpos.h"
+#include "st_cb_drawtex.h"
+#include "st_cb_eglimage.h"
+#include "st_cb_fbo.h"
+#include "st_cb_feedback.h"
+#include "st_cb_program.h"
+#include "st_cb_queryobj.h"
+#include "st_cb_readpixels.h"
+#include "st_cb_texture.h"
+#include "st_cb_xformfb.h"
+#include "st_cb_flush.h"
+#include "st_cb_strings.h"
+#include "st_cb_viewport.h"
+#include "st_atom.h"
+#include "st_draw.h"
+#include "st_extensions.h"
+#include "st_gen_mipmap.h"
+#include "st_program.h"
+#include "pipe/p_context.h"
+#include "util/u_inlines.h"
+#include "cso_cache/cso_context.h"
+
+
+DEBUG_GET_ONCE_BOOL_OPTION(mesa_mvp_dp4, "MESA_MVP_DP4", FALSE)
+
+
+/**
+ * Called via ctx->Driver.UpdateState()
+ */
+void st_invalidate_state(struct gl_context * ctx, GLuint new_state)
+{
+ struct st_context *st = st_context(ctx);
+
+ st->dirty.mesa |= new_state;
+ st->dirty.st |= ST_NEW_MESA;
+
+ /* This is the only core Mesa module we depend upon.
+ * No longer use swrast, swsetup, tnl.
+ */
+ _vbo_InvalidateState(ctx, new_state);
+}
+
+
+/**
+ * Check for multisample env var override.
+ */
+int
+st_get_msaa(void)
+{
+ const char *msaa = _mesa_getenv("__GL_FSAA_MODE");
+ if (msaa)
+ return atoi(msaa);
+ return 0;
+}
+
+
+static struct st_context *
+st_create_context_priv( struct gl_context *ctx, struct pipe_context *pipe )
+{
+ uint i;
+ struct st_context *st = ST_CALLOC_STRUCT( st_context );
+
+ ctx->st = st;
+
+ st->ctx = ctx;
+ st->pipe = pipe;
+
+ /* XXX: this is one-off, per-screen init: */
+ st_debug_init();
+
+ /* state tracker needs the VBO module */
+ _vbo_CreateContext(ctx);
+
+ st->dirty.mesa = ~0;
+ st->dirty.st = ~0;
+
+ st->cso_context = cso_create_context(pipe);
+
+ st_init_atoms( st );
+ st_init_bitmap(st);
+ st_init_clear(st);
+ st_init_draw( st );
+ st_init_generate_mipmap(st);
+ st_init_blit(st);
+
+ if(pipe->screen->get_param(pipe->screen, PIPE_CAP_NPOT_TEXTURES))
+ st->internal_target = PIPE_TEXTURE_2D;
+ else
+ st->internal_target = PIPE_TEXTURE_RECT;
+
+ for (i = 0; i < PIPE_MAX_SAMPLERS; i++)
+ st->state.sampler_list[i] = &st->state.samplers[i];
+
+ for (i = 0; i < 3; i++) {
+ memset(&st->velems_util_draw[i], 0, sizeof(struct pipe_vertex_element));
+ st->velems_util_draw[i].src_offset = i * 4 * sizeof(float);
+ st->velems_util_draw[i].instance_divisor = 0;
+ st->velems_util_draw[i].vertex_buffer_index = 0;
+ st->velems_util_draw[i].src_format = PIPE_FORMAT_R32G32B32A32_FLOAT;
+ }
+
+ /* we want all vertex data to be placed in buffer objects */
+ vbo_use_buffer_objects(ctx);
+
+ /* Need these flags:
+ */
+ st->ctx->FragmentProgram._MaintainTexEnvProgram = GL_TRUE;
+
+ st->ctx->VertexProgram._MaintainTnlProgram = GL_TRUE;
+
+ st->pixel_xfer.cache = _mesa_new_program_cache();
+
+ st->force_msaa = st_get_msaa();
+
+ /* GL limits and extensions */
+ st_init_limits(st);
+ st_init_extensions(st);
+
+ return st;
+}
+
+
+struct st_context *st_create_context(gl_api api, struct pipe_context *pipe,
+ const struct gl_config *visual,
+ struct st_context *share)
+{
+ struct gl_context *ctx;
+ struct gl_context *shareCtx = share ? share->ctx : NULL;
+ struct dd_function_table funcs;
+
+ /* Sanity checks */
+ assert(MESA_SHADER_VERTEX == PIPE_SHADER_VERTEX);
+ assert(MESA_SHADER_FRAGMENT == PIPE_SHADER_FRAGMENT);
+ assert(MESA_SHADER_GEOMETRY == PIPE_SHADER_GEOMETRY);
+
+ memset(&funcs, 0, sizeof(funcs));
+ st_init_driver_functions(&funcs);
+
+ ctx = _mesa_create_context(api, visual, shareCtx, &funcs, NULL);
+
+ /* XXX: need a capability bit in gallium to query if the pipe
+ * driver prefers DP4 or MUL/MAD for vertex transformation.
+ */
+ if (debug_get_option_mesa_mvp_dp4())
+ _mesa_set_mvp_with_dp4( ctx, GL_TRUE );
+
+ return st_create_context_priv(ctx, pipe);
+}
+
+
+static void st_destroy_context_priv( struct st_context *st )
+{
+ uint i;
+
+ st_destroy_atoms( st );
+ st_destroy_draw( st );
+ st_destroy_generate_mipmap(st);
+ st_destroy_blit(st);
+ st_destroy_clear(st);
+ st_destroy_bitmap(st);
+ st_destroy_drawpix(st);
+ st_destroy_drawtex(st);
+
+ /* Unreference any user vertex buffers. */
+ for (i = 0; i < st->num_user_vbs; i++) {
+ pipe_resource_reference(&st->user_vb[i], NULL);
+ }
+
+ for (i = 0; i < Elements(st->state.sampler_views); i++) {
+ pipe_sampler_view_reference(&st->state.sampler_views[i], NULL);
+ }
+
+ if (st->default_texture) {
+ st->ctx->Driver.DeleteTexture(st->ctx, st->default_texture);
+ st->default_texture = NULL;
+ }
+
+ free( st );
+}
+
+
+void st_destroy_context( struct st_context *st )
+{
+ struct pipe_context *pipe = st->pipe;
+ struct cso_context *cso = st->cso_context;
+ struct gl_context *ctx = st->ctx;
+ GLuint i;
+
+ /* need to unbind and destroy CSO objects before anything else */
+ cso_release_all(st->cso_context);
+
+ st_reference_fragprog(st, &st->fp, NULL);
+ st_reference_vertprog(st, &st->vp, NULL);
+
+ /* release framebuffer surfaces */
+ for (i = 0; i < PIPE_MAX_COLOR_BUFS; i++) {
+ pipe_surface_reference(&st->state.framebuffer.cbufs[i], NULL);
+ }
+ pipe_surface_reference(&st->state.framebuffer.zsbuf, NULL);
+
+ pipe->set_index_buffer(pipe, NULL);
+
+ for (i = 0; i < PIPE_SHADER_TYPES; i++) {
+ pipe->set_constant_buffer(pipe, i, 0, NULL);
+ }
+
+ _mesa_delete_program_cache(st->ctx, st->pixel_xfer.cache);
+
+ _vbo_DestroyContext(st->ctx);
+
+ st_destroy_program_variants(st);
+
+ _mesa_free_context_data(ctx);
+
+ st_destroy_context_priv(st);
+
+ cso_destroy_context(cso);
+
+ pipe->destroy( pipe );
+
+ free(ctx);
+}
+
+
+void st_init_driver_functions(struct dd_function_table *functions)
+{
+ _mesa_init_shader_object_functions(functions);
+
+ st_init_accum_functions(functions);
+ st_init_blit_functions(functions);
+ st_init_bufferobject_functions(functions);
+ st_init_clear_functions(functions);
+ st_init_bitmap_functions(functions);
+ st_init_drawpixels_functions(functions);
+ st_init_rasterpos_functions(functions);
+
+ st_init_drawtex_functions(functions);
+
+ st_init_eglimage_functions(functions);
+
+ st_init_fbo_functions(functions);
+ st_init_feedback_functions(functions);
+ st_init_program_functions(functions);
+ st_init_query_functions(functions);
+ st_init_cond_render_functions(functions);
+ st_init_readpixels_functions(functions);
+ st_init_texture_functions(functions);
+ st_init_flush_functions(functions);
+ st_init_string_functions(functions);
+ st_init_viewport_functions(functions);
+
+ st_init_xformfb_functions(functions);
+
+ functions->UpdateState = st_invalidate_state;
+}
diff --git a/mesalib/src/mesa/state_tracker/st_context.h b/mesalib/src/mesa/state_tracker/st_context.h
index 77765f023..ef54fd7cd 100644
--- a/mesalib/src/mesa/state_tracker/st_context.h
+++ b/mesalib/src/mesa/state_tracker/st_context.h
@@ -1,270 +1,270 @@
-/**************************************************************************
- *
- * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 ST_CONTEXT_H
-#define ST_CONTEXT_H
-
-#include "main/mtypes.h"
-#include "pipe/p_state.h"
-#include "state_tracker/st_api.h"
-
-struct bitmap_cache;
-struct blit_state;
-struct dd_function_table;
-struct draw_context;
-struct draw_stage;
-struct gen_mipmap_state;
-struct st_context;
-struct st_fragment_program;
-
-
-#define ST_NEW_MESA 0x1 /* Mesa state has changed */
-#define ST_NEW_FRAGMENT_PROGRAM 0x2
-#define ST_NEW_VERTEX_PROGRAM 0x4
-#define ST_NEW_FRAMEBUFFER 0x8
-#define ST_NEW_EDGEFLAGS_DATA 0x10
-#define ST_NEW_GEOMETRY_PROGRAM 0x20
-
-
-struct st_state_flags {
- GLuint mesa;
- GLuint st;
-};
-
-struct st_tracked_state {
- const char *name;
- struct st_state_flags dirty;
- void (*update)( struct st_context *st );
-};
-
-
-
-struct st_context
-{
- struct st_context_iface iface;
-
- struct gl_context *ctx;
-
- struct pipe_context *pipe;
-
- struct draw_context *draw; /**< For selection/feedback/rastpos only */
- struct draw_stage *feedback_stage; /**< For GL_FEEDBACK rendermode */
- struct draw_stage *selection_stage; /**< For GL_SELECT rendermode */
- struct draw_stage *rastpos_stage; /**< For glRasterPos */
-
-
- /* On old libGL's for linux we need to invalidate the drawables
- * on glViewpport calls, this is set via a option.
- */
- boolean invalidate_on_gl_viewport;
-
- /* Some state is contained in constant objects.
- * Other state is just parameter values.
- */
- struct {
- struct pipe_blend_state blend;
- struct pipe_depth_stencil_alpha_state depth_stencil;
- struct pipe_rasterizer_state rasterizer;
- struct pipe_sampler_state samplers[PIPE_MAX_SAMPLERS];
- struct pipe_sampler_state *sampler_list[PIPE_MAX_SAMPLERS];
- struct pipe_clip_state clip;
- struct {
- void *ptr;
- unsigned size;
- } constants[PIPE_SHADER_TYPES];
- struct pipe_framebuffer_state framebuffer;
- struct pipe_sampler_view *sampler_views[PIPE_MAX_SAMPLERS];
- struct pipe_scissor_state scissor;
- struct pipe_viewport_state viewport;
- unsigned sample_mask;
-
- GLuint num_samplers;
- GLuint num_textures;
-
- GLuint poly_stipple[32]; /**< In OpenGL's bottom-to-top order */
- } state;
-
- char vendor[100];
- char renderer[100];
-
- struct st_state_flags dirty;
-
- GLboolean missing_textures;
- GLboolean vertdata_edgeflags;
-
- /** Mapping from VERT_RESULT_x to post-transformed vertex slot */
- const GLuint *vertex_result_to_slot;
-
- struct st_vertex_program *vp; /**< Currently bound vertex program */
- struct st_fragment_program *fp; /**< Currently bound fragment program */
- struct st_geometry_program *gp; /**< Currently bound geometry program */
-
- struct st_vp_variant *vp_variant;
- struct st_fp_variant *fp_variant;
- struct st_gp_variant *gp_variant;
-
- struct gl_texture_object *default_texture;
-
- struct {
- struct gl_program_cache *cache;
- struct st_fragment_program *program; /**< cur pixel transfer prog */
- GLuint xfer_prog_sn; /**< pixel xfer program serial no. */
- GLuint user_prog_sn; /**< user fragment program serial no. */
- struct st_fragment_program *combined_prog;
- GLuint combined_prog_sn;
- struct pipe_resource *pixelmap_texture;
- struct pipe_sampler_view *pixelmap_sampler_view;
- boolean pixelmap_enabled; /**< use the pixelmap texture? */
- } pixel_xfer;
-
- /** for glBitmap */
- struct {
- struct pipe_rasterizer_state rasterizer;
- struct pipe_sampler_state samplers[2];
- enum pipe_format tex_format;
- void *vs;
- float vertices[4][3][4]; /**< vertex pos + color + texcoord */
- struct pipe_resource *vbuf;
- unsigned vbuf_slot; /* next free slot in vbuf */
- struct bitmap_cache *cache;
- } bitmap;
-
- /** for glDraw/CopyPixels */
- struct {
- struct gl_fragment_program *shaders[4];
- void *vert_shaders[2]; /**< ureg shaders */
- } drawpix;
-
- /** for glClear */
- struct {
- struct pipe_rasterizer_state raster;
- struct pipe_viewport_state viewport;
- struct pipe_clip_state clip;
- void *vs;
- void *fs;
- float vertices[4][2][4]; /**< vertex pos + color */
- struct pipe_resource *vbuf;
- unsigned vbuf_slot;
- boolean enable_ds_separate;
- } clear;
-
- /** used for anything using util_draw_vertex_buffer */
- struct pipe_vertex_element velems_util_draw[3];
-
- void *passthrough_fs; /**< simple pass-through frag shader */
-
- enum pipe_texture_target internal_target;
- struct gen_mipmap_state *gen_mipmap;
- struct blit_state *blit;
-
- struct cso_context *cso_context;
-
- int force_msaa;
- void *winsys_drawable_handle;
-
- /* User vertex buffers. */
- struct pipe_resource *user_vb[PIPE_MAX_ATTRIBS];
- unsigned user_vb_stride[PIPE_MAX_ATTRIBS];
- unsigned num_user_vbs;
-};
-
-
-/* Need this so that we can implement Mesa callbacks in this module.
- */
-static INLINE struct st_context *st_context(struct gl_context *ctx)
-{
- return ctx->st;
-}
-
-
-/**
- * Wrapper for struct gl_framebuffer.
- * This is an opaque type to the outside world.
- */
-struct st_framebuffer
-{
- struct gl_framebuffer Base;
- void *Private;
-
- struct st_framebuffer_iface *iface;
- enum st_attachment_type statts[ST_ATTACHMENT_COUNT];
- unsigned num_statts;
- int32_t revalidate;
-};
-
-
-extern void st_init_driver_functions(struct dd_function_table *functions);
-
-void st_invalidate_state(struct gl_context * ctx, GLuint new_state);
-
-
-
-#define Y_0_TOP 1
-#define Y_0_BOTTOM 2
-
-static INLINE GLuint
-st_fb_orientation(const struct gl_framebuffer *fb)
-{
- if (fb && fb->Name == 0) {
- /* Drawing into a window (on-screen buffer).
- *
- * Negate Y scale to flip image vertically.
- * The NDC Y coords prior to viewport transformation are in the range
- * [y=-1=bottom, y=1=top]
- * Hardware window coords are in the range [y=0=top, y=H-1=bottom] where
- * H is the window height.
- * Use the viewport transformation to invert Y.
- */
- return Y_0_TOP;
- }
- else {
- /* Drawing into user-created FBO (very likely a texture).
- *
- * For textures, T=0=Bottom, so by extension Y=0=Bottom for rendering.
- */
- return Y_0_BOTTOM;
- }
-}
-
-
-/** clear-alloc a struct-sized object, with casting */
-#define ST_CALLOC_STRUCT(T) (struct T *) calloc(1, sizeof(struct T))
-
-
-extern int
-st_get_msaa(void);
-
-extern struct st_context *
-st_create_context(gl_api api, struct pipe_context *pipe,
- const struct gl_config *visual,
- struct st_context *share);
-
-extern void
-st_destroy_context(struct st_context *st);
-
-
-#endif
+/**************************************************************************
+ *
+ * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 ST_CONTEXT_H
+#define ST_CONTEXT_H
+
+#include "main/mtypes.h"
+#include "pipe/p_state.h"
+#include "state_tracker/st_api.h"
+
+struct bitmap_cache;
+struct blit_state;
+struct dd_function_table;
+struct draw_context;
+struct draw_stage;
+struct gen_mipmap_state;
+struct st_context;
+struct st_fragment_program;
+
+
+#define ST_NEW_MESA 0x1 /* Mesa state has changed */
+#define ST_NEW_FRAGMENT_PROGRAM 0x2
+#define ST_NEW_VERTEX_PROGRAM 0x4
+#define ST_NEW_FRAMEBUFFER 0x8
+#define ST_NEW_EDGEFLAGS_DATA 0x10
+#define ST_NEW_GEOMETRY_PROGRAM 0x20
+
+
+struct st_state_flags {
+ GLuint mesa;
+ GLuint st;
+};
+
+struct st_tracked_state {
+ const char *name;
+ struct st_state_flags dirty;
+ void (*update)( struct st_context *st );
+};
+
+
+
+struct st_context
+{
+ struct st_context_iface iface;
+
+ struct gl_context *ctx;
+
+ struct pipe_context *pipe;
+
+ struct draw_context *draw; /**< For selection/feedback/rastpos only */
+ struct draw_stage *feedback_stage; /**< For GL_FEEDBACK rendermode */
+ struct draw_stage *selection_stage; /**< For GL_SELECT rendermode */
+ struct draw_stage *rastpos_stage; /**< For glRasterPos */
+
+
+ /* On old libGL's for linux we need to invalidate the drawables
+ * on glViewpport calls, this is set via a option.
+ */
+ boolean invalidate_on_gl_viewport;
+
+ /* Some state is contained in constant objects.
+ * Other state is just parameter values.
+ */
+ struct {
+ struct pipe_blend_state blend;
+ struct pipe_depth_stencil_alpha_state depth_stencil;
+ struct pipe_rasterizer_state rasterizer;
+ struct pipe_sampler_state samplers[PIPE_MAX_SAMPLERS];
+ struct pipe_sampler_state *sampler_list[PIPE_MAX_SAMPLERS];
+ struct pipe_clip_state clip;
+ struct {
+ void *ptr;
+ unsigned size;
+ } constants[PIPE_SHADER_TYPES];
+ struct pipe_framebuffer_state framebuffer;
+ struct pipe_sampler_view *sampler_views[PIPE_MAX_SAMPLERS];
+ struct pipe_scissor_state scissor;
+ struct pipe_viewport_state viewport;
+ unsigned sample_mask;
+
+ GLuint num_samplers;
+ GLuint num_textures;
+
+ GLuint poly_stipple[32]; /**< In OpenGL's bottom-to-top order */
+ } state;
+
+ char vendor[100];
+ char renderer[100];
+
+ struct st_state_flags dirty;
+
+ GLboolean missing_textures;
+ GLboolean vertdata_edgeflags;
+
+ /** Mapping from VERT_RESULT_x to post-transformed vertex slot */
+ const GLuint *vertex_result_to_slot;
+
+ struct st_vertex_program *vp; /**< Currently bound vertex program */
+ struct st_fragment_program *fp; /**< Currently bound fragment program */
+ struct st_geometry_program *gp; /**< Currently bound geometry program */
+
+ struct st_vp_variant *vp_variant;
+ struct st_fp_variant *fp_variant;
+ struct st_gp_variant *gp_variant;
+
+ struct gl_texture_object *default_texture;
+
+ struct {
+ struct gl_program_cache *cache;
+ struct st_fragment_program *program; /**< cur pixel transfer prog */
+ GLuint xfer_prog_sn; /**< pixel xfer program serial no. */
+ GLuint user_prog_sn; /**< user fragment program serial no. */
+ struct st_fragment_program *combined_prog;
+ GLuint combined_prog_sn;
+ struct pipe_resource *pixelmap_texture;
+ struct pipe_sampler_view *pixelmap_sampler_view;
+ boolean pixelmap_enabled; /**< use the pixelmap texture? */
+ } pixel_xfer;
+
+ /** for glBitmap */
+ struct {
+ struct pipe_rasterizer_state rasterizer;
+ struct pipe_sampler_state samplers[2];
+ enum pipe_format tex_format;
+ void *vs;
+ float vertices[4][3][4]; /**< vertex pos + color + texcoord */
+ struct pipe_resource *vbuf;
+ unsigned vbuf_slot; /* next free slot in vbuf */
+ struct bitmap_cache *cache;
+ } bitmap;
+
+ /** for glDraw/CopyPixels */
+ struct {
+ struct gl_fragment_program *shaders[4];
+ void *vert_shaders[2]; /**< ureg shaders */
+ } drawpix;
+
+ /** for glClear */
+ struct {
+ struct pipe_rasterizer_state raster;
+ struct pipe_viewport_state viewport;
+ struct pipe_clip_state clip;
+ void *vs;
+ void *fs;
+ float vertices[4][2][4]; /**< vertex pos + color */
+ struct pipe_resource *vbuf;
+ unsigned vbuf_slot;
+ boolean enable_ds_separate;
+ } clear;
+
+ /** used for anything using util_draw_vertex_buffer */
+ struct pipe_vertex_element velems_util_draw[3];
+
+ void *passthrough_fs; /**< simple pass-through frag shader */
+
+ enum pipe_texture_target internal_target;
+ struct gen_mipmap_state *gen_mipmap;
+ struct blit_state *blit;
+
+ struct cso_context *cso_context;
+
+ int force_msaa;
+ void *winsys_drawable_handle;
+
+ /* User vertex buffers. */
+ struct pipe_resource *user_vb[PIPE_MAX_ATTRIBS];
+ unsigned user_vb_stride[PIPE_MAX_ATTRIBS];
+ unsigned num_user_vbs;
+};
+
+
+/* Need this so that we can implement Mesa callbacks in this module.
+ */
+static INLINE struct st_context *st_context(struct gl_context *ctx)
+{
+ return ctx->st;
+}
+
+
+/**
+ * Wrapper for struct gl_framebuffer.
+ * This is an opaque type to the outside world.
+ */
+struct st_framebuffer
+{
+ struct gl_framebuffer Base;
+ void *Private;
+
+ struct st_framebuffer_iface *iface;
+ enum st_attachment_type statts[ST_ATTACHMENT_COUNT];
+ unsigned num_statts;
+ int32_t revalidate;
+};
+
+
+extern void st_init_driver_functions(struct dd_function_table *functions);
+
+void st_invalidate_state(struct gl_context * ctx, GLuint new_state);
+
+
+
+#define Y_0_TOP 1
+#define Y_0_BOTTOM 2
+
+static INLINE GLuint
+st_fb_orientation(const struct gl_framebuffer *fb)
+{
+ if (fb && fb->Name == 0) {
+ /* Drawing into a window (on-screen buffer).
+ *
+ * Negate Y scale to flip image vertically.
+ * The NDC Y coords prior to viewport transformation are in the range
+ * [y=-1=bottom, y=1=top]
+ * Hardware window coords are in the range [y=0=top, y=H-1=bottom] where
+ * H is the window height.
+ * Use the viewport transformation to invert Y.
+ */
+ return Y_0_TOP;
+ }
+ else {
+ /* Drawing into user-created FBO (very likely a texture).
+ *
+ * For textures, T=0=Bottom, so by extension Y=0=Bottom for rendering.
+ */
+ return Y_0_BOTTOM;
+ }
+}
+
+
+/** clear-alloc a struct-sized object, with casting */
+#define ST_CALLOC_STRUCT(T) (struct T *) calloc(1, sizeof(struct T))
+
+
+extern int
+st_get_msaa(void);
+
+extern struct st_context *
+st_create_context(gl_api api, struct pipe_context *pipe,
+ const struct gl_config *visual,
+ struct st_context *share);
+
+extern void
+st_destroy_context(struct st_context *st);
+
+
+#endif
diff --git a/mesalib/src/mesa/state_tracker/st_draw.c b/mesalib/src/mesa/state_tracker/st_draw.c
index 11ebd067e..7f661d529 100644
--- a/mesalib/src/mesa/state_tracker/st_draw.c
+++ b/mesalib/src/mesa/state_tracker/st_draw.c
@@ -1,759 +1,759 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-/*
- * This file implements the st_draw_vbo() function which is called from
- * Mesa's VBO module. All point/line/triangle rendering is done through
- * this function whether the user called glBegin/End, glDrawArrays,
- * glDrawElements, glEvalMesh, or glCalList, etc.
- *
- * We basically convert the VBO's vertex attribute/array information into
- * Gallium vertex state, bind the vertex buffer objects and call
- * pipe->draw_elements(), pipe->draw_range_elements() or pipe->draw_arrays().
- *
- * Authors:
- * Keith Whitwell <keith@tungstengraphics.com>
- */
-
-
-#include "main/imports.h"
-#include "main/image.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-#include "program/prog_uniform.h"
-
-#include "vbo/vbo.h"
-
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_cb_bufferobjects.h"
-#include "st_draw.h"
-#include "st_program.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-#include "util/u_format.h"
-#include "util/u_prim.h"
-#include "util/u_draw_quad.h"
-#include "draw/draw_context.h"
-#include "cso_cache/cso_context.h"
-
-
-static GLuint double_types[4] = {
- PIPE_FORMAT_R64_FLOAT,
- PIPE_FORMAT_R64G64_FLOAT,
- PIPE_FORMAT_R64G64B64_FLOAT,
- PIPE_FORMAT_R64G64B64A64_FLOAT
-};
-
-static GLuint float_types[4] = {
- PIPE_FORMAT_R32_FLOAT,
- PIPE_FORMAT_R32G32_FLOAT,
- PIPE_FORMAT_R32G32B32_FLOAT,
- PIPE_FORMAT_R32G32B32A32_FLOAT
-};
-
-static GLuint half_float_types[4] = {
- PIPE_FORMAT_R16_FLOAT,
- PIPE_FORMAT_R16G16_FLOAT,
- PIPE_FORMAT_R16G16B16_FLOAT,
- PIPE_FORMAT_R16G16B16A16_FLOAT
-};
-
-static GLuint uint_types_norm[4] = {
- PIPE_FORMAT_R32_UNORM,
- PIPE_FORMAT_R32G32_UNORM,
- PIPE_FORMAT_R32G32B32_UNORM,
- PIPE_FORMAT_R32G32B32A32_UNORM
-};
-
-static GLuint uint_types_scale[4] = {
- PIPE_FORMAT_R32_USCALED,
- PIPE_FORMAT_R32G32_USCALED,
- PIPE_FORMAT_R32G32B32_USCALED,
- PIPE_FORMAT_R32G32B32A32_USCALED
-};
-
-static GLuint int_types_norm[4] = {
- PIPE_FORMAT_R32_SNORM,
- PIPE_FORMAT_R32G32_SNORM,
- PIPE_FORMAT_R32G32B32_SNORM,
- PIPE_FORMAT_R32G32B32A32_SNORM
-};
-
-static GLuint int_types_scale[4] = {
- PIPE_FORMAT_R32_SSCALED,
- PIPE_FORMAT_R32G32_SSCALED,
- PIPE_FORMAT_R32G32B32_SSCALED,
- PIPE_FORMAT_R32G32B32A32_SSCALED
-};
-
-static GLuint ushort_types_norm[4] = {
- PIPE_FORMAT_R16_UNORM,
- PIPE_FORMAT_R16G16_UNORM,
- PIPE_FORMAT_R16G16B16_UNORM,
- PIPE_FORMAT_R16G16B16A16_UNORM
-};
-
-static GLuint ushort_types_scale[4] = {
- PIPE_FORMAT_R16_USCALED,
- PIPE_FORMAT_R16G16_USCALED,
- PIPE_FORMAT_R16G16B16_USCALED,
- PIPE_FORMAT_R16G16B16A16_USCALED
-};
-
-static GLuint short_types_norm[4] = {
- PIPE_FORMAT_R16_SNORM,
- PIPE_FORMAT_R16G16_SNORM,
- PIPE_FORMAT_R16G16B16_SNORM,
- PIPE_FORMAT_R16G16B16A16_SNORM
-};
-
-static GLuint short_types_scale[4] = {
- PIPE_FORMAT_R16_SSCALED,
- PIPE_FORMAT_R16G16_SSCALED,
- PIPE_FORMAT_R16G16B16_SSCALED,
- PIPE_FORMAT_R16G16B16A16_SSCALED
-};
-
-static GLuint ubyte_types_norm[4] = {
- PIPE_FORMAT_R8_UNORM,
- PIPE_FORMAT_R8G8_UNORM,
- PIPE_FORMAT_R8G8B8_UNORM,
- PIPE_FORMAT_R8G8B8A8_UNORM
-};
-
-static GLuint ubyte_types_scale[4] = {
- PIPE_FORMAT_R8_USCALED,
- PIPE_FORMAT_R8G8_USCALED,
- PIPE_FORMAT_R8G8B8_USCALED,
- PIPE_FORMAT_R8G8B8A8_USCALED
-};
-
-static GLuint byte_types_norm[4] = {
- PIPE_FORMAT_R8_SNORM,
- PIPE_FORMAT_R8G8_SNORM,
- PIPE_FORMAT_R8G8B8_SNORM,
- PIPE_FORMAT_R8G8B8A8_SNORM
-};
-
-static GLuint byte_types_scale[4] = {
- PIPE_FORMAT_R8_SSCALED,
- PIPE_FORMAT_R8G8_SSCALED,
- PIPE_FORMAT_R8G8B8_SSCALED,
- PIPE_FORMAT_R8G8B8A8_SSCALED
-};
-
-static GLuint fixed_types[4] = {
- PIPE_FORMAT_R32_FIXED,
- PIPE_FORMAT_R32G32_FIXED,
- PIPE_FORMAT_R32G32B32_FIXED,
- PIPE_FORMAT_R32G32B32A32_FIXED
-};
-
-
-
-/**
- * Return a PIPE_FORMAT_x for the given GL datatype and size.
- */
-GLuint
-st_pipe_vertex_format(GLenum type, GLuint size, GLenum format,
- GLboolean normalized)
-{
- assert((type >= GL_BYTE && type <= GL_DOUBLE) ||
- type == GL_FIXED || type == GL_HALF_FLOAT);
- assert(size >= 1);
- assert(size <= 4);
- assert(format == GL_RGBA || format == GL_BGRA);
-
- if (format == GL_BGRA) {
- /* this is an odd-ball case */
- assert(type == GL_UNSIGNED_BYTE);
- assert(normalized);
- return PIPE_FORMAT_B8G8R8A8_UNORM;
- }
-
- if (normalized) {
- switch (type) {
- case GL_DOUBLE: return double_types[size-1];
- case GL_FLOAT: return float_types[size-1];
- case GL_HALF_FLOAT: return half_float_types[size-1];
- case GL_INT: return int_types_norm[size-1];
- case GL_SHORT: return short_types_norm[size-1];
- case GL_BYTE: return byte_types_norm[size-1];
- case GL_UNSIGNED_INT: return uint_types_norm[size-1];
- case GL_UNSIGNED_SHORT: return ushort_types_norm[size-1];
- case GL_UNSIGNED_BYTE: return ubyte_types_norm[size-1];
- case GL_FIXED: return fixed_types[size-1];
- default: assert(0); return 0;
- }
- }
- else {
- switch (type) {
- case GL_DOUBLE: return double_types[size-1];
- case GL_FLOAT: return float_types[size-1];
- case GL_HALF_FLOAT: return half_float_types[size-1];
- case GL_INT: return int_types_scale[size-1];
- case GL_SHORT: return short_types_scale[size-1];
- case GL_BYTE: return byte_types_scale[size-1];
- case GL_UNSIGNED_INT: return uint_types_scale[size-1];
- case GL_UNSIGNED_SHORT: return ushort_types_scale[size-1];
- case GL_UNSIGNED_BYTE: return ubyte_types_scale[size-1];
- case GL_FIXED: return fixed_types[size-1];
- default: assert(0); return 0;
- }
- }
- return 0; /* silence compiler warning */
-}
-
-
-
-
-
-/**
- * Examine the active arrays to determine if we have interleaved
- * vertex arrays all living in one VBO, or all living in user space.
- * \param userSpace returns whether the arrays are in user space.
- */
-static GLboolean
-is_interleaved_arrays(const struct st_vertex_program *vp,
- const struct st_vp_variant *vpv,
- const struct gl_client_array **arrays)
-{
- GLuint attr;
- const struct gl_buffer_object *firstBufObj = NULL;
- GLint firstStride = -1;
- const GLubyte *client_addr = NULL;
- GLboolean user_memory;
-
- for (attr = 0; attr < vpv->num_inputs; attr++) {
- const GLuint mesaAttr = vp->index_to_input[attr];
- const struct gl_buffer_object *bufObj = arrays[mesaAttr]->BufferObj;
- const GLsizei stride = arrays[mesaAttr]->StrideB; /* in bytes */
-
- if (firstStride < 0) {
- firstStride = stride;
- user_memory = !bufObj || !bufObj->Name;
- }
- else if (firstStride != stride) {
- return GL_FALSE;
- }
-
- if (!bufObj || !bufObj->Name) {
- /* Try to detect if the client-space arrays are
- * "close" to each other.
- */
- if (!user_memory) {
- return GL_FALSE;
- }
- if (!client_addr) {
- client_addr = arrays[mesaAttr]->Ptr;
- }
- else if (abs(arrays[mesaAttr]->Ptr - client_addr) > firstStride) {
- /* arrays start too far apart */
- return GL_FALSE;
- }
- }
- else if (!firstBufObj) {
- if (user_memory) {
- return GL_FALSE;
- }
- firstBufObj = bufObj;
- }
- else if (bufObj != firstBufObj) {
- return GL_FALSE;
- }
- }
-
- return GL_TRUE;
-}
-
-
-/**
- * Set up for drawing interleaved arrays that all live in one VBO
- * or all live in user space.
- * \param vbuffer returns vertex buffer info
- * \param velements returns vertex element info
- */
-static void
-setup_interleaved_attribs(struct gl_context *ctx,
- const struct st_vertex_program *vp,
- const struct st_vp_variant *vpv,
- const struct gl_client_array **arrays,
- struct pipe_vertex_buffer *vbuffer,
- struct pipe_vertex_element velements[],
- unsigned max_index)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- GLuint attr;
- const GLubyte *low_addr = NULL;
-
- /* Find the lowest address. */
- for (attr = 0; attr < vpv->num_inputs; attr++) {
- const GLubyte *start = arrays[vp->index_to_input[attr]]->Ptr;
-
- low_addr = !low_addr ? start : MIN2(low_addr, start);
- }
-
- for (attr = 0; attr < vpv->num_inputs; attr++) {
- const GLuint mesaAttr = vp->index_to_input[attr];
- struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
- struct st_buffer_object *stobj = st_buffer_object(bufobj);
- GLsizei stride = arrays[mesaAttr]->StrideB;
-
- if (attr == 0) {
- if (bufobj && bufobj->Name) {
- vbuffer->buffer = NULL;
- pipe_resource_reference(&vbuffer->buffer, stobj->buffer);
- vbuffer->buffer_offset = pointer_to_offset(low_addr);
- } else {
- vbuffer->buffer =
- pipe_user_buffer_create(pipe->screen, (void*)low_addr,
- stride * (max_index + 1),
- PIPE_BIND_VERTEX_BUFFER);
- vbuffer->buffer_offset = 0;
-
- /* Track user vertex buffers. */
- pipe_resource_reference(&st->user_vb[0], vbuffer->buffer);
- st->user_vb_stride[0] = stride;
- st->num_user_vbs = 1;
- }
- vbuffer->stride = stride; /* in bytes */
- }
-
- velements[attr].src_offset =
- (unsigned) (arrays[mesaAttr]->Ptr - low_addr);
- velements[attr].instance_divisor = arrays[mesaAttr]->InstanceDivisor;
- velements[attr].vertex_buffer_index = 0;
- velements[attr].src_format =
- st_pipe_vertex_format(arrays[mesaAttr]->Type,
- arrays[mesaAttr]->Size,
- arrays[mesaAttr]->Format,
- arrays[mesaAttr]->Normalized);
- assert(velements[attr].src_format);
- }
-}
-
-
-/**
- * Set up a separate pipe_vertex_buffer and pipe_vertex_element for each
- * vertex attribute.
- * \param vbuffer returns vertex buffer info
- * \param velements returns vertex element info
- */
-static void
-setup_non_interleaved_attribs(struct gl_context *ctx,
- const struct st_vertex_program *vp,
- const struct st_vp_variant *vpv,
- const struct gl_client_array **arrays,
- struct pipe_vertex_buffer vbuffer[],
- struct pipe_vertex_element velements[],
- unsigned max_index)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- GLuint attr;
-
- for (attr = 0; attr < vpv->num_inputs; attr++) {
- const GLuint mesaAttr = vp->index_to_input[attr];
- struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
- GLsizei stride = arrays[mesaAttr]->StrideB;
-
- if (bufobj && bufobj->Name) {
- /* Attribute data is in a VBO.
- * Recall that for VBOs, the gl_client_array->Ptr field is
- * really an offset from the start of the VBO, not a pointer.
- */
- struct st_buffer_object *stobj = st_buffer_object(bufobj);
- assert(stobj->buffer);
-
- vbuffer[attr].buffer = NULL;
- pipe_resource_reference(&vbuffer[attr].buffer, stobj->buffer);
- vbuffer[attr].buffer_offset = pointer_to_offset(arrays[mesaAttr]->Ptr);
- }
- else {
- /* wrap user data */
- if (arrays[mesaAttr]->Ptr) {
- vbuffer[attr].buffer =
- pipe_user_buffer_create(pipe->screen,
- (void *) arrays[mesaAttr]->Ptr,
- stride * (max_index + 1),
- PIPE_BIND_VERTEX_BUFFER);
- }
- else {
- /* no array, use ctx->Current.Attrib[] value */
- uint bytes = sizeof(ctx->Current.Attrib[0]);
- vbuffer[attr].buffer =
- pipe_user_buffer_create(pipe->screen,
- (void *) ctx->Current.Attrib[mesaAttr],
- bytes,
- PIPE_BIND_VERTEX_BUFFER);
- stride = 0;
- }
-
- vbuffer[attr].buffer_offset = 0;
-
- /* Track user vertex buffers. */
- pipe_resource_reference(&st->user_vb[attr], vbuffer->buffer);
- st->user_vb_stride[attr] = stride;
- st->num_user_vbs = MAX2(st->num_user_vbs, attr+1);
- }
-
- /* common-case setup */
- vbuffer[attr].stride = stride; /* in bytes */
-
- velements[attr].src_offset = 0;
- velements[attr].instance_divisor = arrays[mesaAttr]->InstanceDivisor;
- velements[attr].vertex_buffer_index = attr;
- velements[attr].src_format
- = st_pipe_vertex_format(arrays[mesaAttr]->Type,
- arrays[mesaAttr]->Size,
- arrays[mesaAttr]->Format,
- arrays[mesaAttr]->Normalized);
- assert(velements[attr].src_format);
- }
-}
-
-
-static void
-setup_index_buffer(struct gl_context *ctx,
- const struct _mesa_index_buffer *ib,
- struct pipe_index_buffer *ibuffer)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
-
- memset(ibuffer, 0, sizeof(*ibuffer));
- if (ib) {
- struct gl_buffer_object *bufobj = ib->obj;
-
- switch (ib->type) {
- case GL_UNSIGNED_INT:
- ibuffer->index_size = 4;
- break;
- case GL_UNSIGNED_SHORT:
- ibuffer->index_size = 2;
- break;
- case GL_UNSIGNED_BYTE:
- ibuffer->index_size = 1;
- break;
- default:
- assert(0);
- return;
- }
-
- /* get/create the index buffer object */
- if (bufobj && bufobj->Name) {
- /* elements/indexes are in a real VBO */
- struct st_buffer_object *stobj = st_buffer_object(bufobj);
- pipe_resource_reference(&ibuffer->buffer, stobj->buffer);
- ibuffer->offset = pointer_to_offset(ib->ptr);
- }
- else {
- /* element/indicies are in user space memory */
- ibuffer->buffer =
- pipe_user_buffer_create(pipe->screen, (void *) ib->ptr,
- ib->count * ibuffer->index_size,
- PIPE_BIND_INDEX_BUFFER);
- }
- }
-}
-
-/**
- * Prior to drawing, check that any uniforms referenced by the
- * current shader have been set. If a uniform has not been set,
- * issue a warning.
- */
-static void
-check_uniforms(struct gl_context *ctx)
-{
- struct gl_shader_program *shProg[3] = {
- ctx->Shader.CurrentVertexProgram,
- ctx->Shader.CurrentGeometryProgram,
- ctx->Shader.CurrentFragmentProgram,
- };
- unsigned j;
-
- for (j = 0; j < 3; j++) {
- unsigned i;
-
- if (shProg[j] == NULL || !shProg[j]->LinkStatus)
- continue;
-
- for (i = 0; i < shProg[j]->Uniforms->NumUniforms; i++) {
- const struct gl_uniform *u = &shProg[j]->Uniforms->Uniforms[i];
- if (!u->Initialized) {
- _mesa_warning(ctx,
- "Using shader with uninitialized uniform: %s",
- u->Name);
- }
- }
- }
-}
-
-
-/**
- * Translate OpenGL primtive type (GL_POINTS, GL_TRIANGLE_STRIP, etc) to
- * the corresponding Gallium type.
- */
-static unsigned
-translate_prim(const struct gl_context *ctx, unsigned prim)
-{
- /* GL prims should match Gallium prims, spot-check a few */
- assert(GL_POINTS == PIPE_PRIM_POINTS);
- assert(GL_QUADS == PIPE_PRIM_QUADS);
- assert(GL_TRIANGLE_STRIP_ADJACENCY == PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY);
-
- /* Avoid quadstrips if it's easy to do so:
- * Note: it's imporant to do the correct trimming if we change the prim type!
- * We do that wherever this function is called.
- */
- if (prim == GL_QUAD_STRIP &&
- ctx->Light.ShadeModel != GL_FLAT &&
- ctx->Polygon.FrontMode == GL_FILL &&
- ctx->Polygon.BackMode == GL_FILL)
- prim = GL_TRIANGLE_STRIP;
-
- return prim;
-}
-
-
-static void
-st_validate_varrays(struct gl_context *ctx,
- const struct gl_client_array **arrays,
- unsigned max_index)
-{
- struct st_context *st = st_context(ctx);
- const struct st_vertex_program *vp;
- const struct st_vp_variant *vpv;
- struct pipe_vertex_buffer vbuffer[PIPE_MAX_SHADER_INPUTS];
- struct pipe_vertex_element velements[PIPE_MAX_ATTRIBS];
- unsigned num_vbuffers, num_velements;
- GLuint attr;
- unsigned i;
-
- /* must get these after state validation! */
- vp = st->vp;
- vpv = st->vp_variant;
-
- memset(velements, 0, sizeof(struct pipe_vertex_element) * vpv->num_inputs);
-
- /* Unreference any user vertex buffers. */
- for (i = 0; i < st->num_user_vbs; i++) {
- pipe_resource_reference(&st->user_vb[i], NULL);
- }
- st->num_user_vbs = 0;
-
- /*
- * Setup the vbuffer[] and velements[] arrays.
- */
- if (is_interleaved_arrays(vp, vpv, arrays)) {
- setup_interleaved_attribs(ctx, vp, vpv, arrays, vbuffer, velements,
- max_index);
- num_vbuffers = 1;
- num_velements = vpv->num_inputs;
- if (num_velements == 0)
- num_vbuffers = 0;
- }
- else {
- setup_non_interleaved_attribs(ctx, vp, vpv, arrays,
- vbuffer, velements, max_index);
- num_vbuffers = vpv->num_inputs;
- num_velements = vpv->num_inputs;
- }
-
- cso_set_vertex_buffers(st->cso_context, num_vbuffers, vbuffer);
- cso_set_vertex_elements(st->cso_context, num_velements, velements);
-
- /* unreference buffers (frees wrapped user-space buffer objects)
- * This is OK, because the pipe driver should reference buffers by itself
- * in set_vertex_buffers. */
- for (attr = 0; attr < num_vbuffers; attr++) {
- pipe_resource_reference(&vbuffer[attr].buffer, NULL);
- assert(!vbuffer[attr].buffer);
- }
-}
-
-
-/**
- * This function gets plugged into the VBO module and is called when
- * we have something to render.
- * Basically, translate the information into the format expected by gallium.
- */
-void
-st_draw_vbo(struct gl_context *ctx,
- const struct gl_client_array **arrays,
- const struct _mesa_prim *prims,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLboolean index_bounds_valid,
- GLuint min_index,
- GLuint max_index)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct pipe_index_buffer ibuffer;
- struct pipe_draw_info info;
- unsigned i;
- GLboolean new_array = GL_TRUE;
- /* Fix this (Bug 34378):
- GLboolean new_array =
- st->dirty.st && (st->dirty.mesa & (_NEW_ARRAY | _NEW_PROGRAM)) != 0;*/
-
- /* Mesa core state should have been validated already */
- assert(ctx->NewState == 0x0);
-
- if (ib) {
- /* Gallium probably doesn't want this in some cases. */
- if (!index_bounds_valid)
- if (!vbo_all_varyings_in_vbos(arrays))
- vbo_get_minmax_index(ctx, prims, ib, &min_index, &max_index);
- } else {
- /* Get min/max index for non-indexed drawing. */
- min_index = ~0;
- max_index = 0;
-
- for (i = 0; i < nr_prims; i++) {
- min_index = MIN2(min_index, prims[i].start);
- max_index = MAX2(max_index, prims[i].start + prims[i].count - 1);
- }
- }
-
- /* Validate state. */
- if (st->dirty.st) {
- GLboolean vertDataEdgeFlags;
-
- /* sanity check for pointer arithmetic below */
- assert(sizeof(arrays[0]->Ptr[0]) == 1);
-
- vertDataEdgeFlags = arrays[VERT_ATTRIB_EDGEFLAG]->BufferObj &&
- arrays[VERT_ATTRIB_EDGEFLAG]->BufferObj->Name;
- if (vertDataEdgeFlags != st->vertdata_edgeflags) {
- st->vertdata_edgeflags = vertDataEdgeFlags;
- st->dirty.st |= ST_NEW_EDGEFLAGS_DATA;
- }
-
- st_validate_state(st);
-
- if (new_array) {
- st_validate_varrays(ctx, arrays, max_index);
- }
-
-#if 0
- if (MESA_VERBOSE & VERBOSE_GLSL) {
- check_uniforms(ctx);
- }
-#else
- (void) check_uniforms;
-#endif
- }
-
- /* Notify the driver that the content of user buffers may have been
- * changed. */
- if (!new_array && st->num_user_vbs) {
- for (i = 0; i < st->num_user_vbs; i++) {
- if (st->user_vb[i]) {
- unsigned stride = st->user_vb_stride[i];
-
- if (stride) {
- pipe->redefine_user_buffer(pipe, st->user_vb[i],
- min_index * stride,
- (max_index + 1 - min_index) * stride);
- } else {
- /* stride == 0 */
- pipe->redefine_user_buffer(pipe, st->user_vb[i],
- 0, st->user_vb[i]->width0);
- }
- }
- }
- }
-
- setup_index_buffer(ctx, ib, &ibuffer);
- pipe->set_index_buffer(pipe, &ibuffer);
-
- util_draw_init_info(&info);
- if (ib) {
- info.indexed = TRUE;
- if (min_index != ~0 && max_index != ~0) {
- info.min_index = min_index;
- info.max_index = max_index;
- }
- }
-
- info.primitive_restart = st->ctx->Array.PrimitiveRestart;
- info.restart_index = st->ctx->Array.RestartIndex;
-
- /* do actual drawing */
- for (i = 0; i < nr_prims; i++) {
- info.mode = translate_prim( ctx, prims[i].mode );
- info.start = prims[i].start;
- info.count = prims[i].count;
- info.instance_count = prims[i].num_instances;
- info.index_bias = prims[i].basevertex;
- if (!ib) {
- info.min_index = info.start;
- info.max_index = info.start + info.count - 1;
- }
-
- if (u_trim_pipe_prim(info.mode, &info.count))
- pipe->draw_vbo(pipe, &info);
- }
-
- pipe_resource_reference(&ibuffer.buffer, NULL);
-}
-
-
-void st_init_draw( struct st_context *st )
-{
- struct gl_context *ctx = st->ctx;
-
- vbo_set_draw_func(ctx, st_draw_vbo);
-
-#if FEATURE_feedback || FEATURE_rastpos
- st->draw = draw_create(st->pipe); /* for selection/feedback */
-
- /* Disable draw options that might convert points/lines to tris, etc.
- * as that would foul-up feedback/selection mode.
- */
- draw_wide_line_threshold(st->draw, 1000.0f);
- draw_wide_point_threshold(st->draw, 1000.0f);
- draw_enable_line_stipple(st->draw, FALSE);
- draw_enable_point_sprites(st->draw, FALSE);
-#endif
-}
-
-
-void st_destroy_draw( struct st_context *st )
-{
-#if FEATURE_feedback || FEATURE_rastpos
- draw_destroy(st->draw);
-#endif
-}
-
-
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+/*
+ * This file implements the st_draw_vbo() function which is called from
+ * Mesa's VBO module. All point/line/triangle rendering is done through
+ * this function whether the user called glBegin/End, glDrawArrays,
+ * glDrawElements, glEvalMesh, or glCalList, etc.
+ *
+ * We basically convert the VBO's vertex attribute/array information into
+ * Gallium vertex state, bind the vertex buffer objects and call
+ * pipe->draw_elements(), pipe->draw_range_elements() or pipe->draw_arrays().
+ *
+ * Authors:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ */
+
+
+#include "main/imports.h"
+#include "main/image.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+#include "program/prog_uniform.h"
+
+#include "vbo/vbo.h"
+
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_cb_bufferobjects.h"
+#include "st_draw.h"
+#include "st_program.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+#include "util/u_format.h"
+#include "util/u_prim.h"
+#include "util/u_draw_quad.h"
+#include "draw/draw_context.h"
+#include "cso_cache/cso_context.h"
+
+
+static GLuint double_types[4] = {
+ PIPE_FORMAT_R64_FLOAT,
+ PIPE_FORMAT_R64G64_FLOAT,
+ PIPE_FORMAT_R64G64B64_FLOAT,
+ PIPE_FORMAT_R64G64B64A64_FLOAT
+};
+
+static GLuint float_types[4] = {
+ PIPE_FORMAT_R32_FLOAT,
+ PIPE_FORMAT_R32G32_FLOAT,
+ PIPE_FORMAT_R32G32B32_FLOAT,
+ PIPE_FORMAT_R32G32B32A32_FLOAT
+};
+
+static GLuint half_float_types[4] = {
+ PIPE_FORMAT_R16_FLOAT,
+ PIPE_FORMAT_R16G16_FLOAT,
+ PIPE_FORMAT_R16G16B16_FLOAT,
+ PIPE_FORMAT_R16G16B16A16_FLOAT
+};
+
+static GLuint uint_types_norm[4] = {
+ PIPE_FORMAT_R32_UNORM,
+ PIPE_FORMAT_R32G32_UNORM,
+ PIPE_FORMAT_R32G32B32_UNORM,
+ PIPE_FORMAT_R32G32B32A32_UNORM
+};
+
+static GLuint uint_types_scale[4] = {
+ PIPE_FORMAT_R32_USCALED,
+ PIPE_FORMAT_R32G32_USCALED,
+ PIPE_FORMAT_R32G32B32_USCALED,
+ PIPE_FORMAT_R32G32B32A32_USCALED
+};
+
+static GLuint int_types_norm[4] = {
+ PIPE_FORMAT_R32_SNORM,
+ PIPE_FORMAT_R32G32_SNORM,
+ PIPE_FORMAT_R32G32B32_SNORM,
+ PIPE_FORMAT_R32G32B32A32_SNORM
+};
+
+static GLuint int_types_scale[4] = {
+ PIPE_FORMAT_R32_SSCALED,
+ PIPE_FORMAT_R32G32_SSCALED,
+ PIPE_FORMAT_R32G32B32_SSCALED,
+ PIPE_FORMAT_R32G32B32A32_SSCALED
+};
+
+static GLuint ushort_types_norm[4] = {
+ PIPE_FORMAT_R16_UNORM,
+ PIPE_FORMAT_R16G16_UNORM,
+ PIPE_FORMAT_R16G16B16_UNORM,
+ PIPE_FORMAT_R16G16B16A16_UNORM
+};
+
+static GLuint ushort_types_scale[4] = {
+ PIPE_FORMAT_R16_USCALED,
+ PIPE_FORMAT_R16G16_USCALED,
+ PIPE_FORMAT_R16G16B16_USCALED,
+ PIPE_FORMAT_R16G16B16A16_USCALED
+};
+
+static GLuint short_types_norm[4] = {
+ PIPE_FORMAT_R16_SNORM,
+ PIPE_FORMAT_R16G16_SNORM,
+ PIPE_FORMAT_R16G16B16_SNORM,
+ PIPE_FORMAT_R16G16B16A16_SNORM
+};
+
+static GLuint short_types_scale[4] = {
+ PIPE_FORMAT_R16_SSCALED,
+ PIPE_FORMAT_R16G16_SSCALED,
+ PIPE_FORMAT_R16G16B16_SSCALED,
+ PIPE_FORMAT_R16G16B16A16_SSCALED
+};
+
+static GLuint ubyte_types_norm[4] = {
+ PIPE_FORMAT_R8_UNORM,
+ PIPE_FORMAT_R8G8_UNORM,
+ PIPE_FORMAT_R8G8B8_UNORM,
+ PIPE_FORMAT_R8G8B8A8_UNORM
+};
+
+static GLuint ubyte_types_scale[4] = {
+ PIPE_FORMAT_R8_USCALED,
+ PIPE_FORMAT_R8G8_USCALED,
+ PIPE_FORMAT_R8G8B8_USCALED,
+ PIPE_FORMAT_R8G8B8A8_USCALED
+};
+
+static GLuint byte_types_norm[4] = {
+ PIPE_FORMAT_R8_SNORM,
+ PIPE_FORMAT_R8G8_SNORM,
+ PIPE_FORMAT_R8G8B8_SNORM,
+ PIPE_FORMAT_R8G8B8A8_SNORM
+};
+
+static GLuint byte_types_scale[4] = {
+ PIPE_FORMAT_R8_SSCALED,
+ PIPE_FORMAT_R8G8_SSCALED,
+ PIPE_FORMAT_R8G8B8_SSCALED,
+ PIPE_FORMAT_R8G8B8A8_SSCALED
+};
+
+static GLuint fixed_types[4] = {
+ PIPE_FORMAT_R32_FIXED,
+ PIPE_FORMAT_R32G32_FIXED,
+ PIPE_FORMAT_R32G32B32_FIXED,
+ PIPE_FORMAT_R32G32B32A32_FIXED
+};
+
+
+
+/**
+ * Return a PIPE_FORMAT_x for the given GL datatype and size.
+ */
+GLuint
+st_pipe_vertex_format(GLenum type, GLuint size, GLenum format,
+ GLboolean normalized)
+{
+ assert((type >= GL_BYTE && type <= GL_DOUBLE) ||
+ type == GL_FIXED || type == GL_HALF_FLOAT);
+ assert(size >= 1);
+ assert(size <= 4);
+ assert(format == GL_RGBA || format == GL_BGRA);
+
+ if (format == GL_BGRA) {
+ /* this is an odd-ball case */
+ assert(type == GL_UNSIGNED_BYTE);
+ assert(normalized);
+ return PIPE_FORMAT_B8G8R8A8_UNORM;
+ }
+
+ if (normalized) {
+ switch (type) {
+ case GL_DOUBLE: return double_types[size-1];
+ case GL_FLOAT: return float_types[size-1];
+ case GL_HALF_FLOAT: return half_float_types[size-1];
+ case GL_INT: return int_types_norm[size-1];
+ case GL_SHORT: return short_types_norm[size-1];
+ case GL_BYTE: return byte_types_norm[size-1];
+ case GL_UNSIGNED_INT: return uint_types_norm[size-1];
+ case GL_UNSIGNED_SHORT: return ushort_types_norm[size-1];
+ case GL_UNSIGNED_BYTE: return ubyte_types_norm[size-1];
+ case GL_FIXED: return fixed_types[size-1];
+ default: assert(0); return 0;
+ }
+ }
+ else {
+ switch (type) {
+ case GL_DOUBLE: return double_types[size-1];
+ case GL_FLOAT: return float_types[size-1];
+ case GL_HALF_FLOAT: return half_float_types[size-1];
+ case GL_INT: return int_types_scale[size-1];
+ case GL_SHORT: return short_types_scale[size-1];
+ case GL_BYTE: return byte_types_scale[size-1];
+ case GL_UNSIGNED_INT: return uint_types_scale[size-1];
+ case GL_UNSIGNED_SHORT: return ushort_types_scale[size-1];
+ case GL_UNSIGNED_BYTE: return ubyte_types_scale[size-1];
+ case GL_FIXED: return fixed_types[size-1];
+ default: assert(0); return 0;
+ }
+ }
+ return 0; /* silence compiler warning */
+}
+
+
+
+
+
+/**
+ * Examine the active arrays to determine if we have interleaved
+ * vertex arrays all living in one VBO, or all living in user space.
+ * \param userSpace returns whether the arrays are in user space.
+ */
+static GLboolean
+is_interleaved_arrays(const struct st_vertex_program *vp,
+ const struct st_vp_variant *vpv,
+ const struct gl_client_array **arrays)
+{
+ GLuint attr;
+ const struct gl_buffer_object *firstBufObj = NULL;
+ GLint firstStride = -1;
+ const GLubyte *client_addr = NULL;
+ GLboolean user_memory;
+
+ for (attr = 0; attr < vpv->num_inputs; attr++) {
+ const GLuint mesaAttr = vp->index_to_input[attr];
+ const struct gl_buffer_object *bufObj = arrays[mesaAttr]->BufferObj;
+ const GLsizei stride = arrays[mesaAttr]->StrideB; /* in bytes */
+
+ if (firstStride < 0) {
+ firstStride = stride;
+ user_memory = !bufObj || !bufObj->Name;
+ }
+ else if (firstStride != stride) {
+ return GL_FALSE;
+ }
+
+ if (!bufObj || !bufObj->Name) {
+ /* Try to detect if the client-space arrays are
+ * "close" to each other.
+ */
+ if (!user_memory) {
+ return GL_FALSE;
+ }
+ if (!client_addr) {
+ client_addr = arrays[mesaAttr]->Ptr;
+ }
+ else if (abs(arrays[mesaAttr]->Ptr - client_addr) > firstStride) {
+ /* arrays start too far apart */
+ return GL_FALSE;
+ }
+ }
+ else if (!firstBufObj) {
+ if (user_memory) {
+ return GL_FALSE;
+ }
+ firstBufObj = bufObj;
+ }
+ else if (bufObj != firstBufObj) {
+ return GL_FALSE;
+ }
+ }
+
+ return GL_TRUE;
+}
+
+
+/**
+ * Set up for drawing interleaved arrays that all live in one VBO
+ * or all live in user space.
+ * \param vbuffer returns vertex buffer info
+ * \param velements returns vertex element info
+ */
+static void
+setup_interleaved_attribs(struct gl_context *ctx,
+ const struct st_vertex_program *vp,
+ const struct st_vp_variant *vpv,
+ const struct gl_client_array **arrays,
+ struct pipe_vertex_buffer *vbuffer,
+ struct pipe_vertex_element velements[],
+ unsigned max_index)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ GLuint attr;
+ const GLubyte *low_addr = NULL;
+
+ /* Find the lowest address. */
+ for (attr = 0; attr < vpv->num_inputs; attr++) {
+ const GLubyte *start = arrays[vp->index_to_input[attr]]->Ptr;
+
+ low_addr = !low_addr ? start : MIN2(low_addr, start);
+ }
+
+ for (attr = 0; attr < vpv->num_inputs; attr++) {
+ const GLuint mesaAttr = vp->index_to_input[attr];
+ struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
+ struct st_buffer_object *stobj = st_buffer_object(bufobj);
+ GLsizei stride = arrays[mesaAttr]->StrideB;
+
+ if (attr == 0) {
+ if (bufobj && bufobj->Name) {
+ vbuffer->buffer = NULL;
+ pipe_resource_reference(&vbuffer->buffer, stobj->buffer);
+ vbuffer->buffer_offset = pointer_to_offset(low_addr);
+ } else {
+ vbuffer->buffer =
+ pipe_user_buffer_create(pipe->screen, (void*)low_addr,
+ stride * (max_index + 1),
+ PIPE_BIND_VERTEX_BUFFER);
+ vbuffer->buffer_offset = 0;
+
+ /* Track user vertex buffers. */
+ pipe_resource_reference(&st->user_vb[0], vbuffer->buffer);
+ st->user_vb_stride[0] = stride;
+ st->num_user_vbs = 1;
+ }
+ vbuffer->stride = stride; /* in bytes */
+ }
+
+ velements[attr].src_offset =
+ (unsigned) (arrays[mesaAttr]->Ptr - low_addr);
+ velements[attr].instance_divisor = arrays[mesaAttr]->InstanceDivisor;
+ velements[attr].vertex_buffer_index = 0;
+ velements[attr].src_format =
+ st_pipe_vertex_format(arrays[mesaAttr]->Type,
+ arrays[mesaAttr]->Size,
+ arrays[mesaAttr]->Format,
+ arrays[mesaAttr]->Normalized);
+ assert(velements[attr].src_format);
+ }
+}
+
+
+/**
+ * Set up a separate pipe_vertex_buffer and pipe_vertex_element for each
+ * vertex attribute.
+ * \param vbuffer returns vertex buffer info
+ * \param velements returns vertex element info
+ */
+static void
+setup_non_interleaved_attribs(struct gl_context *ctx,
+ const struct st_vertex_program *vp,
+ const struct st_vp_variant *vpv,
+ const struct gl_client_array **arrays,
+ struct pipe_vertex_buffer vbuffer[],
+ struct pipe_vertex_element velements[],
+ unsigned max_index)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ GLuint attr;
+
+ for (attr = 0; attr < vpv->num_inputs; attr++) {
+ const GLuint mesaAttr = vp->index_to_input[attr];
+ struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
+ GLsizei stride = arrays[mesaAttr]->StrideB;
+
+ if (bufobj && bufobj->Name) {
+ /* Attribute data is in a VBO.
+ * Recall that for VBOs, the gl_client_array->Ptr field is
+ * really an offset from the start of the VBO, not a pointer.
+ */
+ struct st_buffer_object *stobj = st_buffer_object(bufobj);
+ assert(stobj->buffer);
+
+ vbuffer[attr].buffer = NULL;
+ pipe_resource_reference(&vbuffer[attr].buffer, stobj->buffer);
+ vbuffer[attr].buffer_offset = pointer_to_offset(arrays[mesaAttr]->Ptr);
+ }
+ else {
+ /* wrap user data */
+ if (arrays[mesaAttr]->Ptr) {
+ vbuffer[attr].buffer =
+ pipe_user_buffer_create(pipe->screen,
+ (void *) arrays[mesaAttr]->Ptr,
+ stride * (max_index + 1),
+ PIPE_BIND_VERTEX_BUFFER);
+ }
+ else {
+ /* no array, use ctx->Current.Attrib[] value */
+ uint bytes = sizeof(ctx->Current.Attrib[0]);
+ vbuffer[attr].buffer =
+ pipe_user_buffer_create(pipe->screen,
+ (void *) ctx->Current.Attrib[mesaAttr],
+ bytes,
+ PIPE_BIND_VERTEX_BUFFER);
+ stride = 0;
+ }
+
+ vbuffer[attr].buffer_offset = 0;
+
+ /* Track user vertex buffers. */
+ pipe_resource_reference(&st->user_vb[attr], vbuffer->buffer);
+ st->user_vb_stride[attr] = stride;
+ st->num_user_vbs = MAX2(st->num_user_vbs, attr+1);
+ }
+
+ /* common-case setup */
+ vbuffer[attr].stride = stride; /* in bytes */
+
+ velements[attr].src_offset = 0;
+ velements[attr].instance_divisor = arrays[mesaAttr]->InstanceDivisor;
+ velements[attr].vertex_buffer_index = attr;
+ velements[attr].src_format
+ = st_pipe_vertex_format(arrays[mesaAttr]->Type,
+ arrays[mesaAttr]->Size,
+ arrays[mesaAttr]->Format,
+ arrays[mesaAttr]->Normalized);
+ assert(velements[attr].src_format);
+ }
+}
+
+
+static void
+setup_index_buffer(struct gl_context *ctx,
+ const struct _mesa_index_buffer *ib,
+ struct pipe_index_buffer *ibuffer)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+
+ memset(ibuffer, 0, sizeof(*ibuffer));
+ if (ib) {
+ struct gl_buffer_object *bufobj = ib->obj;
+
+ switch (ib->type) {
+ case GL_UNSIGNED_INT:
+ ibuffer->index_size = 4;
+ break;
+ case GL_UNSIGNED_SHORT:
+ ibuffer->index_size = 2;
+ break;
+ case GL_UNSIGNED_BYTE:
+ ibuffer->index_size = 1;
+ break;
+ default:
+ assert(0);
+ return;
+ }
+
+ /* get/create the index buffer object */
+ if (bufobj && bufobj->Name) {
+ /* elements/indexes are in a real VBO */
+ struct st_buffer_object *stobj = st_buffer_object(bufobj);
+ pipe_resource_reference(&ibuffer->buffer, stobj->buffer);
+ ibuffer->offset = pointer_to_offset(ib->ptr);
+ }
+ else {
+ /* element/indicies are in user space memory */
+ ibuffer->buffer =
+ pipe_user_buffer_create(pipe->screen, (void *) ib->ptr,
+ ib->count * ibuffer->index_size,
+ PIPE_BIND_INDEX_BUFFER);
+ }
+ }
+}
+
+/**
+ * Prior to drawing, check that any uniforms referenced by the
+ * current shader have been set. If a uniform has not been set,
+ * issue a warning.
+ */
+static void
+check_uniforms(struct gl_context *ctx)
+{
+ struct gl_shader_program *shProg[3] = {
+ ctx->Shader.CurrentVertexProgram,
+ ctx->Shader.CurrentGeometryProgram,
+ ctx->Shader.CurrentFragmentProgram,
+ };
+ unsigned j;
+
+ for (j = 0; j < 3; j++) {
+ unsigned i;
+
+ if (shProg[j] == NULL || !shProg[j]->LinkStatus)
+ continue;
+
+ for (i = 0; i < shProg[j]->Uniforms->NumUniforms; i++) {
+ const struct gl_uniform *u = &shProg[j]->Uniforms->Uniforms[i];
+ if (!u->Initialized) {
+ _mesa_warning(ctx,
+ "Using shader with uninitialized uniform: %s",
+ u->Name);
+ }
+ }
+ }
+}
+
+
+/**
+ * Translate OpenGL primtive type (GL_POINTS, GL_TRIANGLE_STRIP, etc) to
+ * the corresponding Gallium type.
+ */
+static unsigned
+translate_prim(const struct gl_context *ctx, unsigned prim)
+{
+ /* GL prims should match Gallium prims, spot-check a few */
+ assert(GL_POINTS == PIPE_PRIM_POINTS);
+ assert(GL_QUADS == PIPE_PRIM_QUADS);
+ assert(GL_TRIANGLE_STRIP_ADJACENCY == PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY);
+
+ /* Avoid quadstrips if it's easy to do so:
+ * Note: it's imporant to do the correct trimming if we change the prim type!
+ * We do that wherever this function is called.
+ */
+ if (prim == GL_QUAD_STRIP &&
+ ctx->Light.ShadeModel != GL_FLAT &&
+ ctx->Polygon.FrontMode == GL_FILL &&
+ ctx->Polygon.BackMode == GL_FILL)
+ prim = GL_TRIANGLE_STRIP;
+
+ return prim;
+}
+
+
+static void
+st_validate_varrays(struct gl_context *ctx,
+ const struct gl_client_array **arrays,
+ unsigned max_index)
+{
+ struct st_context *st = st_context(ctx);
+ const struct st_vertex_program *vp;
+ const struct st_vp_variant *vpv;
+ struct pipe_vertex_buffer vbuffer[PIPE_MAX_SHADER_INPUTS];
+ struct pipe_vertex_element velements[PIPE_MAX_ATTRIBS];
+ unsigned num_vbuffers, num_velements;
+ GLuint attr;
+ unsigned i;
+
+ /* must get these after state validation! */
+ vp = st->vp;
+ vpv = st->vp_variant;
+
+ memset(velements, 0, sizeof(struct pipe_vertex_element) * vpv->num_inputs);
+
+ /* Unreference any user vertex buffers. */
+ for (i = 0; i < st->num_user_vbs; i++) {
+ pipe_resource_reference(&st->user_vb[i], NULL);
+ }
+ st->num_user_vbs = 0;
+
+ /*
+ * Setup the vbuffer[] and velements[] arrays.
+ */
+ if (is_interleaved_arrays(vp, vpv, arrays)) {
+ setup_interleaved_attribs(ctx, vp, vpv, arrays, vbuffer, velements,
+ max_index);
+ num_vbuffers = 1;
+ num_velements = vpv->num_inputs;
+ if (num_velements == 0)
+ num_vbuffers = 0;
+ }
+ else {
+ setup_non_interleaved_attribs(ctx, vp, vpv, arrays,
+ vbuffer, velements, max_index);
+ num_vbuffers = vpv->num_inputs;
+ num_velements = vpv->num_inputs;
+ }
+
+ cso_set_vertex_buffers(st->cso_context, num_vbuffers, vbuffer);
+ cso_set_vertex_elements(st->cso_context, num_velements, velements);
+
+ /* unreference buffers (frees wrapped user-space buffer objects)
+ * This is OK, because the pipe driver should reference buffers by itself
+ * in set_vertex_buffers. */
+ for (attr = 0; attr < num_vbuffers; attr++) {
+ pipe_resource_reference(&vbuffer[attr].buffer, NULL);
+ assert(!vbuffer[attr].buffer);
+ }
+}
+
+
+/**
+ * This function gets plugged into the VBO module and is called when
+ * we have something to render.
+ * Basically, translate the information into the format expected by gallium.
+ */
+void
+st_draw_vbo(struct gl_context *ctx,
+ const struct gl_client_array **arrays,
+ const struct _mesa_prim *prims,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLboolean index_bounds_valid,
+ GLuint min_index,
+ GLuint max_index)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_index_buffer ibuffer;
+ struct pipe_draw_info info;
+ unsigned i;
+ GLboolean new_array = GL_TRUE;
+ /* Fix this (Bug 34378):
+ GLboolean new_array =
+ st->dirty.st && (st->dirty.mesa & (_NEW_ARRAY | _NEW_PROGRAM)) != 0;*/
+
+ /* Mesa core state should have been validated already */
+ assert(ctx->NewState == 0x0);
+
+ if (ib) {
+ /* Gallium probably doesn't want this in some cases. */
+ if (!index_bounds_valid)
+ if (!vbo_all_varyings_in_vbos(arrays))
+ vbo_get_minmax_index(ctx, prims, ib, &min_index, &max_index);
+ } else {
+ /* Get min/max index for non-indexed drawing. */
+ min_index = ~0;
+ max_index = 0;
+
+ for (i = 0; i < nr_prims; i++) {
+ min_index = MIN2(min_index, prims[i].start);
+ max_index = MAX2(max_index, prims[i].start + prims[i].count - 1);
+ }
+ }
+
+ /* Validate state. */
+ if (st->dirty.st) {
+ GLboolean vertDataEdgeFlags;
+
+ /* sanity check for pointer arithmetic below */
+ assert(sizeof(arrays[0]->Ptr[0]) == 1);
+
+ vertDataEdgeFlags = arrays[VERT_ATTRIB_EDGEFLAG]->BufferObj &&
+ arrays[VERT_ATTRIB_EDGEFLAG]->BufferObj->Name;
+ if (vertDataEdgeFlags != st->vertdata_edgeflags) {
+ st->vertdata_edgeflags = vertDataEdgeFlags;
+ st->dirty.st |= ST_NEW_EDGEFLAGS_DATA;
+ }
+
+ st_validate_state(st);
+
+ if (new_array) {
+ st_validate_varrays(ctx, arrays, max_index);
+ }
+
+#if 0
+ if (MESA_VERBOSE & VERBOSE_GLSL) {
+ check_uniforms(ctx);
+ }
+#else
+ (void) check_uniforms;
+#endif
+ }
+
+ /* Notify the driver that the content of user buffers may have been
+ * changed. */
+ if (!new_array && st->num_user_vbs) {
+ for (i = 0; i < st->num_user_vbs; i++) {
+ if (st->user_vb[i]) {
+ unsigned stride = st->user_vb_stride[i];
+
+ if (stride) {
+ pipe->redefine_user_buffer(pipe, st->user_vb[i],
+ min_index * stride,
+ (max_index + 1 - min_index) * stride);
+ } else {
+ /* stride == 0 */
+ pipe->redefine_user_buffer(pipe, st->user_vb[i],
+ 0, st->user_vb[i]->width0);
+ }
+ }
+ }
+ }
+
+ setup_index_buffer(ctx, ib, &ibuffer);
+ pipe->set_index_buffer(pipe, &ibuffer);
+
+ util_draw_init_info(&info);
+ if (ib) {
+ info.indexed = TRUE;
+ if (min_index != ~0 && max_index != ~0) {
+ info.min_index = min_index;
+ info.max_index = max_index;
+ }
+ }
+
+ info.primitive_restart = st->ctx->Array.PrimitiveRestart;
+ info.restart_index = st->ctx->Array.RestartIndex;
+
+ /* do actual drawing */
+ for (i = 0; i < nr_prims; i++) {
+ info.mode = translate_prim( ctx, prims[i].mode );
+ info.start = prims[i].start;
+ info.count = prims[i].count;
+ info.instance_count = prims[i].num_instances;
+ info.index_bias = prims[i].basevertex;
+ if (!ib) {
+ info.min_index = info.start;
+ info.max_index = info.start + info.count - 1;
+ }
+
+ if (u_trim_pipe_prim(info.mode, &info.count))
+ pipe->draw_vbo(pipe, &info);
+ }
+
+ pipe_resource_reference(&ibuffer.buffer, NULL);
+}
+
+
+void st_init_draw( struct st_context *st )
+{
+ struct gl_context *ctx = st->ctx;
+
+ vbo_set_draw_func(ctx, st_draw_vbo);
+
+#if FEATURE_feedback || FEATURE_rastpos
+ st->draw = draw_create(st->pipe); /* for selection/feedback */
+
+ /* Disable draw options that might convert points/lines to tris, etc.
+ * as that would foul-up feedback/selection mode.
+ */
+ draw_wide_line_threshold(st->draw, 1000.0f);
+ draw_wide_point_threshold(st->draw, 1000.0f);
+ draw_enable_line_stipple(st->draw, FALSE);
+ draw_enable_point_sprites(st->draw, FALSE);
+#endif
+}
+
+
+void st_destroy_draw( struct st_context *st )
+{
+#if FEATURE_feedback || FEATURE_rastpos
+ draw_destroy(st->draw);
+#endif
+}
+
+
diff --git a/mesalib/src/mesa/state_tracker/st_draw_feedback.c b/mesalib/src/mesa/state_tracker/st_draw_feedback.c
index 1e1220bfe..f0734eae0 100644
--- a/mesalib/src/mesa/state_tracker/st_draw_feedback.c
+++ b/mesalib/src/mesa/state_tracker/st_draw_feedback.c
@@ -1,277 +1,277 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-#include "main/imports.h"
-#include "main/image.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-
-#include "vbo/vbo.h"
-
-#include "st_context.h"
-#include "st_atom.h"
-#include "st_cb_bufferobjects.h"
-#include "st_draw.h"
-#include "st_program.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-
-#include "draw/draw_private.h"
-#include "draw/draw_context.h"
-
-
-#if FEATURE_feedback || FEATURE_rastpos
-
-/**
- * Set the (private) draw module's post-transformed vertex format when in
- * GL_SELECT or GL_FEEDBACK mode or for glRasterPos.
- */
-static void
-set_feedback_vertex_format(struct gl_context *ctx)
-{
-#if 0
- struct st_context *st = st_context(ctx);
- struct vertex_info vinfo;
- GLuint i;
-
- memset(&vinfo, 0, sizeof(vinfo));
-
- if (ctx->RenderMode == GL_SELECT) {
- assert(ctx->RenderMode == GL_SELECT);
- vinfo.num_attribs = 1;
- vinfo.format[0] = FORMAT_4F;
- vinfo.interp_mode[0] = INTERP_LINEAR;
- }
- else {
- /* GL_FEEDBACK, or glRasterPos */
- /* emit all attribs (pos, color, texcoord) as GLfloat[4] */
- vinfo.num_attribs = st->state.vs->cso->state.num_outputs;
- for (i = 0; i < vinfo.num_attribs; i++) {
- vinfo.format[i] = FORMAT_4F;
- vinfo.interp_mode[i] = INTERP_LINEAR;
- }
- }
-
- draw_set_vertex_info(st->draw, &vinfo);
-#endif
-}
-
-
-/**
- * Called by VBO to draw arrays when in selection or feedback mode and
- * to implement glRasterPos.
- * This is very much like the normal draw_vbo() function above.
- * Look at code refactoring some day.
- * Might move this into the failover module some day.
- */
-void
-st_feedback_draw_vbo(struct gl_context *ctx,
- const struct gl_client_array **arrays,
- const struct _mesa_prim *prims,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLboolean index_bounds_valid,
- GLuint min_index,
- GLuint max_index)
-{
- struct st_context *st = st_context(ctx);
- struct pipe_context *pipe = st->pipe;
- struct draw_context *draw = st->draw;
- const struct st_vertex_program *vp;
- const struct pipe_shader_state *vs;
- struct pipe_vertex_buffer vbuffers[PIPE_MAX_SHADER_INPUTS];
- struct pipe_vertex_element velements[PIPE_MAX_ATTRIBS];
- struct pipe_index_buffer ibuffer;
- struct pipe_transfer *vb_transfer[PIPE_MAX_ATTRIBS];
- struct pipe_transfer *ib_transfer = NULL;
- GLuint attr, i;
- const void *mapped_indices = NULL;
-
- assert(draw);
-
- st_validate_state(st);
-
- if (!index_bounds_valid)
- vbo_get_minmax_index(ctx, prims, ib, &min_index, &max_index);
-
- /* must get these after state validation! */
- vp = st->vp;
- vs = &st->vp_variant->tgsi;
-
- if (!st->vp_variant->draw_shader) {
- st->vp_variant->draw_shader = draw_create_vertex_shader(draw, vs);
- }
-
- /*
- * Set up the draw module's state.
- *
- * We'd like to do this less frequently, but the normal state-update
- * code sends state updates to the pipe, not to our private draw module.
- */
- assert(draw);
- draw_set_viewport_state(draw, &st->state.viewport);
- draw_set_clip_state(draw, &st->state.clip);
- draw_set_rasterizer_state(draw, &st->state.rasterizer, NULL);
- draw_bind_vertex_shader(draw, st->vp_variant->draw_shader);
- set_feedback_vertex_format(ctx);
-
- /* loop over TGSI shader inputs to determine vertex buffer
- * and attribute info
- */
- for (attr = 0; attr < vp->num_inputs; attr++) {
- const GLuint mesaAttr = vp->index_to_input[attr];
- struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
- void *map;
-
- if (bufobj && bufobj->Name) {
- /* Attribute data is in a VBO.
- * Recall that for VBOs, the gl_client_array->Ptr field is
- * really an offset from the start of the VBO, not a pointer.
- */
- struct st_buffer_object *stobj = st_buffer_object(bufobj);
- assert(stobj->buffer);
-
- vbuffers[attr].buffer = NULL;
- pipe_resource_reference(&vbuffers[attr].buffer, stobj->buffer);
- vbuffers[attr].buffer_offset = pointer_to_offset(arrays[0]->Ptr);
- velements[attr].src_offset = arrays[mesaAttr]->Ptr - arrays[0]->Ptr;
- }
- else {
- /* attribute data is in user-space memory, not a VBO */
- uint bytes = (arrays[mesaAttr]->Size
- * _mesa_sizeof_type(arrays[mesaAttr]->Type)
- * (max_index + 1));
-
- /* wrap user data */
- vbuffers[attr].buffer
- = pipe_user_buffer_create(pipe->screen, (void *) arrays[mesaAttr]->Ptr,
- bytes,
- PIPE_BIND_VERTEX_BUFFER);
- vbuffers[attr].buffer_offset = 0;
- velements[attr].src_offset = 0;
- }
-
- /* common-case setup */
- vbuffers[attr].stride = arrays[mesaAttr]->StrideB; /* in bytes */
- velements[attr].instance_divisor = 0;
- velements[attr].vertex_buffer_index = attr;
- velements[attr].src_format =
- st_pipe_vertex_format(arrays[mesaAttr]->Type,
- arrays[mesaAttr]->Size,
- arrays[mesaAttr]->Format,
- arrays[mesaAttr]->Normalized);
- assert(velements[attr].src_format);
-
- /* tell draw about this attribute */
-#if 0
- draw_set_vertex_buffer(draw, attr, &vbuffer[attr]);
-#endif
-
- /* map the attrib buffer */
- map = pipe_buffer_map(pipe, vbuffers[attr].buffer,
- PIPE_TRANSFER_READ,
- &vb_transfer[attr]);
- draw_set_mapped_vertex_buffer(draw, attr, map);
- }
-
- draw_set_vertex_buffers(draw, vp->num_inputs, vbuffers);
- draw_set_vertex_elements(draw, vp->num_inputs, velements);
-
- memset(&ibuffer, 0, sizeof(ibuffer));
- if (ib) {
- struct gl_buffer_object *bufobj = ib->obj;
-
- switch (ib->type) {
- case GL_UNSIGNED_INT:
- ibuffer.index_size = 4;
- break;
- case GL_UNSIGNED_SHORT:
- ibuffer.index_size = 2;
- break;
- case GL_UNSIGNED_BYTE:
- ibuffer.index_size = 1;
- break;
- default:
- assert(0);
- goto out_unref_vertex;
- }
-
- if (bufobj && bufobj->Name) {
- struct st_buffer_object *stobj = st_buffer_object(bufobj);
-
- pipe_resource_reference(&ibuffer.buffer, stobj->buffer);
- ibuffer.offset = pointer_to_offset(ib->ptr);
-
- mapped_indices = pipe_buffer_map(pipe, stobj->buffer,
- PIPE_TRANSFER_READ, &ib_transfer);
- }
- else {
- /* skip setting ibuffer.buffer as the draw module does not use it */
- mapped_indices = ib->ptr;
- }
-
- draw_set_index_buffer(draw, &ibuffer);
- draw_set_mapped_index_buffer(draw, mapped_indices);
- }
-
- /* set the constant buffer */
- draw_set_mapped_constant_buffer(st->draw, PIPE_SHADER_VERTEX, 0,
- st->state.constants[PIPE_SHADER_VERTEX].ptr,
- st->state.constants[PIPE_SHADER_VERTEX].size);
-
-
- /* draw here */
- for (i = 0; i < nr_prims; i++) {
- draw_arrays(draw, prims[i].mode, prims[i].start, prims[i].count);
- }
-
-
- /*
- * unmap vertex/index buffers
- */
- if (ib) {
- draw_set_mapped_index_buffer(draw, NULL);
- draw_set_index_buffer(draw, NULL);
-
- if (ib_transfer)
- pipe_buffer_unmap(pipe, ib_transfer);
- pipe_resource_reference(&ibuffer.buffer, NULL);
- }
-
- out_unref_vertex:
- for (attr = 0; attr < vp->num_inputs; attr++) {
- pipe_buffer_unmap(pipe, vb_transfer[attr]);
- draw_set_mapped_vertex_buffer(draw, attr, NULL);
- pipe_resource_reference(&vbuffers[attr].buffer, NULL);
- }
- draw_set_vertex_buffers(draw, 0, NULL);
-}
-
-#endif /* FEATURE_feedback || FEATURE_rastpos */
-
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+#include "main/imports.h"
+#include "main/image.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+
+#include "vbo/vbo.h"
+
+#include "st_context.h"
+#include "st_atom.h"
+#include "st_cb_bufferobjects.h"
+#include "st_draw.h"
+#include "st_program.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+
+#include "draw/draw_private.h"
+#include "draw/draw_context.h"
+
+
+#if FEATURE_feedback || FEATURE_rastpos
+
+/**
+ * Set the (private) draw module's post-transformed vertex format when in
+ * GL_SELECT or GL_FEEDBACK mode or for glRasterPos.
+ */
+static void
+set_feedback_vertex_format(struct gl_context *ctx)
+{
+#if 0
+ struct st_context *st = st_context(ctx);
+ struct vertex_info vinfo;
+ GLuint i;
+
+ memset(&vinfo, 0, sizeof(vinfo));
+
+ if (ctx->RenderMode == GL_SELECT) {
+ assert(ctx->RenderMode == GL_SELECT);
+ vinfo.num_attribs = 1;
+ vinfo.format[0] = FORMAT_4F;
+ vinfo.interp_mode[0] = INTERP_LINEAR;
+ }
+ else {
+ /* GL_FEEDBACK, or glRasterPos */
+ /* emit all attribs (pos, color, texcoord) as GLfloat[4] */
+ vinfo.num_attribs = st->state.vs->cso->state.num_outputs;
+ for (i = 0; i < vinfo.num_attribs; i++) {
+ vinfo.format[i] = FORMAT_4F;
+ vinfo.interp_mode[i] = INTERP_LINEAR;
+ }
+ }
+
+ draw_set_vertex_info(st->draw, &vinfo);
+#endif
+}
+
+
+/**
+ * Called by VBO to draw arrays when in selection or feedback mode and
+ * to implement glRasterPos.
+ * This is very much like the normal draw_vbo() function above.
+ * Look at code refactoring some day.
+ * Might move this into the failover module some day.
+ */
+void
+st_feedback_draw_vbo(struct gl_context *ctx,
+ const struct gl_client_array **arrays,
+ const struct _mesa_prim *prims,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLboolean index_bounds_valid,
+ GLuint min_index,
+ GLuint max_index)
+{
+ struct st_context *st = st_context(ctx);
+ struct pipe_context *pipe = st->pipe;
+ struct draw_context *draw = st->draw;
+ const struct st_vertex_program *vp;
+ const struct pipe_shader_state *vs;
+ struct pipe_vertex_buffer vbuffers[PIPE_MAX_SHADER_INPUTS];
+ struct pipe_vertex_element velements[PIPE_MAX_ATTRIBS];
+ struct pipe_index_buffer ibuffer;
+ struct pipe_transfer *vb_transfer[PIPE_MAX_ATTRIBS];
+ struct pipe_transfer *ib_transfer = NULL;
+ GLuint attr, i;
+ const void *mapped_indices = NULL;
+
+ assert(draw);
+
+ st_validate_state(st);
+
+ if (!index_bounds_valid)
+ vbo_get_minmax_index(ctx, prims, ib, &min_index, &max_index);
+
+ /* must get these after state validation! */
+ vp = st->vp;
+ vs = &st->vp_variant->tgsi;
+
+ if (!st->vp_variant->draw_shader) {
+ st->vp_variant->draw_shader = draw_create_vertex_shader(draw, vs);
+ }
+
+ /*
+ * Set up the draw module's state.
+ *
+ * We'd like to do this less frequently, but the normal state-update
+ * code sends state updates to the pipe, not to our private draw module.
+ */
+ assert(draw);
+ draw_set_viewport_state(draw, &st->state.viewport);
+ draw_set_clip_state(draw, &st->state.clip);
+ draw_set_rasterizer_state(draw, &st->state.rasterizer, NULL);
+ draw_bind_vertex_shader(draw, st->vp_variant->draw_shader);
+ set_feedback_vertex_format(ctx);
+
+ /* loop over TGSI shader inputs to determine vertex buffer
+ * and attribute info
+ */
+ for (attr = 0; attr < vp->num_inputs; attr++) {
+ const GLuint mesaAttr = vp->index_to_input[attr];
+ struct gl_buffer_object *bufobj = arrays[mesaAttr]->BufferObj;
+ void *map;
+
+ if (bufobj && bufobj->Name) {
+ /* Attribute data is in a VBO.
+ * Recall that for VBOs, the gl_client_array->Ptr field is
+ * really an offset from the start of the VBO, not a pointer.
+ */
+ struct st_buffer_object *stobj = st_buffer_object(bufobj);
+ assert(stobj->buffer);
+
+ vbuffers[attr].buffer = NULL;
+ pipe_resource_reference(&vbuffers[attr].buffer, stobj->buffer);
+ vbuffers[attr].buffer_offset = pointer_to_offset(arrays[0]->Ptr);
+ velements[attr].src_offset = arrays[mesaAttr]->Ptr - arrays[0]->Ptr;
+ }
+ else {
+ /* attribute data is in user-space memory, not a VBO */
+ uint bytes = (arrays[mesaAttr]->Size
+ * _mesa_sizeof_type(arrays[mesaAttr]->Type)
+ * (max_index + 1));
+
+ /* wrap user data */
+ vbuffers[attr].buffer
+ = pipe_user_buffer_create(pipe->screen, (void *) arrays[mesaAttr]->Ptr,
+ bytes,
+ PIPE_BIND_VERTEX_BUFFER);
+ vbuffers[attr].buffer_offset = 0;
+ velements[attr].src_offset = 0;
+ }
+
+ /* common-case setup */
+ vbuffers[attr].stride = arrays[mesaAttr]->StrideB; /* in bytes */
+ velements[attr].instance_divisor = 0;
+ velements[attr].vertex_buffer_index = attr;
+ velements[attr].src_format =
+ st_pipe_vertex_format(arrays[mesaAttr]->Type,
+ arrays[mesaAttr]->Size,
+ arrays[mesaAttr]->Format,
+ arrays[mesaAttr]->Normalized);
+ assert(velements[attr].src_format);
+
+ /* tell draw about this attribute */
+#if 0
+ draw_set_vertex_buffer(draw, attr, &vbuffer[attr]);
+#endif
+
+ /* map the attrib buffer */
+ map = pipe_buffer_map(pipe, vbuffers[attr].buffer,
+ PIPE_TRANSFER_READ,
+ &vb_transfer[attr]);
+ draw_set_mapped_vertex_buffer(draw, attr, map);
+ }
+
+ draw_set_vertex_buffers(draw, vp->num_inputs, vbuffers);
+ draw_set_vertex_elements(draw, vp->num_inputs, velements);
+
+ memset(&ibuffer, 0, sizeof(ibuffer));
+ if (ib) {
+ struct gl_buffer_object *bufobj = ib->obj;
+
+ switch (ib->type) {
+ case GL_UNSIGNED_INT:
+ ibuffer.index_size = 4;
+ break;
+ case GL_UNSIGNED_SHORT:
+ ibuffer.index_size = 2;
+ break;
+ case GL_UNSIGNED_BYTE:
+ ibuffer.index_size = 1;
+ break;
+ default:
+ assert(0);
+ goto out_unref_vertex;
+ }
+
+ if (bufobj && bufobj->Name) {
+ struct st_buffer_object *stobj = st_buffer_object(bufobj);
+
+ pipe_resource_reference(&ibuffer.buffer, stobj->buffer);
+ ibuffer.offset = pointer_to_offset(ib->ptr);
+
+ mapped_indices = pipe_buffer_map(pipe, stobj->buffer,
+ PIPE_TRANSFER_READ, &ib_transfer);
+ }
+ else {
+ /* skip setting ibuffer.buffer as the draw module does not use it */
+ mapped_indices = ib->ptr;
+ }
+
+ draw_set_index_buffer(draw, &ibuffer);
+ draw_set_mapped_index_buffer(draw, mapped_indices);
+ }
+
+ /* set the constant buffer */
+ draw_set_mapped_constant_buffer(st->draw, PIPE_SHADER_VERTEX, 0,
+ st->state.constants[PIPE_SHADER_VERTEX].ptr,
+ st->state.constants[PIPE_SHADER_VERTEX].size);
+
+
+ /* draw here */
+ for (i = 0; i < nr_prims; i++) {
+ draw_arrays(draw, prims[i].mode, prims[i].start, prims[i].count);
+ }
+
+
+ /*
+ * unmap vertex/index buffers
+ */
+ if (ib) {
+ draw_set_mapped_index_buffer(draw, NULL);
+ draw_set_index_buffer(draw, NULL);
+
+ if (ib_transfer)
+ pipe_buffer_unmap(pipe, ib_transfer);
+ pipe_resource_reference(&ibuffer.buffer, NULL);
+ }
+
+ out_unref_vertex:
+ for (attr = 0; attr < vp->num_inputs; attr++) {
+ pipe_buffer_unmap(pipe, vb_transfer[attr]);
+ draw_set_mapped_vertex_buffer(draw, attr, NULL);
+ pipe_resource_reference(&vbuffers[attr].buffer, NULL);
+ }
+ draw_set_vertex_buffers(draw, 0, NULL);
+}
+
+#endif /* FEATURE_feedback || FEATURE_rastpos */
+
diff --git a/mesalib/src/mesa/state_tracker/st_format.c b/mesalib/src/mesa/state_tracker/st_format.c
index 577ee6189..3620d0cb6 100644
--- a/mesalib/src/mesa/state_tracker/st_format.c
+++ b/mesalib/src/mesa/state_tracker/st_format.c
@@ -1,1149 +1,1149 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * Copyright (c) 2008-2010 VMware, Inc.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-
-/**
- * Mesa / Gallium format conversion and format selection code.
- * \author Brian Paul
- */
-
-#include "main/imports.h"
-#include "main/context.h"
-#include "main/texstore.h"
-#include "main/image.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "pipe/p_screen.h"
-#include "util/u_format.h"
-#include "st_context.h"
-#include "st_format.h"
-
-
-static GLuint
-format_max_bits(enum pipe_format format)
-{
- GLuint size = util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 0);
-
- size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 1));
- size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 2));
- size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 3));
- size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_ZS, 0));
- size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_ZS, 1));
- return size;
-}
-
-
-/**
- * Return basic GL datatype for the given gallium format.
- */
-GLenum
-st_format_datatype(enum pipe_format format)
-{
- const struct util_format_description *desc;
-
- desc = util_format_description(format);
- assert(desc);
-
- if (desc->layout == UTIL_FORMAT_LAYOUT_PLAIN) {
- if (format == PIPE_FORMAT_B5G5R5A1_UNORM ||
- format == PIPE_FORMAT_B5G6R5_UNORM) {
- return GL_UNSIGNED_SHORT;
- }
- else if (format == PIPE_FORMAT_Z24_UNORM_S8_USCALED ||
- format == PIPE_FORMAT_S8_USCALED_Z24_UNORM ||
- format == PIPE_FORMAT_Z24X8_UNORM ||
- format == PIPE_FORMAT_X8Z24_UNORM) {
- return GL_UNSIGNED_INT_24_8;
- }
- else {
- const GLuint size = format_max_bits(format);
- if (size == 8) {
- if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
- return GL_UNSIGNED_BYTE;
- else
- return GL_BYTE;
- }
- else if (size == 16) {
- if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
- return GL_UNSIGNED_SHORT;
- else
- return GL_SHORT;
- }
- else {
- assert( size <= 32 );
- if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
- return GL_UNSIGNED_INT;
- else
- return GL_INT;
- }
- }
- }
- else if (format == PIPE_FORMAT_UYVY) {
- return GL_UNSIGNED_SHORT;
- }
- else if (format == PIPE_FORMAT_YUYV) {
- return GL_UNSIGNED_SHORT;
- }
- else {
- /* probably a compressed format, unsupported anyway */
- return GL_NONE;
- }
-}
-
-
-/**
- * Translate Mesa format to Gallium format.
- */
-enum pipe_format
-st_mesa_format_to_pipe_format(gl_format mesaFormat)
-{
- switch (mesaFormat) {
- case MESA_FORMAT_RGBA8888:
- return PIPE_FORMAT_A8B8G8R8_UNORM;
- case MESA_FORMAT_RGBA8888_REV:
- return PIPE_FORMAT_R8G8B8A8_UNORM;
- case MESA_FORMAT_ARGB8888:
- return PIPE_FORMAT_B8G8R8A8_UNORM;
- case MESA_FORMAT_ARGB8888_REV:
- return PIPE_FORMAT_A8R8G8B8_UNORM;
- case MESA_FORMAT_XRGB8888:
- return PIPE_FORMAT_B8G8R8X8_UNORM;
- case MESA_FORMAT_XRGB8888_REV:
- return PIPE_FORMAT_X8R8G8B8_UNORM;
- case MESA_FORMAT_ARGB1555:
- return PIPE_FORMAT_B5G5R5A1_UNORM;
- case MESA_FORMAT_ARGB4444:
- return PIPE_FORMAT_B4G4R4A4_UNORM;
- case MESA_FORMAT_RGB565:
- return PIPE_FORMAT_B5G6R5_UNORM;
- case MESA_FORMAT_RGB332:
- return PIPE_FORMAT_B2G3R3_UNORM;
- case MESA_FORMAT_ARGB2101010:
- return PIPE_FORMAT_B10G10R10A2_UNORM;
- case MESA_FORMAT_AL44:
- return PIPE_FORMAT_L4A4_UNORM;
- case MESA_FORMAT_AL88:
- return PIPE_FORMAT_L8A8_UNORM;
- case MESA_FORMAT_AL1616:
- return PIPE_FORMAT_L16A16_UNORM;
- case MESA_FORMAT_A8:
- return PIPE_FORMAT_A8_UNORM;
- case MESA_FORMAT_A16:
- return PIPE_FORMAT_A16_UNORM;
- case MESA_FORMAT_L8:
- return PIPE_FORMAT_L8_UNORM;
- case MESA_FORMAT_L16:
- return PIPE_FORMAT_L16_UNORM;
- case MESA_FORMAT_I8:
- return PIPE_FORMAT_I8_UNORM;
- case MESA_FORMAT_I16:
- return PIPE_FORMAT_I16_UNORM;
- case MESA_FORMAT_Z16:
- return PIPE_FORMAT_Z16_UNORM;
- case MESA_FORMAT_Z32:
- return PIPE_FORMAT_Z32_UNORM;
- case MESA_FORMAT_Z24_S8:
- return PIPE_FORMAT_S8_USCALED_Z24_UNORM;
- case MESA_FORMAT_S8_Z24:
- return PIPE_FORMAT_Z24_UNORM_S8_USCALED;
- case MESA_FORMAT_Z24_X8:
- return PIPE_FORMAT_X8Z24_UNORM;
- case MESA_FORMAT_X8_Z24:
- return PIPE_FORMAT_Z24X8_UNORM;
- case MESA_FORMAT_S8:
- return PIPE_FORMAT_S8_USCALED;
- case MESA_FORMAT_YCBCR:
- return PIPE_FORMAT_UYVY;
-#if FEATURE_texture_s3tc
- case MESA_FORMAT_RGB_DXT1:
- return PIPE_FORMAT_DXT1_RGB;
- case MESA_FORMAT_RGBA_DXT1:
- return PIPE_FORMAT_DXT1_RGBA;
- case MESA_FORMAT_RGBA_DXT3:
- return PIPE_FORMAT_DXT3_RGBA;
- case MESA_FORMAT_RGBA_DXT5:
- return PIPE_FORMAT_DXT5_RGBA;
-#if FEATURE_EXT_texture_sRGB
- case MESA_FORMAT_SRGB_DXT1:
- return PIPE_FORMAT_DXT1_SRGB;
- case MESA_FORMAT_SRGBA_DXT1:
- return PIPE_FORMAT_DXT1_SRGBA;
- case MESA_FORMAT_SRGBA_DXT3:
- return PIPE_FORMAT_DXT3_SRGBA;
- case MESA_FORMAT_SRGBA_DXT5:
- return PIPE_FORMAT_DXT5_SRGBA;
-#endif
-#endif
-#if FEATURE_EXT_texture_sRGB
- case MESA_FORMAT_SLA8:
- return PIPE_FORMAT_L8A8_SRGB;
- case MESA_FORMAT_SL8:
- return PIPE_FORMAT_L8_SRGB;
- case MESA_FORMAT_SRGB8:
- return PIPE_FORMAT_R8G8B8_SRGB;
- case MESA_FORMAT_SRGBA8:
- return PIPE_FORMAT_A8B8G8R8_SRGB;
- case MESA_FORMAT_SARGB8:
- return PIPE_FORMAT_B8G8R8A8_SRGB;
-#endif
- case MESA_FORMAT_R8:
- return PIPE_FORMAT_R8_UNORM;
- case MESA_FORMAT_R16:
- return PIPE_FORMAT_R16_UNORM;
- case MESA_FORMAT_RG88:
- return PIPE_FORMAT_R8G8_UNORM;
- case MESA_FORMAT_RG1616:
- return PIPE_FORMAT_R16G16_UNORM;
- case MESA_FORMAT_RGBA_16:
- return PIPE_FORMAT_R16G16B16A16_UNORM;
-
- /* signed int formats */
- case MESA_FORMAT_RGBA_INT8:
- return PIPE_FORMAT_R8G8B8A8_SSCALED;
- case MESA_FORMAT_RGBA_INT16:
- return PIPE_FORMAT_R16G16B16A16_SSCALED;
- case MESA_FORMAT_RGBA_INT32:
- return PIPE_FORMAT_R32G32B32A32_SSCALED;
-
- /* unsigned int formats */
- case MESA_FORMAT_RGBA_UINT8:
- return PIPE_FORMAT_R8G8B8A8_USCALED;
- case MESA_FORMAT_RGBA_UINT16:
- return PIPE_FORMAT_R16G16B16A16_USCALED;
- case MESA_FORMAT_RGBA_UINT32:
- return PIPE_FORMAT_R32G32B32A32_USCALED;
-
- default:
- assert(0);
- return PIPE_FORMAT_NONE;
- }
-}
-
-
-/**
- * Translate Gallium format to Mesa format.
- */
-gl_format
-st_pipe_format_to_mesa_format(enum pipe_format format)
-{
- switch (format) {
- case PIPE_FORMAT_A8B8G8R8_UNORM:
- return MESA_FORMAT_RGBA8888;
- case PIPE_FORMAT_R8G8B8A8_UNORM:
- return MESA_FORMAT_RGBA8888_REV;
- case PIPE_FORMAT_B8G8R8A8_UNORM:
- return MESA_FORMAT_ARGB8888;
- case PIPE_FORMAT_A8R8G8B8_UNORM:
- return MESA_FORMAT_ARGB8888_REV;
- case PIPE_FORMAT_B8G8R8X8_UNORM:
- return MESA_FORMAT_XRGB8888;
- case PIPE_FORMAT_X8R8G8B8_UNORM:
- return MESA_FORMAT_XRGB8888_REV;
- case PIPE_FORMAT_B5G5R5A1_UNORM:
- return MESA_FORMAT_ARGB1555;
- case PIPE_FORMAT_B4G4R4A4_UNORM:
- return MESA_FORMAT_ARGB4444;
- case PIPE_FORMAT_B5G6R5_UNORM:
- return MESA_FORMAT_RGB565;
- case PIPE_FORMAT_B2G3R3_UNORM:
- return MESA_FORMAT_RGB332;
- case PIPE_FORMAT_B10G10R10A2_UNORM:
- return MESA_FORMAT_ARGB2101010;
- case PIPE_FORMAT_L4A4_UNORM:
- return MESA_FORMAT_AL44;
- case PIPE_FORMAT_L8A8_UNORM:
- return MESA_FORMAT_AL88;
- case PIPE_FORMAT_L16A16_UNORM:
- return MESA_FORMAT_AL1616;
- case PIPE_FORMAT_A8_UNORM:
- return MESA_FORMAT_A8;
- case PIPE_FORMAT_A16_UNORM:
- return MESA_FORMAT_A16;
- case PIPE_FORMAT_L8_UNORM:
- return MESA_FORMAT_L8;
- case PIPE_FORMAT_L16_UNORM:
- return MESA_FORMAT_L16;
- case PIPE_FORMAT_I8_UNORM:
- return MESA_FORMAT_I8;
- case PIPE_FORMAT_I16_UNORM:
- return MESA_FORMAT_I16;
- case PIPE_FORMAT_S8_USCALED:
- return MESA_FORMAT_S8;
-
- case PIPE_FORMAT_R16G16B16A16_UNORM:
- return MESA_FORMAT_RGBA_16;
- case PIPE_FORMAT_R16G16B16A16_SNORM:
- return MESA_FORMAT_SIGNED_RGBA_16;
-
- case PIPE_FORMAT_Z16_UNORM:
- return MESA_FORMAT_Z16;
- case PIPE_FORMAT_Z32_UNORM:
- return MESA_FORMAT_Z32;
- case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
- return MESA_FORMAT_Z24_S8;
- case PIPE_FORMAT_X8Z24_UNORM:
- return MESA_FORMAT_Z24_X8;
- case PIPE_FORMAT_Z24X8_UNORM:
- return MESA_FORMAT_X8_Z24;
- case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
- return MESA_FORMAT_S8_Z24;
-
- case PIPE_FORMAT_UYVY:
- return MESA_FORMAT_YCBCR;
- case PIPE_FORMAT_YUYV:
- return MESA_FORMAT_YCBCR_REV;
-
-#if FEATURE_texture_s3tc
- case PIPE_FORMAT_DXT1_RGB:
- return MESA_FORMAT_RGB_DXT1;
- case PIPE_FORMAT_DXT1_RGBA:
- return MESA_FORMAT_RGBA_DXT1;
- case PIPE_FORMAT_DXT3_RGBA:
- return MESA_FORMAT_RGBA_DXT3;
- case PIPE_FORMAT_DXT5_RGBA:
- return MESA_FORMAT_RGBA_DXT5;
-#if FEATURE_EXT_texture_sRGB
- case PIPE_FORMAT_DXT1_SRGB:
- return MESA_FORMAT_SRGB_DXT1;
- case PIPE_FORMAT_DXT1_SRGBA:
- return MESA_FORMAT_SRGBA_DXT1;
- case PIPE_FORMAT_DXT3_SRGBA:
- return MESA_FORMAT_SRGBA_DXT3;
- case PIPE_FORMAT_DXT5_SRGBA:
- return MESA_FORMAT_SRGBA_DXT5;
-#endif
-#endif
-
-#if FEATURE_EXT_texture_sRGB
- case PIPE_FORMAT_L8A8_SRGB:
- return MESA_FORMAT_SLA8;
- case PIPE_FORMAT_L8_SRGB:
- return MESA_FORMAT_SL8;
- case PIPE_FORMAT_R8G8B8_SRGB:
- return MESA_FORMAT_SRGB8;
- case PIPE_FORMAT_A8B8G8R8_SRGB:
- return MESA_FORMAT_SRGBA8;
- case PIPE_FORMAT_B8G8R8A8_SRGB:
- return MESA_FORMAT_SARGB8;
-#endif
-
- case PIPE_FORMAT_R8_UNORM:
- return MESA_FORMAT_R8;
- case PIPE_FORMAT_R16_UNORM:
- return MESA_FORMAT_R16;
- case PIPE_FORMAT_R8G8_UNORM:
- return MESA_FORMAT_RG88;
- case PIPE_FORMAT_R16G16_UNORM:
- return MESA_FORMAT_RG1616;
-
- /* signed int formats */
- case PIPE_FORMAT_R8G8B8A8_SSCALED:
- return MESA_FORMAT_RGBA_INT8;
- case PIPE_FORMAT_R16G16B16A16_SSCALED:
- return MESA_FORMAT_RGBA_INT16;
- case PIPE_FORMAT_R32G32B32A32_SSCALED:
- return MESA_FORMAT_RGBA_INT32;
-
- /* unsigned int formats */
- case PIPE_FORMAT_R8G8B8A8_USCALED:
- return MESA_FORMAT_RGBA_UINT8;
- case PIPE_FORMAT_R16G16B16A16_USCALED:
- return MESA_FORMAT_RGBA_UINT16;
- case PIPE_FORMAT_R32G32B32A32_USCALED:
- return MESA_FORMAT_RGBA_UINT32;
-
- default:
- assert(0);
- return MESA_FORMAT_NONE;
- }
-}
-
-
-/**
- * Return first supported format from the given list.
- */
-static enum pipe_format
-find_supported_format(struct pipe_screen *screen,
- const enum pipe_format formats[],
- uint num_formats,
- enum pipe_texture_target target,
- unsigned sample_count,
- unsigned tex_usage,
- unsigned geom_flags)
-{
- uint i;
- for (i = 0; i < num_formats; i++) {
- if (screen->is_format_supported(screen, formats[i], target,
- sample_count, tex_usage, geom_flags)) {
- return formats[i];
- }
- }
- return PIPE_FORMAT_NONE;
-}
-
-
-/**
- * Find an RGBA format supported by the context/winsys.
- */
-static enum pipe_format
-default_rgba_format(struct pipe_screen *screen,
- enum pipe_texture_target target,
- unsigned sample_count,
- unsigned tex_usage,
- unsigned geom_flags)
-{
- static const enum pipe_format colorFormats[] = {
- PIPE_FORMAT_B8G8R8A8_UNORM,
- PIPE_FORMAT_A8R8G8B8_UNORM,
- PIPE_FORMAT_A8B8G8R8_UNORM,
- PIPE_FORMAT_B5G6R5_UNORM
- };
- return find_supported_format(screen, colorFormats, Elements(colorFormats),
- target, sample_count, tex_usage, geom_flags);
-}
-
-
-/**
- * Find an RGB format supported by the context/winsys.
- */
-static enum pipe_format
-default_rgb_format(struct pipe_screen *screen,
- enum pipe_texture_target target,
- unsigned sample_count,
- unsigned tex_usage,
- unsigned geom_flags)
-{
- static const enum pipe_format colorFormats[] = {
- PIPE_FORMAT_B8G8R8X8_UNORM,
- PIPE_FORMAT_X8R8G8B8_UNORM,
- PIPE_FORMAT_X8B8G8R8_UNORM,
- PIPE_FORMAT_B8G8R8A8_UNORM,
- PIPE_FORMAT_A8R8G8B8_UNORM,
- PIPE_FORMAT_A8B8G8R8_UNORM,
- PIPE_FORMAT_B5G6R5_UNORM
- };
- return find_supported_format(screen, colorFormats, Elements(colorFormats),
- target, sample_count, tex_usage, geom_flags);
-}
-
-/**
- * Find an sRGBA format supported by the context/winsys.
- */
-static enum pipe_format
-default_srgba_format(struct pipe_screen *screen,
- enum pipe_texture_target target,
- unsigned sample_count,
- unsigned tex_usage,
- unsigned geom_flags)
-{
- static const enum pipe_format colorFormats[] = {
- PIPE_FORMAT_B8G8R8A8_SRGB,
- PIPE_FORMAT_A8R8G8B8_SRGB,
- PIPE_FORMAT_A8B8G8R8_SRGB,
- };
- return find_supported_format(screen, colorFormats, Elements(colorFormats),
- target, sample_count, tex_usage, geom_flags);
-}
-
-
-/**
- * Given an OpenGL internalFormat value for a texture or surface, return
- * the best matching PIPE_FORMAT_x, or PIPE_FORMAT_NONE if there's no match.
- * This is called during glTexImage2D, for example.
- *
- * The bindings parameter typically has PIPE_BIND_SAMPLER_VIEW set, plus
- * either PIPE_BINDING_RENDER_TARGET or PIPE_BINDING_DEPTH_STENCIL if
- * we want render-to-texture ability.
- *
- * \param internalFormat the user value passed to glTexImage2D
- * \param target one of PIPE_TEXTURE_x
- * \param bindings bitmask of PIPE_BIND_x flags.
- */
-enum pipe_format
-st_choose_format(struct pipe_screen *screen, GLenum internalFormat,
- enum pipe_texture_target target, unsigned sample_count,
- unsigned bindings)
-{
- unsigned geom_flags = 0; /* we don't care about POT vs. NPOT here, yet */
-
- switch (internalFormat) {
- case GL_RGB10:
- case GL_RGB10_A2:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B10G10R10A2_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B10G10R10A2_UNORM;
- /* Pass through. */
- case 4:
- case GL_RGBA:
- case GL_RGBA8:
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_BGRA:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B8G8R8A8_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B8G8R8A8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case 3:
- case GL_RGB:
- case GL_RGB8:
- return default_rgb_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_RGB12:
- case GL_RGB16:
- case GL_RGBA12:
- case GL_RGBA16:
- if (screen->is_format_supported( screen, PIPE_FORMAT_R16G16B16A16_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_R16G16B16A16_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_RGBA4:
- case GL_RGBA2:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B4G4R4A4_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B4G4R4A4_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_RGB5_A1:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B5G5R5A1_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B5G5R5A1_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_R3_G3_B2:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B2G3R3_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B2G3R3_UNORM;
- /* Pass through. */
- case GL_RGB5:
- case GL_RGB4:
- if (screen->is_format_supported( screen, PIPE_FORMAT_B5G6R5_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B5G6R5_UNORM;
- if (screen->is_format_supported( screen, PIPE_FORMAT_B5G5R5A1_UNORM,
- target, sample_count, bindings,
- geom_flags ))
- return PIPE_FORMAT_B5G5R5A1_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_ALPHA12:
- case GL_ALPHA16:
- if (screen->is_format_supported( screen, PIPE_FORMAT_A16_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_A16_UNORM;
- /* Pass through. */
- case GL_ALPHA:
- case GL_ALPHA4:
- case GL_ALPHA8:
- case GL_COMPRESSED_ALPHA:
- if (screen->is_format_supported( screen, PIPE_FORMAT_A8_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_A8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_LUMINANCE12:
- case GL_LUMINANCE16:
- if (screen->is_format_supported( screen, PIPE_FORMAT_L16_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L16_UNORM;
- /* Pass through. */
- case 1:
- case GL_LUMINANCE:
- case GL_LUMINANCE4:
- case GL_LUMINANCE8:
- case GL_COMPRESSED_LUMINANCE:
- if (screen->is_format_supported( screen, PIPE_FORMAT_L8_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_LUMINANCE12_ALPHA4:
- case GL_LUMINANCE12_ALPHA12:
- case GL_LUMINANCE16_ALPHA16:
- if (screen->is_format_supported( screen, PIPE_FORMAT_L16A16_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L16A16_UNORM;
- /* Pass through. */
- case 2:
- case GL_LUMINANCE_ALPHA:
- case GL_LUMINANCE6_ALPHA2:
- case GL_LUMINANCE8_ALPHA8:
- case GL_COMPRESSED_LUMINANCE_ALPHA:
- if (screen->is_format_supported( screen, PIPE_FORMAT_L8A8_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L8A8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_LUMINANCE4_ALPHA4:
- if (screen->is_format_supported( screen, PIPE_FORMAT_L4A4_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L4A4_UNORM;
- if (screen->is_format_supported( screen, PIPE_FORMAT_L8A8_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_L8A8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_INTENSITY12:
- case GL_INTENSITY16:
- if (screen->is_format_supported( screen, PIPE_FORMAT_I16_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_I16_UNORM;
- /* Pass through. */
- case GL_INTENSITY:
- case GL_INTENSITY4:
- case GL_INTENSITY8:
- case GL_COMPRESSED_INTENSITY:
- if (screen->is_format_supported( screen, PIPE_FORMAT_I8_UNORM, target,
- sample_count, bindings, geom_flags ))
- return PIPE_FORMAT_I8_UNORM;
- return default_rgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_YCBCR_MESA:
- if (screen->is_format_supported(screen, PIPE_FORMAT_UYVY, target,
- sample_count, bindings, geom_flags)) {
- return PIPE_FORMAT_UYVY;
- }
- if (screen->is_format_supported(screen, PIPE_FORMAT_YUYV, target,
- sample_count, bindings, geom_flags)) {
- return PIPE_FORMAT_YUYV;
- }
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_RED:
- case GL_COMPRESSED_RG:
- case GL_COMPRESSED_RGB:
- /* can only sample from compressed formats */
- if (bindings & ~PIPE_BIND_SAMPLER_VIEW)
- return PIPE_FORMAT_NONE;
- else if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGB,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT1_RGB;
- else
- return default_rgb_format(screen, target, sample_count, bindings,
- geom_flags);
-
- case GL_COMPRESSED_RGBA:
- /* can only sample from compressed formats */
- if (bindings & ~PIPE_BIND_SAMPLER_VIEW)
- return PIPE_FORMAT_NONE;
- else if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_RGBA,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT3_RGBA;
- else
- return default_rgba_format(screen, target, sample_count, bindings,
- geom_flags);
-
- case GL_RGB_S3TC:
- case GL_RGB4_S3TC:
- case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGB,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT1_RGB;
- else
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGBA,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT1_RGBA;
- else
- return PIPE_FORMAT_NONE;
-
- case GL_RGBA_S3TC:
- case GL_RGBA4_S3TC:
- case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_RGBA,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT3_RGBA;
- else
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT5_RGBA,
- target, sample_count, bindings,
- geom_flags))
- return PIPE_FORMAT_DXT5_RGBA;
- else
- return PIPE_FORMAT_NONE;
-
-#if 0
- case GL_COMPRESSED_RGB_FXT1_3DFX:
- return PIPE_FORMAT_RGB_FXT1;
- case GL_COMPRESSED_RGBA_FXT1_3DFX:
- return PIPE_FORMAT_RGB_FXT1;
-#endif
-
- case GL_DEPTH_COMPONENT16:
- if (screen->is_format_supported(screen, PIPE_FORMAT_Z16_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_Z16_UNORM;
- /* fall-through */
- case GL_DEPTH_COMPONENT24:
- if (screen->is_format_supported(screen, PIPE_FORMAT_Z24_UNORM_S8_USCALED,
- target, sample_count, bindings, geom_flags))
- return PIPE_FORMAT_Z24_UNORM_S8_USCALED;
- if (screen->is_format_supported(screen, PIPE_FORMAT_S8_USCALED_Z24_UNORM,
- target, sample_count, bindings, geom_flags))
- return PIPE_FORMAT_S8_USCALED_Z24_UNORM;
- /* fall-through */
- case GL_DEPTH_COMPONENT32:
- if (screen->is_format_supported(screen, PIPE_FORMAT_Z32_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_Z32_UNORM;
- /* fall-through */
- case GL_DEPTH_COMPONENT:
- {
- static const enum pipe_format formats[] = {
- PIPE_FORMAT_Z32_UNORM,
- PIPE_FORMAT_Z24_UNORM_S8_USCALED,
- PIPE_FORMAT_S8_USCALED_Z24_UNORM,
- PIPE_FORMAT_Z16_UNORM
- };
- return find_supported_format(screen, formats, Elements(formats),
- target, sample_count, bindings, geom_flags);
- }
-
- case GL_STENCIL_INDEX:
- case GL_STENCIL_INDEX1_EXT:
- case GL_STENCIL_INDEX4_EXT:
- case GL_STENCIL_INDEX8_EXT:
- case GL_STENCIL_INDEX16_EXT:
- {
- static const enum pipe_format formats[] = {
- PIPE_FORMAT_S8_USCALED,
- PIPE_FORMAT_Z24_UNORM_S8_USCALED,
- PIPE_FORMAT_S8_USCALED_Z24_UNORM
- };
- return find_supported_format(screen, formats, Elements(formats),
- target, sample_count, bindings, geom_flags);
- }
-
- case GL_DEPTH_STENCIL_EXT:
- case GL_DEPTH24_STENCIL8_EXT:
- {
- static const enum pipe_format formats[] = {
- PIPE_FORMAT_Z24_UNORM_S8_USCALED,
- PIPE_FORMAT_S8_USCALED_Z24_UNORM
- };
- return find_supported_format(screen, formats, Elements(formats),
- target, sample_count, bindings, geom_flags);
- }
-
- case GL_SRGB_EXT:
- case GL_SRGB8_EXT:
- case GL_SRGB_ALPHA_EXT:
- case GL_SRGB8_ALPHA8_EXT:
- return default_srgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_COMPRESSED_SRGB_EXT:
- case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_SRGB, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_DXT1_SRGB;
- return default_srgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
- return PIPE_FORMAT_DXT1_SRGBA;
-
- case GL_COMPRESSED_SRGB_ALPHA_EXT:
- case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_SRGBA, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_DXT3_SRGBA;
- return default_srgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
- return PIPE_FORMAT_DXT5_SRGBA;
-
- case GL_SLUMINANCE_ALPHA_EXT:
- case GL_SLUMINANCE8_ALPHA8_EXT:
- case GL_COMPRESSED_SLUMINANCE_EXT:
- case GL_COMPRESSED_SLUMINANCE_ALPHA_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_L8A8_SRGB, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_L8A8_SRGB;
- return default_srgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_SLUMINANCE_EXT:
- case GL_SLUMINANCE8_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_L8_SRGB, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_L8_SRGB;
- return default_srgba_format( screen, target, sample_count, bindings,
- geom_flags );
-
- case GL_RED:
- case GL_R8:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R8_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R8_UNORM;
- return PIPE_FORMAT_NONE;
- case GL_RG:
- case GL_RG8:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R8G8_UNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_R16:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R16_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R16_UNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_RG16:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R16G16_UNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_RED_RGTC1:
- if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC1_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_RGTC1_UNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_SIGNED_RED_RGTC1:
- if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC1_SNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_RGTC1_SNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_RG_RGTC2:
- if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC2_UNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_RGTC2_UNORM;
- return PIPE_FORMAT_NONE;
-
- case GL_COMPRESSED_SIGNED_RG_RGTC2:
- if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC2_SNORM, target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_RGTC2_SNORM;
- return PIPE_FORMAT_NONE;
-
- /* signed/unsigned integer formats.
- * XXX Mesa only has formats for RGBA signed/unsigned integer formats.
- * If/when new formats are added this code should be updated.
- */
- case GL_RED_INTEGER_EXT:
- case GL_GREEN_INTEGER_EXT:
- case GL_BLUE_INTEGER_EXT:
- case GL_ALPHA_INTEGER_EXT:
- case GL_RGB_INTEGER_EXT:
- case GL_RGBA_INTEGER_EXT:
- case GL_BGR_INTEGER_EXT:
- case GL_BGRA_INTEGER_EXT:
- case GL_LUMINANCE_INTEGER_EXT:
- case GL_LUMINANCE_ALPHA_INTEGER_EXT:
- /* fall-through */
- case GL_RGBA8I_EXT:
- case GL_RGB8I_EXT:
- case GL_ALPHA8I_EXT:
- case GL_INTENSITY8I_EXT:
- case GL_LUMINANCE8I_EXT:
- case GL_LUMINANCE_ALPHA8I_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8B8A8_SSCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R8G8B8A8_SSCALED;
- return PIPE_FORMAT_NONE;
- case GL_RGBA16I_EXT:
- case GL_RGB16I_EXT:
- case GL_ALPHA16I_EXT:
- case GL_INTENSITY16I_EXT:
- case GL_LUMINANCE16I_EXT:
- case GL_LUMINANCE_ALPHA16I_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16B16A16_SSCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R16G16B16A16_SSCALED;
- return PIPE_FORMAT_NONE;
- case GL_RGBA32I_EXT:
- case GL_RGB32I_EXT:
- case GL_ALPHA32I_EXT:
- case GL_INTENSITY32I_EXT:
- case GL_LUMINANCE32I_EXT:
- case GL_LUMINANCE_ALPHA32I_EXT:
- /* xxx */
- if (screen->is_format_supported(screen, PIPE_FORMAT_R32G32B32A32_SSCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R32G32B32A32_SSCALED;
- return PIPE_FORMAT_NONE;
-
- case GL_RGBA8UI_EXT:
- case GL_RGB8UI_EXT:
- case GL_ALPHA8UI_EXT:
- case GL_INTENSITY8UI_EXT:
- case GL_LUMINANCE8UI_EXT:
- case GL_LUMINANCE_ALPHA8UI_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8B8A8_USCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R8G8B8A8_USCALED;
- return PIPE_FORMAT_NONE;
-
- case GL_RGBA16UI_EXT:
- case GL_RGB16UI_EXT:
- case GL_ALPHA16UI_EXT:
- case GL_INTENSITY16UI_EXT:
- case GL_LUMINANCE16UI_EXT:
- case GL_LUMINANCE_ALPHA16UI_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16B16A16_USCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R16G16B16A16_USCALED;
- return PIPE_FORMAT_NONE;
-
- case GL_RGBA32UI_EXT:
- case GL_RGB32UI_EXT:
- case GL_ALPHA32UI_EXT:
- case GL_INTENSITY32UI_EXT:
- case GL_LUMINANCE32UI_EXT:
- case GL_LUMINANCE_ALPHA32UI_EXT:
- if (screen->is_format_supported(screen, PIPE_FORMAT_R32G32B32A32_USCALED,
- target,
- sample_count, bindings, geom_flags))
- return PIPE_FORMAT_R32G32B32A32_USCALED;
- return PIPE_FORMAT_NONE;
-
- default:
- return PIPE_FORMAT_NONE;
- }
-}
-
-
-/**
- * Called by FBO code to choose a PIPE_FORMAT_ for drawing surfaces.
- */
-enum pipe_format
-st_choose_renderbuffer_format(struct pipe_screen *screen,
- GLenum internalFormat, unsigned sample_count)
-{
- uint usage;
- if (_mesa_is_depth_or_stencil_format(internalFormat))
- usage = PIPE_BIND_DEPTH_STENCIL;
- else
- usage = PIPE_BIND_RENDER_TARGET;
- return st_choose_format(screen, internalFormat, PIPE_TEXTURE_2D,
- sample_count, usage);
-}
-
-
-/**
- * Called via ctx->Driver.chooseTextureFormat().
- */
-gl_format
-st_ChooseTextureFormat_renderable(struct gl_context *ctx, GLint internalFormat,
- GLenum format, GLenum type, GLboolean renderable)
-{
- struct pipe_screen *screen = st_context(ctx)->pipe->screen;
- enum pipe_format pFormat;
- uint bindings;
-
- (void) format;
- (void) type;
-
- /* GL textures may wind up being render targets, but we don't know
- * that in advance. Specify potential render target flags now.
- */
- bindings = PIPE_BIND_SAMPLER_VIEW;
- if (renderable == GL_TRUE) {
- if (_mesa_is_depth_format(internalFormat) ||
- _mesa_is_depth_or_stencil_format(internalFormat))
- bindings |= PIPE_BIND_DEPTH_STENCIL;
- else
- bindings |= PIPE_BIND_RENDER_TARGET;
- }
-
- pFormat = st_choose_format(screen, internalFormat,
- PIPE_TEXTURE_2D, 0, bindings);
-
- if (pFormat == PIPE_FORMAT_NONE) {
- /* try choosing format again, this time without render target bindings */
- pFormat = st_choose_format(screen, internalFormat,
- PIPE_TEXTURE_2D, 0, PIPE_BIND_SAMPLER_VIEW);
- }
-
- if (pFormat == PIPE_FORMAT_NONE) {
- /* no luck at all */
- return MESA_FORMAT_NONE;
- }
-
- return st_pipe_format_to_mesa_format(pFormat);
-}
-
-gl_format
-st_ChooseTextureFormat(struct gl_context *ctx, GLint internalFormat,
- GLenum format, GLenum type)
-{
- boolean want_renderable =
- internalFormat == 3 || internalFormat == 4 ||
- internalFormat == GL_RGB || internalFormat == GL_RGBA ||
- internalFormat == GL_RGB8 || internalFormat == GL_RGBA8 ||
- internalFormat == GL_BGRA;
-
- return st_ChooseTextureFormat_renderable(ctx, internalFormat,
- format, type, want_renderable);
-}
-
-/**
- * Test if a gallium format is equivalent to a GL format/type.
- */
-GLboolean
-st_equal_formats(enum pipe_format pFormat, GLenum format, GLenum type)
-{
- switch (pFormat) {
- case PIPE_FORMAT_A8B8G8R8_UNORM:
- return format == GL_RGBA && type == GL_UNSIGNED_BYTE;
- case PIPE_FORMAT_A8R8G8B8_UNORM:
- return format == GL_BGRA && type == GL_UNSIGNED_BYTE;
- case PIPE_FORMAT_B5G6R5_UNORM:
- return format == GL_RGB && type == GL_UNSIGNED_SHORT_5_6_5;
- /* XXX more combos... */
- default:
- return GL_FALSE;
- }
-}
-
-GLboolean
-st_sampler_compat_formats(enum pipe_format format1, enum pipe_format format2)
-{
- if (format1 == format2)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_B8G8R8A8_UNORM &&
- format2 == PIPE_FORMAT_B8G8R8X8_UNORM)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_B8G8R8X8_UNORM &&
- format2 == PIPE_FORMAT_B8G8R8A8_UNORM)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_A8B8G8R8_UNORM &&
- format2 == PIPE_FORMAT_X8B8G8R8_UNORM)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_X8B8G8R8_UNORM &&
- format2 == PIPE_FORMAT_A8B8G8R8_UNORM)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_A8R8G8B8_UNORM &&
- format2 == PIPE_FORMAT_X8R8G8B8_UNORM)
- return GL_TRUE;
-
- if (format1 == PIPE_FORMAT_X8R8G8B8_UNORM &&
- format2 == PIPE_FORMAT_A8R8G8B8_UNORM)
- return GL_TRUE;
-
- return GL_FALSE;
-}
-
-
-
-/**
- * This is used for translating texture border color and the clear
- * color. For example, the clear color is interpreted according to
- * the renderbuffer's base format. For example, if clearing a
- * GL_LUMINANCE buffer, ClearColor[0] = luminance and ClearColor[1] =
- * alpha. Similarly for texture border colors.
- */
-void
-st_translate_color(const GLfloat colorIn[4], GLenum baseFormat,
- GLfloat colorOut[4])
-{
- switch (baseFormat) {
- case GL_RED:
- colorOut[0] = colorIn[0];
- colorOut[1] = 0.0F;
- colorOut[2] = 0.0F;
- colorOut[3] = 1.0F;
- break;
- case GL_RG:
- colorOut[0] = colorIn[0];
- colorOut[1] = colorIn[1];
- colorOut[2] = 0.0F;
- colorOut[3] = 1.0F;
- break;
- case GL_RGB:
- colorOut[0] = colorIn[0];
- colorOut[1] = colorIn[1];
- colorOut[2] = colorIn[2];
- colorOut[3] = 1.0F;
- break;
- case GL_ALPHA:
- colorOut[0] = colorOut[1] = colorOut[2] = 0.0;
- colorOut[3] = colorIn[3];
- break;
- case GL_LUMINANCE:
- colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0];
- colorOut[3] = 1.0;
- break;
- case GL_LUMINANCE_ALPHA:
- colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0];
- colorOut[3] = colorIn[3];
- break;
- case GL_INTENSITY:
- colorOut[0] = colorOut[1] = colorOut[2] = colorOut[3] = colorIn[0];
- break;
- default:
- COPY_4V(colorOut, colorIn);
- }
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * Copyright (c) 2008-2010 VMware, Inc.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+
+/**
+ * Mesa / Gallium format conversion and format selection code.
+ * \author Brian Paul
+ */
+
+#include "main/imports.h"
+#include "main/context.h"
+#include "main/texstore.h"
+#include "main/image.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "pipe/p_screen.h"
+#include "util/u_format.h"
+#include "st_context.h"
+#include "st_format.h"
+
+
+static GLuint
+format_max_bits(enum pipe_format format)
+{
+ GLuint size = util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 0);
+
+ size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 1));
+ size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 2));
+ size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, 3));
+ size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_ZS, 0));
+ size = MAX2(size, util_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_ZS, 1));
+ return size;
+}
+
+
+/**
+ * Return basic GL datatype for the given gallium format.
+ */
+GLenum
+st_format_datatype(enum pipe_format format)
+{
+ const struct util_format_description *desc;
+
+ desc = util_format_description(format);
+ assert(desc);
+
+ if (desc->layout == UTIL_FORMAT_LAYOUT_PLAIN) {
+ if (format == PIPE_FORMAT_B5G5R5A1_UNORM ||
+ format == PIPE_FORMAT_B5G6R5_UNORM) {
+ return GL_UNSIGNED_SHORT;
+ }
+ else if (format == PIPE_FORMAT_Z24_UNORM_S8_USCALED ||
+ format == PIPE_FORMAT_S8_USCALED_Z24_UNORM ||
+ format == PIPE_FORMAT_Z24X8_UNORM ||
+ format == PIPE_FORMAT_X8Z24_UNORM) {
+ return GL_UNSIGNED_INT_24_8;
+ }
+ else {
+ const GLuint size = format_max_bits(format);
+ if (size == 8) {
+ if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
+ return GL_UNSIGNED_BYTE;
+ else
+ return GL_BYTE;
+ }
+ else if (size == 16) {
+ if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
+ return GL_UNSIGNED_SHORT;
+ else
+ return GL_SHORT;
+ }
+ else {
+ assert( size <= 32 );
+ if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED)
+ return GL_UNSIGNED_INT;
+ else
+ return GL_INT;
+ }
+ }
+ }
+ else if (format == PIPE_FORMAT_UYVY) {
+ return GL_UNSIGNED_SHORT;
+ }
+ else if (format == PIPE_FORMAT_YUYV) {
+ return GL_UNSIGNED_SHORT;
+ }
+ else {
+ /* probably a compressed format, unsupported anyway */
+ return GL_NONE;
+ }
+}
+
+
+/**
+ * Translate Mesa format to Gallium format.
+ */
+enum pipe_format
+st_mesa_format_to_pipe_format(gl_format mesaFormat)
+{
+ switch (mesaFormat) {
+ case MESA_FORMAT_RGBA8888:
+ return PIPE_FORMAT_A8B8G8R8_UNORM;
+ case MESA_FORMAT_RGBA8888_REV:
+ return PIPE_FORMAT_R8G8B8A8_UNORM;
+ case MESA_FORMAT_ARGB8888:
+ return PIPE_FORMAT_B8G8R8A8_UNORM;
+ case MESA_FORMAT_ARGB8888_REV:
+ return PIPE_FORMAT_A8R8G8B8_UNORM;
+ case MESA_FORMAT_XRGB8888:
+ return PIPE_FORMAT_B8G8R8X8_UNORM;
+ case MESA_FORMAT_XRGB8888_REV:
+ return PIPE_FORMAT_X8R8G8B8_UNORM;
+ case MESA_FORMAT_ARGB1555:
+ return PIPE_FORMAT_B5G5R5A1_UNORM;
+ case MESA_FORMAT_ARGB4444:
+ return PIPE_FORMAT_B4G4R4A4_UNORM;
+ case MESA_FORMAT_RGB565:
+ return PIPE_FORMAT_B5G6R5_UNORM;
+ case MESA_FORMAT_RGB332:
+ return PIPE_FORMAT_B2G3R3_UNORM;
+ case MESA_FORMAT_ARGB2101010:
+ return PIPE_FORMAT_B10G10R10A2_UNORM;
+ case MESA_FORMAT_AL44:
+ return PIPE_FORMAT_L4A4_UNORM;
+ case MESA_FORMAT_AL88:
+ return PIPE_FORMAT_L8A8_UNORM;
+ case MESA_FORMAT_AL1616:
+ return PIPE_FORMAT_L16A16_UNORM;
+ case MESA_FORMAT_A8:
+ return PIPE_FORMAT_A8_UNORM;
+ case MESA_FORMAT_A16:
+ return PIPE_FORMAT_A16_UNORM;
+ case MESA_FORMAT_L8:
+ return PIPE_FORMAT_L8_UNORM;
+ case MESA_FORMAT_L16:
+ return PIPE_FORMAT_L16_UNORM;
+ case MESA_FORMAT_I8:
+ return PIPE_FORMAT_I8_UNORM;
+ case MESA_FORMAT_I16:
+ return PIPE_FORMAT_I16_UNORM;
+ case MESA_FORMAT_Z16:
+ return PIPE_FORMAT_Z16_UNORM;
+ case MESA_FORMAT_Z32:
+ return PIPE_FORMAT_Z32_UNORM;
+ case MESA_FORMAT_Z24_S8:
+ return PIPE_FORMAT_S8_USCALED_Z24_UNORM;
+ case MESA_FORMAT_S8_Z24:
+ return PIPE_FORMAT_Z24_UNORM_S8_USCALED;
+ case MESA_FORMAT_Z24_X8:
+ return PIPE_FORMAT_X8Z24_UNORM;
+ case MESA_FORMAT_X8_Z24:
+ return PIPE_FORMAT_Z24X8_UNORM;
+ case MESA_FORMAT_S8:
+ return PIPE_FORMAT_S8_USCALED;
+ case MESA_FORMAT_YCBCR:
+ return PIPE_FORMAT_UYVY;
+#if FEATURE_texture_s3tc
+ case MESA_FORMAT_RGB_DXT1:
+ return PIPE_FORMAT_DXT1_RGB;
+ case MESA_FORMAT_RGBA_DXT1:
+ return PIPE_FORMAT_DXT1_RGBA;
+ case MESA_FORMAT_RGBA_DXT3:
+ return PIPE_FORMAT_DXT3_RGBA;
+ case MESA_FORMAT_RGBA_DXT5:
+ return PIPE_FORMAT_DXT5_RGBA;
+#if FEATURE_EXT_texture_sRGB
+ case MESA_FORMAT_SRGB_DXT1:
+ return PIPE_FORMAT_DXT1_SRGB;
+ case MESA_FORMAT_SRGBA_DXT1:
+ return PIPE_FORMAT_DXT1_SRGBA;
+ case MESA_FORMAT_SRGBA_DXT3:
+ return PIPE_FORMAT_DXT3_SRGBA;
+ case MESA_FORMAT_SRGBA_DXT5:
+ return PIPE_FORMAT_DXT5_SRGBA;
+#endif
+#endif
+#if FEATURE_EXT_texture_sRGB
+ case MESA_FORMAT_SLA8:
+ return PIPE_FORMAT_L8A8_SRGB;
+ case MESA_FORMAT_SL8:
+ return PIPE_FORMAT_L8_SRGB;
+ case MESA_FORMAT_SRGB8:
+ return PIPE_FORMAT_R8G8B8_SRGB;
+ case MESA_FORMAT_SRGBA8:
+ return PIPE_FORMAT_A8B8G8R8_SRGB;
+ case MESA_FORMAT_SARGB8:
+ return PIPE_FORMAT_B8G8R8A8_SRGB;
+#endif
+ case MESA_FORMAT_R8:
+ return PIPE_FORMAT_R8_UNORM;
+ case MESA_FORMAT_R16:
+ return PIPE_FORMAT_R16_UNORM;
+ case MESA_FORMAT_RG88:
+ return PIPE_FORMAT_R8G8_UNORM;
+ case MESA_FORMAT_RG1616:
+ return PIPE_FORMAT_R16G16_UNORM;
+ case MESA_FORMAT_RGBA_16:
+ return PIPE_FORMAT_R16G16B16A16_UNORM;
+
+ /* signed int formats */
+ case MESA_FORMAT_RGBA_INT8:
+ return PIPE_FORMAT_R8G8B8A8_SSCALED;
+ case MESA_FORMAT_RGBA_INT16:
+ return PIPE_FORMAT_R16G16B16A16_SSCALED;
+ case MESA_FORMAT_RGBA_INT32:
+ return PIPE_FORMAT_R32G32B32A32_SSCALED;
+
+ /* unsigned int formats */
+ case MESA_FORMAT_RGBA_UINT8:
+ return PIPE_FORMAT_R8G8B8A8_USCALED;
+ case MESA_FORMAT_RGBA_UINT16:
+ return PIPE_FORMAT_R16G16B16A16_USCALED;
+ case MESA_FORMAT_RGBA_UINT32:
+ return PIPE_FORMAT_R32G32B32A32_USCALED;
+
+ default:
+ assert(0);
+ return PIPE_FORMAT_NONE;
+ }
+}
+
+
+/**
+ * Translate Gallium format to Mesa format.
+ */
+gl_format
+st_pipe_format_to_mesa_format(enum pipe_format format)
+{
+ switch (format) {
+ case PIPE_FORMAT_A8B8G8R8_UNORM:
+ return MESA_FORMAT_RGBA8888;
+ case PIPE_FORMAT_R8G8B8A8_UNORM:
+ return MESA_FORMAT_RGBA8888_REV;
+ case PIPE_FORMAT_B8G8R8A8_UNORM:
+ return MESA_FORMAT_ARGB8888;
+ case PIPE_FORMAT_A8R8G8B8_UNORM:
+ return MESA_FORMAT_ARGB8888_REV;
+ case PIPE_FORMAT_B8G8R8X8_UNORM:
+ return MESA_FORMAT_XRGB8888;
+ case PIPE_FORMAT_X8R8G8B8_UNORM:
+ return MESA_FORMAT_XRGB8888_REV;
+ case PIPE_FORMAT_B5G5R5A1_UNORM:
+ return MESA_FORMAT_ARGB1555;
+ case PIPE_FORMAT_B4G4R4A4_UNORM:
+ return MESA_FORMAT_ARGB4444;
+ case PIPE_FORMAT_B5G6R5_UNORM:
+ return MESA_FORMAT_RGB565;
+ case PIPE_FORMAT_B2G3R3_UNORM:
+ return MESA_FORMAT_RGB332;
+ case PIPE_FORMAT_B10G10R10A2_UNORM:
+ return MESA_FORMAT_ARGB2101010;
+ case PIPE_FORMAT_L4A4_UNORM:
+ return MESA_FORMAT_AL44;
+ case PIPE_FORMAT_L8A8_UNORM:
+ return MESA_FORMAT_AL88;
+ case PIPE_FORMAT_L16A16_UNORM:
+ return MESA_FORMAT_AL1616;
+ case PIPE_FORMAT_A8_UNORM:
+ return MESA_FORMAT_A8;
+ case PIPE_FORMAT_A16_UNORM:
+ return MESA_FORMAT_A16;
+ case PIPE_FORMAT_L8_UNORM:
+ return MESA_FORMAT_L8;
+ case PIPE_FORMAT_L16_UNORM:
+ return MESA_FORMAT_L16;
+ case PIPE_FORMAT_I8_UNORM:
+ return MESA_FORMAT_I8;
+ case PIPE_FORMAT_I16_UNORM:
+ return MESA_FORMAT_I16;
+ case PIPE_FORMAT_S8_USCALED:
+ return MESA_FORMAT_S8;
+
+ case PIPE_FORMAT_R16G16B16A16_UNORM:
+ return MESA_FORMAT_RGBA_16;
+ case PIPE_FORMAT_R16G16B16A16_SNORM:
+ return MESA_FORMAT_SIGNED_RGBA_16;
+
+ case PIPE_FORMAT_Z16_UNORM:
+ return MESA_FORMAT_Z16;
+ case PIPE_FORMAT_Z32_UNORM:
+ return MESA_FORMAT_Z32;
+ case PIPE_FORMAT_S8_USCALED_Z24_UNORM:
+ return MESA_FORMAT_Z24_S8;
+ case PIPE_FORMAT_X8Z24_UNORM:
+ return MESA_FORMAT_Z24_X8;
+ case PIPE_FORMAT_Z24X8_UNORM:
+ return MESA_FORMAT_X8_Z24;
+ case PIPE_FORMAT_Z24_UNORM_S8_USCALED:
+ return MESA_FORMAT_S8_Z24;
+
+ case PIPE_FORMAT_UYVY:
+ return MESA_FORMAT_YCBCR;
+ case PIPE_FORMAT_YUYV:
+ return MESA_FORMAT_YCBCR_REV;
+
+#if FEATURE_texture_s3tc
+ case PIPE_FORMAT_DXT1_RGB:
+ return MESA_FORMAT_RGB_DXT1;
+ case PIPE_FORMAT_DXT1_RGBA:
+ return MESA_FORMAT_RGBA_DXT1;
+ case PIPE_FORMAT_DXT3_RGBA:
+ return MESA_FORMAT_RGBA_DXT3;
+ case PIPE_FORMAT_DXT5_RGBA:
+ return MESA_FORMAT_RGBA_DXT5;
+#if FEATURE_EXT_texture_sRGB
+ case PIPE_FORMAT_DXT1_SRGB:
+ return MESA_FORMAT_SRGB_DXT1;
+ case PIPE_FORMAT_DXT1_SRGBA:
+ return MESA_FORMAT_SRGBA_DXT1;
+ case PIPE_FORMAT_DXT3_SRGBA:
+ return MESA_FORMAT_SRGBA_DXT3;
+ case PIPE_FORMAT_DXT5_SRGBA:
+ return MESA_FORMAT_SRGBA_DXT5;
+#endif
+#endif
+
+#if FEATURE_EXT_texture_sRGB
+ case PIPE_FORMAT_L8A8_SRGB:
+ return MESA_FORMAT_SLA8;
+ case PIPE_FORMAT_L8_SRGB:
+ return MESA_FORMAT_SL8;
+ case PIPE_FORMAT_R8G8B8_SRGB:
+ return MESA_FORMAT_SRGB8;
+ case PIPE_FORMAT_A8B8G8R8_SRGB:
+ return MESA_FORMAT_SRGBA8;
+ case PIPE_FORMAT_B8G8R8A8_SRGB:
+ return MESA_FORMAT_SARGB8;
+#endif
+
+ case PIPE_FORMAT_R8_UNORM:
+ return MESA_FORMAT_R8;
+ case PIPE_FORMAT_R16_UNORM:
+ return MESA_FORMAT_R16;
+ case PIPE_FORMAT_R8G8_UNORM:
+ return MESA_FORMAT_RG88;
+ case PIPE_FORMAT_R16G16_UNORM:
+ return MESA_FORMAT_RG1616;
+
+ /* signed int formats */
+ case PIPE_FORMAT_R8G8B8A8_SSCALED:
+ return MESA_FORMAT_RGBA_INT8;
+ case PIPE_FORMAT_R16G16B16A16_SSCALED:
+ return MESA_FORMAT_RGBA_INT16;
+ case PIPE_FORMAT_R32G32B32A32_SSCALED:
+ return MESA_FORMAT_RGBA_INT32;
+
+ /* unsigned int formats */
+ case PIPE_FORMAT_R8G8B8A8_USCALED:
+ return MESA_FORMAT_RGBA_UINT8;
+ case PIPE_FORMAT_R16G16B16A16_USCALED:
+ return MESA_FORMAT_RGBA_UINT16;
+ case PIPE_FORMAT_R32G32B32A32_USCALED:
+ return MESA_FORMAT_RGBA_UINT32;
+
+ default:
+ assert(0);
+ return MESA_FORMAT_NONE;
+ }
+}
+
+
+/**
+ * Return first supported format from the given list.
+ */
+static enum pipe_format
+find_supported_format(struct pipe_screen *screen,
+ const enum pipe_format formats[],
+ uint num_formats,
+ enum pipe_texture_target target,
+ unsigned sample_count,
+ unsigned tex_usage,
+ unsigned geom_flags)
+{
+ uint i;
+ for (i = 0; i < num_formats; i++) {
+ if (screen->is_format_supported(screen, formats[i], target,
+ sample_count, tex_usage, geom_flags)) {
+ return formats[i];
+ }
+ }
+ return PIPE_FORMAT_NONE;
+}
+
+
+/**
+ * Find an RGBA format supported by the context/winsys.
+ */
+static enum pipe_format
+default_rgba_format(struct pipe_screen *screen,
+ enum pipe_texture_target target,
+ unsigned sample_count,
+ unsigned tex_usage,
+ unsigned geom_flags)
+{
+ static const enum pipe_format colorFormats[] = {
+ PIPE_FORMAT_B8G8R8A8_UNORM,
+ PIPE_FORMAT_A8R8G8B8_UNORM,
+ PIPE_FORMAT_A8B8G8R8_UNORM,
+ PIPE_FORMAT_B5G6R5_UNORM
+ };
+ return find_supported_format(screen, colorFormats, Elements(colorFormats),
+ target, sample_count, tex_usage, geom_flags);
+}
+
+
+/**
+ * Find an RGB format supported by the context/winsys.
+ */
+static enum pipe_format
+default_rgb_format(struct pipe_screen *screen,
+ enum pipe_texture_target target,
+ unsigned sample_count,
+ unsigned tex_usage,
+ unsigned geom_flags)
+{
+ static const enum pipe_format colorFormats[] = {
+ PIPE_FORMAT_B8G8R8X8_UNORM,
+ PIPE_FORMAT_X8R8G8B8_UNORM,
+ PIPE_FORMAT_X8B8G8R8_UNORM,
+ PIPE_FORMAT_B8G8R8A8_UNORM,
+ PIPE_FORMAT_A8R8G8B8_UNORM,
+ PIPE_FORMAT_A8B8G8R8_UNORM,
+ PIPE_FORMAT_B5G6R5_UNORM
+ };
+ return find_supported_format(screen, colorFormats, Elements(colorFormats),
+ target, sample_count, tex_usage, geom_flags);
+}
+
+/**
+ * Find an sRGBA format supported by the context/winsys.
+ */
+static enum pipe_format
+default_srgba_format(struct pipe_screen *screen,
+ enum pipe_texture_target target,
+ unsigned sample_count,
+ unsigned tex_usage,
+ unsigned geom_flags)
+{
+ static const enum pipe_format colorFormats[] = {
+ PIPE_FORMAT_B8G8R8A8_SRGB,
+ PIPE_FORMAT_A8R8G8B8_SRGB,
+ PIPE_FORMAT_A8B8G8R8_SRGB,
+ };
+ return find_supported_format(screen, colorFormats, Elements(colorFormats),
+ target, sample_count, tex_usage, geom_flags);
+}
+
+
+/**
+ * Given an OpenGL internalFormat value for a texture or surface, return
+ * the best matching PIPE_FORMAT_x, or PIPE_FORMAT_NONE if there's no match.
+ * This is called during glTexImage2D, for example.
+ *
+ * The bindings parameter typically has PIPE_BIND_SAMPLER_VIEW set, plus
+ * either PIPE_BINDING_RENDER_TARGET or PIPE_BINDING_DEPTH_STENCIL if
+ * we want render-to-texture ability.
+ *
+ * \param internalFormat the user value passed to glTexImage2D
+ * \param target one of PIPE_TEXTURE_x
+ * \param bindings bitmask of PIPE_BIND_x flags.
+ */
+enum pipe_format
+st_choose_format(struct pipe_screen *screen, GLenum internalFormat,
+ enum pipe_texture_target target, unsigned sample_count,
+ unsigned bindings)
+{
+ unsigned geom_flags = 0; /* we don't care about POT vs. NPOT here, yet */
+
+ switch (internalFormat) {
+ case GL_RGB10:
+ case GL_RGB10_A2:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B10G10R10A2_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B10G10R10A2_UNORM;
+ /* Pass through. */
+ case 4:
+ case GL_RGBA:
+ case GL_RGBA8:
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_BGRA:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B8G8R8A8_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B8G8R8A8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case 3:
+ case GL_RGB:
+ case GL_RGB8:
+ return default_rgb_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_RGB12:
+ case GL_RGB16:
+ case GL_RGBA12:
+ case GL_RGBA16:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_R16G16B16A16_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_R16G16B16A16_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_RGBA4:
+ case GL_RGBA2:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B4G4R4A4_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B4G4R4A4_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_RGB5_A1:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B5G5R5A1_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B5G5R5A1_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_R3_G3_B2:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B2G3R3_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B2G3R3_UNORM;
+ /* Pass through. */
+ case GL_RGB5:
+ case GL_RGB4:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B5G6R5_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B5G6R5_UNORM;
+ if (screen->is_format_supported( screen, PIPE_FORMAT_B5G5R5A1_UNORM,
+ target, sample_count, bindings,
+ geom_flags ))
+ return PIPE_FORMAT_B5G5R5A1_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_ALPHA12:
+ case GL_ALPHA16:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_A16_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_A16_UNORM;
+ /* Pass through. */
+ case GL_ALPHA:
+ case GL_ALPHA4:
+ case GL_ALPHA8:
+ case GL_COMPRESSED_ALPHA:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_A8_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_A8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_LUMINANCE12:
+ case GL_LUMINANCE16:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L16_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L16_UNORM;
+ /* Pass through. */
+ case 1:
+ case GL_LUMINANCE:
+ case GL_LUMINANCE4:
+ case GL_LUMINANCE8:
+ case GL_COMPRESSED_LUMINANCE:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L8_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_LUMINANCE12_ALPHA4:
+ case GL_LUMINANCE12_ALPHA12:
+ case GL_LUMINANCE16_ALPHA16:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L16A16_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L16A16_UNORM;
+ /* Pass through. */
+ case 2:
+ case GL_LUMINANCE_ALPHA:
+ case GL_LUMINANCE6_ALPHA2:
+ case GL_LUMINANCE8_ALPHA8:
+ case GL_COMPRESSED_LUMINANCE_ALPHA:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L8A8_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L8A8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_LUMINANCE4_ALPHA4:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L4A4_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L4A4_UNORM;
+ if (screen->is_format_supported( screen, PIPE_FORMAT_L8A8_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_L8A8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_INTENSITY12:
+ case GL_INTENSITY16:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_I16_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_I16_UNORM;
+ /* Pass through. */
+ case GL_INTENSITY:
+ case GL_INTENSITY4:
+ case GL_INTENSITY8:
+ case GL_COMPRESSED_INTENSITY:
+ if (screen->is_format_supported( screen, PIPE_FORMAT_I8_UNORM, target,
+ sample_count, bindings, geom_flags ))
+ return PIPE_FORMAT_I8_UNORM;
+ return default_rgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_YCBCR_MESA:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_UYVY, target,
+ sample_count, bindings, geom_flags)) {
+ return PIPE_FORMAT_UYVY;
+ }
+ if (screen->is_format_supported(screen, PIPE_FORMAT_YUYV, target,
+ sample_count, bindings, geom_flags)) {
+ return PIPE_FORMAT_YUYV;
+ }
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_RED:
+ case GL_COMPRESSED_RG:
+ case GL_COMPRESSED_RGB:
+ /* can only sample from compressed formats */
+ if (bindings & ~PIPE_BIND_SAMPLER_VIEW)
+ return PIPE_FORMAT_NONE;
+ else if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGB,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT1_RGB;
+ else
+ return default_rgb_format(screen, target, sample_count, bindings,
+ geom_flags);
+
+ case GL_COMPRESSED_RGBA:
+ /* can only sample from compressed formats */
+ if (bindings & ~PIPE_BIND_SAMPLER_VIEW)
+ return PIPE_FORMAT_NONE;
+ else if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_RGBA,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT3_RGBA;
+ else
+ return default_rgba_format(screen, target, sample_count, bindings,
+ geom_flags);
+
+ case GL_RGB_S3TC:
+ case GL_RGB4_S3TC:
+ case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGB,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT1_RGB;
+ else
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_RGBA,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT1_RGBA;
+ else
+ return PIPE_FORMAT_NONE;
+
+ case GL_RGBA_S3TC:
+ case GL_RGBA4_S3TC:
+ case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_RGBA,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT3_RGBA;
+ else
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT5_RGBA,
+ target, sample_count, bindings,
+ geom_flags))
+ return PIPE_FORMAT_DXT5_RGBA;
+ else
+ return PIPE_FORMAT_NONE;
+
+#if 0
+ case GL_COMPRESSED_RGB_FXT1_3DFX:
+ return PIPE_FORMAT_RGB_FXT1;
+ case GL_COMPRESSED_RGBA_FXT1_3DFX:
+ return PIPE_FORMAT_RGB_FXT1;
+#endif
+
+ case GL_DEPTH_COMPONENT16:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_Z16_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_Z16_UNORM;
+ /* fall-through */
+ case GL_DEPTH_COMPONENT24:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_Z24_UNORM_S8_USCALED,
+ target, sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_Z24_UNORM_S8_USCALED;
+ if (screen->is_format_supported(screen, PIPE_FORMAT_S8_USCALED_Z24_UNORM,
+ target, sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_S8_USCALED_Z24_UNORM;
+ /* fall-through */
+ case GL_DEPTH_COMPONENT32:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_Z32_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_Z32_UNORM;
+ /* fall-through */
+ case GL_DEPTH_COMPONENT:
+ {
+ static const enum pipe_format formats[] = {
+ PIPE_FORMAT_Z32_UNORM,
+ PIPE_FORMAT_Z24_UNORM_S8_USCALED,
+ PIPE_FORMAT_S8_USCALED_Z24_UNORM,
+ PIPE_FORMAT_Z16_UNORM
+ };
+ return find_supported_format(screen, formats, Elements(formats),
+ target, sample_count, bindings, geom_flags);
+ }
+
+ case GL_STENCIL_INDEX:
+ case GL_STENCIL_INDEX1_EXT:
+ case GL_STENCIL_INDEX4_EXT:
+ case GL_STENCIL_INDEX8_EXT:
+ case GL_STENCIL_INDEX16_EXT:
+ {
+ static const enum pipe_format formats[] = {
+ PIPE_FORMAT_S8_USCALED,
+ PIPE_FORMAT_Z24_UNORM_S8_USCALED,
+ PIPE_FORMAT_S8_USCALED_Z24_UNORM
+ };
+ return find_supported_format(screen, formats, Elements(formats),
+ target, sample_count, bindings, geom_flags);
+ }
+
+ case GL_DEPTH_STENCIL_EXT:
+ case GL_DEPTH24_STENCIL8_EXT:
+ {
+ static const enum pipe_format formats[] = {
+ PIPE_FORMAT_Z24_UNORM_S8_USCALED,
+ PIPE_FORMAT_S8_USCALED_Z24_UNORM
+ };
+ return find_supported_format(screen, formats, Elements(formats),
+ target, sample_count, bindings, geom_flags);
+ }
+
+ case GL_SRGB_EXT:
+ case GL_SRGB8_EXT:
+ case GL_SRGB_ALPHA_EXT:
+ case GL_SRGB8_ALPHA8_EXT:
+ return default_srgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_COMPRESSED_SRGB_EXT:
+ case GL_COMPRESSED_SRGB_S3TC_DXT1_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT1_SRGB, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_DXT1_SRGB;
+ return default_srgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:
+ return PIPE_FORMAT_DXT1_SRGBA;
+
+ case GL_COMPRESSED_SRGB_ALPHA_EXT:
+ case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_DXT3_SRGBA, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_DXT3_SRGBA;
+ return default_srgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:
+ return PIPE_FORMAT_DXT5_SRGBA;
+
+ case GL_SLUMINANCE_ALPHA_EXT:
+ case GL_SLUMINANCE8_ALPHA8_EXT:
+ case GL_COMPRESSED_SLUMINANCE_EXT:
+ case GL_COMPRESSED_SLUMINANCE_ALPHA_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_L8A8_SRGB, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_L8A8_SRGB;
+ return default_srgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_SLUMINANCE_EXT:
+ case GL_SLUMINANCE8_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_L8_SRGB, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_L8_SRGB;
+ return default_srgba_format( screen, target, sample_count, bindings,
+ geom_flags );
+
+ case GL_RED:
+ case GL_R8:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R8_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R8_UNORM;
+ return PIPE_FORMAT_NONE;
+ case GL_RG:
+ case GL_RG8:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R8G8_UNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_R16:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R16_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R16_UNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_RG16:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R16G16_UNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_RED_RGTC1:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC1_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_RGTC1_UNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_SIGNED_RED_RGTC1:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC1_SNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_RGTC1_SNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_RG_RGTC2:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC2_UNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_RGTC2_UNORM;
+ return PIPE_FORMAT_NONE;
+
+ case GL_COMPRESSED_SIGNED_RG_RGTC2:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_RGTC2_SNORM, target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_RGTC2_SNORM;
+ return PIPE_FORMAT_NONE;
+
+ /* signed/unsigned integer formats.
+ * XXX Mesa only has formats for RGBA signed/unsigned integer formats.
+ * If/when new formats are added this code should be updated.
+ */
+ case GL_RED_INTEGER_EXT:
+ case GL_GREEN_INTEGER_EXT:
+ case GL_BLUE_INTEGER_EXT:
+ case GL_ALPHA_INTEGER_EXT:
+ case GL_RGB_INTEGER_EXT:
+ case GL_RGBA_INTEGER_EXT:
+ case GL_BGR_INTEGER_EXT:
+ case GL_BGRA_INTEGER_EXT:
+ case GL_LUMINANCE_INTEGER_EXT:
+ case GL_LUMINANCE_ALPHA_INTEGER_EXT:
+ /* fall-through */
+ case GL_RGBA8I_EXT:
+ case GL_RGB8I_EXT:
+ case GL_ALPHA8I_EXT:
+ case GL_INTENSITY8I_EXT:
+ case GL_LUMINANCE8I_EXT:
+ case GL_LUMINANCE_ALPHA8I_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8B8A8_SSCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R8G8B8A8_SSCALED;
+ return PIPE_FORMAT_NONE;
+ case GL_RGBA16I_EXT:
+ case GL_RGB16I_EXT:
+ case GL_ALPHA16I_EXT:
+ case GL_INTENSITY16I_EXT:
+ case GL_LUMINANCE16I_EXT:
+ case GL_LUMINANCE_ALPHA16I_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16B16A16_SSCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R16G16B16A16_SSCALED;
+ return PIPE_FORMAT_NONE;
+ case GL_RGBA32I_EXT:
+ case GL_RGB32I_EXT:
+ case GL_ALPHA32I_EXT:
+ case GL_INTENSITY32I_EXT:
+ case GL_LUMINANCE32I_EXT:
+ case GL_LUMINANCE_ALPHA32I_EXT:
+ /* xxx */
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R32G32B32A32_SSCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R32G32B32A32_SSCALED;
+ return PIPE_FORMAT_NONE;
+
+ case GL_RGBA8UI_EXT:
+ case GL_RGB8UI_EXT:
+ case GL_ALPHA8UI_EXT:
+ case GL_INTENSITY8UI_EXT:
+ case GL_LUMINANCE8UI_EXT:
+ case GL_LUMINANCE_ALPHA8UI_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R8G8B8A8_USCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R8G8B8A8_USCALED;
+ return PIPE_FORMAT_NONE;
+
+ case GL_RGBA16UI_EXT:
+ case GL_RGB16UI_EXT:
+ case GL_ALPHA16UI_EXT:
+ case GL_INTENSITY16UI_EXT:
+ case GL_LUMINANCE16UI_EXT:
+ case GL_LUMINANCE_ALPHA16UI_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R16G16B16A16_USCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R16G16B16A16_USCALED;
+ return PIPE_FORMAT_NONE;
+
+ case GL_RGBA32UI_EXT:
+ case GL_RGB32UI_EXT:
+ case GL_ALPHA32UI_EXT:
+ case GL_INTENSITY32UI_EXT:
+ case GL_LUMINANCE32UI_EXT:
+ case GL_LUMINANCE_ALPHA32UI_EXT:
+ if (screen->is_format_supported(screen, PIPE_FORMAT_R32G32B32A32_USCALED,
+ target,
+ sample_count, bindings, geom_flags))
+ return PIPE_FORMAT_R32G32B32A32_USCALED;
+ return PIPE_FORMAT_NONE;
+
+ default:
+ return PIPE_FORMAT_NONE;
+ }
+}
+
+
+/**
+ * Called by FBO code to choose a PIPE_FORMAT_ for drawing surfaces.
+ */
+enum pipe_format
+st_choose_renderbuffer_format(struct pipe_screen *screen,
+ GLenum internalFormat, unsigned sample_count)
+{
+ uint usage;
+ if (_mesa_is_depth_or_stencil_format(internalFormat))
+ usage = PIPE_BIND_DEPTH_STENCIL;
+ else
+ usage = PIPE_BIND_RENDER_TARGET;
+ return st_choose_format(screen, internalFormat, PIPE_TEXTURE_2D,
+ sample_count, usage);
+}
+
+
+/**
+ * Called via ctx->Driver.chooseTextureFormat().
+ */
+gl_format
+st_ChooseTextureFormat_renderable(struct gl_context *ctx, GLint internalFormat,
+ GLenum format, GLenum type, GLboolean renderable)
+{
+ struct pipe_screen *screen = st_context(ctx)->pipe->screen;
+ enum pipe_format pFormat;
+ uint bindings;
+
+ (void) format;
+ (void) type;
+
+ /* GL textures may wind up being render targets, but we don't know
+ * that in advance. Specify potential render target flags now.
+ */
+ bindings = PIPE_BIND_SAMPLER_VIEW;
+ if (renderable == GL_TRUE) {
+ if (_mesa_is_depth_format(internalFormat) ||
+ _mesa_is_depth_or_stencil_format(internalFormat))
+ bindings |= PIPE_BIND_DEPTH_STENCIL;
+ else
+ bindings |= PIPE_BIND_RENDER_TARGET;
+ }
+
+ pFormat = st_choose_format(screen, internalFormat,
+ PIPE_TEXTURE_2D, 0, bindings);
+
+ if (pFormat == PIPE_FORMAT_NONE) {
+ /* try choosing format again, this time without render target bindings */
+ pFormat = st_choose_format(screen, internalFormat,
+ PIPE_TEXTURE_2D, 0, PIPE_BIND_SAMPLER_VIEW);
+ }
+
+ if (pFormat == PIPE_FORMAT_NONE) {
+ /* no luck at all */
+ return MESA_FORMAT_NONE;
+ }
+
+ return st_pipe_format_to_mesa_format(pFormat);
+}
+
+gl_format
+st_ChooseTextureFormat(struct gl_context *ctx, GLint internalFormat,
+ GLenum format, GLenum type)
+{
+ boolean want_renderable =
+ internalFormat == 3 || internalFormat == 4 ||
+ internalFormat == GL_RGB || internalFormat == GL_RGBA ||
+ internalFormat == GL_RGB8 || internalFormat == GL_RGBA8 ||
+ internalFormat == GL_BGRA;
+
+ return st_ChooseTextureFormat_renderable(ctx, internalFormat,
+ format, type, want_renderable);
+}
+
+/**
+ * Test if a gallium format is equivalent to a GL format/type.
+ */
+GLboolean
+st_equal_formats(enum pipe_format pFormat, GLenum format, GLenum type)
+{
+ switch (pFormat) {
+ case PIPE_FORMAT_A8B8G8R8_UNORM:
+ return format == GL_RGBA && type == GL_UNSIGNED_BYTE;
+ case PIPE_FORMAT_A8R8G8B8_UNORM:
+ return format == GL_BGRA && type == GL_UNSIGNED_BYTE;
+ case PIPE_FORMAT_B5G6R5_UNORM:
+ return format == GL_RGB && type == GL_UNSIGNED_SHORT_5_6_5;
+ /* XXX more combos... */
+ default:
+ return GL_FALSE;
+ }
+}
+
+GLboolean
+st_sampler_compat_formats(enum pipe_format format1, enum pipe_format format2)
+{
+ if (format1 == format2)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_B8G8R8A8_UNORM &&
+ format2 == PIPE_FORMAT_B8G8R8X8_UNORM)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_B8G8R8X8_UNORM &&
+ format2 == PIPE_FORMAT_B8G8R8A8_UNORM)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_A8B8G8R8_UNORM &&
+ format2 == PIPE_FORMAT_X8B8G8R8_UNORM)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_X8B8G8R8_UNORM &&
+ format2 == PIPE_FORMAT_A8B8G8R8_UNORM)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_A8R8G8B8_UNORM &&
+ format2 == PIPE_FORMAT_X8R8G8B8_UNORM)
+ return GL_TRUE;
+
+ if (format1 == PIPE_FORMAT_X8R8G8B8_UNORM &&
+ format2 == PIPE_FORMAT_A8R8G8B8_UNORM)
+ return GL_TRUE;
+
+ return GL_FALSE;
+}
+
+
+
+/**
+ * This is used for translating texture border color and the clear
+ * color. For example, the clear color is interpreted according to
+ * the renderbuffer's base format. For example, if clearing a
+ * GL_LUMINANCE buffer, ClearColor[0] = luminance and ClearColor[1] =
+ * alpha. Similarly for texture border colors.
+ */
+void
+st_translate_color(const GLfloat colorIn[4], GLenum baseFormat,
+ GLfloat colorOut[4])
+{
+ switch (baseFormat) {
+ case GL_RED:
+ colorOut[0] = colorIn[0];
+ colorOut[1] = 0.0F;
+ colorOut[2] = 0.0F;
+ colorOut[3] = 1.0F;
+ break;
+ case GL_RG:
+ colorOut[0] = colorIn[0];
+ colorOut[1] = colorIn[1];
+ colorOut[2] = 0.0F;
+ colorOut[3] = 1.0F;
+ break;
+ case GL_RGB:
+ colorOut[0] = colorIn[0];
+ colorOut[1] = colorIn[1];
+ colorOut[2] = colorIn[2];
+ colorOut[3] = 1.0F;
+ break;
+ case GL_ALPHA:
+ colorOut[0] = colorOut[1] = colorOut[2] = 0.0;
+ colorOut[3] = colorIn[3];
+ break;
+ case GL_LUMINANCE:
+ colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0];
+ colorOut[3] = 1.0;
+ break;
+ case GL_LUMINANCE_ALPHA:
+ colorOut[0] = colorOut[1] = colorOut[2] = colorIn[0];
+ colorOut[3] = colorIn[3];
+ break;
+ case GL_INTENSITY:
+ colorOut[0] = colorOut[1] = colorOut[2] = colorOut[3] = colorIn[0];
+ break;
+ default:
+ COPY_4V(colorOut, colorIn);
+ }
+}
diff --git a/mesalib/src/mesa/state_tracker/st_format.h b/mesalib/src/mesa/state_tracker/st_format.h
index 0fb570f6e..d31e60711 100644
--- a/mesalib/src/mesa/state_tracker/st_format.h
+++ b/mesalib/src/mesa/state_tracker/st_format.h
@@ -1,86 +1,86 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * Copyright (c) 2010 VMware, Inc.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 ST_FORMAT_H
-#define ST_FORMAT_H
-
-#include "main/formats.h"
-#include "main/glheader.h"
-
-#include "pipe/p_defines.h"
-#include "pipe/p_format.h"
-
-struct gl_context;
-struct pipe_screen;
-
-extern GLenum
-st_format_datatype(enum pipe_format format);
-
-
-extern enum pipe_format
-st_mesa_format_to_pipe_format(gl_format mesaFormat);
-
-extern gl_format
-st_pipe_format_to_mesa_format(enum pipe_format pipeFormat);
-
-
-extern enum pipe_format
-st_choose_format(struct pipe_screen *screen, GLenum internalFormat,
- enum pipe_texture_target target, unsigned sample_count,
- unsigned tex_usage);
-
-extern enum pipe_format
-st_choose_renderbuffer_format(struct pipe_screen *screen,
- GLenum internalFormat, unsigned sample_count);
-
-
-gl_format
-st_ChooseTextureFormat_renderable(struct gl_context *ctx, GLint internalFormat,
- GLenum format, GLenum type, GLboolean renderable);
-
-extern gl_format
-st_ChooseTextureFormat(struct gl_context * ctx, GLint internalFormat,
- GLenum format, GLenum type);
-
-
-extern GLboolean
-st_equal_formats(enum pipe_format pFormat, GLenum format, GLenum type);
-
-/* can we use a sampler view to translate these formats
- only used to make TFP so far */
-extern GLboolean
-st_sampler_compat_formats(enum pipe_format format1, enum pipe_format format2);
-
-
-extern void
-st_translate_color(const GLfloat colorIn[4], GLenum baseFormat,
- GLfloat colorOut[4]);
-
-
-#endif /* ST_FORMAT_H */
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * Copyright (c) 2010 VMware, Inc.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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 ST_FORMAT_H
+#define ST_FORMAT_H
+
+#include "main/formats.h"
+#include "main/glheader.h"
+
+#include "pipe/p_defines.h"
+#include "pipe/p_format.h"
+
+struct gl_context;
+struct pipe_screen;
+
+extern GLenum
+st_format_datatype(enum pipe_format format);
+
+
+extern enum pipe_format
+st_mesa_format_to_pipe_format(gl_format mesaFormat);
+
+extern gl_format
+st_pipe_format_to_mesa_format(enum pipe_format pipeFormat);
+
+
+extern enum pipe_format
+st_choose_format(struct pipe_screen *screen, GLenum internalFormat,
+ enum pipe_texture_target target, unsigned sample_count,
+ unsigned tex_usage);
+
+extern enum pipe_format
+st_choose_renderbuffer_format(struct pipe_screen *screen,
+ GLenum internalFormat, unsigned sample_count);
+
+
+gl_format
+st_ChooseTextureFormat_renderable(struct gl_context *ctx, GLint internalFormat,
+ GLenum format, GLenum type, GLboolean renderable);
+
+extern gl_format
+st_ChooseTextureFormat(struct gl_context * ctx, GLint internalFormat,
+ GLenum format, GLenum type);
+
+
+extern GLboolean
+st_equal_formats(enum pipe_format pFormat, GLenum format, GLenum type);
+
+/* can we use a sampler view to translate these formats
+ only used to make TFP so far */
+extern GLboolean
+st_sampler_compat_formats(enum pipe_format format1, enum pipe_format format2);
+
+
+extern void
+st_translate_color(const GLfloat colorIn[4], GLenum baseFormat,
+ GLfloat colorOut[4]);
+
+
+#endif /* ST_FORMAT_H */
diff --git a/mesalib/src/mesa/state_tracker/st_gen_mipmap.c b/mesalib/src/mesa/state_tracker/st_gen_mipmap.c
index 4bf682808..d04ec696f 100644
--- a/mesalib/src/mesa/state_tracker/st_gen_mipmap.c
+++ b/mesalib/src/mesa/state_tracker/st_gen_mipmap.c
@@ -1,422 +1,422 @@
-/**************************************************************************
- *
- * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-
-#include "main/imports.h"
-#include "main/mipmap.h"
-#include "main/teximage.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "util/u_inlines.h"
-#include "util/u_format.h"
-#include "util/u_gen_mipmap.h"
-
-#include "st_debug.h"
-#include "st_context.h"
-#include "st_texture.h"
-#include "st_gen_mipmap.h"
-#include "st_cb_texture.h"
-
-
-/**
- * one-time init for generate mipmap
- * XXX Note: there may be other times we need no-op/simple state like this.
- * In that case, some code refactoring would be good.
- */
-void
-st_init_generate_mipmap(struct st_context *st)
-{
- st->gen_mipmap = util_create_gen_mipmap(st->pipe, st->cso_context);
-}
-
-
-void
-st_destroy_generate_mipmap(struct st_context *st)
-{
- util_destroy_gen_mipmap(st->gen_mipmap);
- st->gen_mipmap = NULL;
-}
-
-
-/**
- * Generate mipmap levels using hardware rendering.
- * \return TRUE if successful, FALSE if not possible
- */
-static boolean
-st_render_mipmap(struct st_context *st,
- GLenum target,
- struct st_texture_object *stObj,
- uint baseLevel, uint lastLevel)
-{
- struct pipe_context *pipe = st->pipe;
- struct pipe_screen *screen = pipe->screen;
- struct pipe_sampler_view *psv = st_get_texture_sampler_view(stObj, pipe);
- const uint face = _mesa_tex_target_to_face(target);
-
- assert(psv->texture == stObj->pt);
-#if 0
- assert(target != GL_TEXTURE_3D); /* implemented but untested */
-#endif
-
- /* check if we can render in the texture's format */
- /* XXX should probably kill this and always use util_gen_mipmap
- since this implements a sw fallback as well */
- if (!screen->is_format_supported(screen, psv->format, psv->texture->target,
- 0, PIPE_BIND_RENDER_TARGET, 0)) {
- return FALSE;
- }
-
- util_gen_mipmap(st->gen_mipmap, psv, face, baseLevel, lastLevel,
- PIPE_TEX_FILTER_LINEAR);
-
- return TRUE;
-}
-
-
-/**
- * Helper function to decompress an image. The result is a 32-bpp RGBA
- * image with stride==width.
- */
-static void
-decompress_image(enum pipe_format format,
- const uint8_t *src, uint8_t *dst,
- unsigned width, unsigned height, unsigned src_stride)
-{
- const struct util_format_description *desc = util_format_description(format);
- const uint bw = util_format_get_blockwidth(format);
- const uint bh = util_format_get_blockheight(format);
- const uint dst_stride = 4 * MAX2(width, bw);
-
- desc->unpack_rgba_8unorm(dst, dst_stride, src, src_stride, width, height);
-
- if (width < bw || height < bh) {
- /* We're decompressing an image smaller than the compression
- * block size. We don't want garbage pixel values in the region
- * outside (width x height) so replicate pixels from the (width
- * x height) region to fill out the (bw x bh) block size.
- */
- uint x, y;
- for (y = 0; y < bh; y++) {
- for (x = 0; x < bw; x++) {
- if (x >= width || y >= height) {
- uint p = (y * bw + x) * 4;
- dst[p + 0] = dst[0];
- dst[p + 1] = dst[1];
- dst[p + 2] = dst[2];
- dst[p + 3] = dst[3];
- }
- }
- }
- }
-}
-
-
-/**
- * Helper function to compress an image. The source is a 32-bpp RGBA image
- * with stride==width.
- */
-static void
-compress_image(enum pipe_format format,
- const uint8_t *src, uint8_t *dst,
- unsigned width, unsigned height, unsigned dst_stride)
-{
- const struct util_format_description *desc = util_format_description(format);
- const uint src_stride = 4 * width;
-
- desc->pack_rgba_8unorm(dst, dst_stride, src, src_stride, width, height);
-}
-
-
-/**
- * Software fallback for generate mipmap levels.
- */
-static void
-fallback_generate_mipmap(struct gl_context *ctx, GLenum target,
- struct gl_texture_object *texObj)
-{
- struct pipe_context *pipe = st_context(ctx)->pipe;
- struct pipe_resource *pt = st_get_texobj_resource(texObj);
- const uint baseLevel = texObj->BaseLevel;
- const uint lastLevel = pt->last_level;
- const uint face = _mesa_tex_target_to_face(target);
- uint dstLevel;
- GLenum datatype;
- GLuint comps;
- GLboolean compressed;
-
- if (ST_DEBUG & DEBUG_FALLBACK)
- debug_printf("%s: fallback processing\n", __FUNCTION__);
-
- assert(target != GL_TEXTURE_3D); /* not done yet */
-
- compressed =
- _mesa_is_format_compressed(texObj->Image[face][baseLevel]->TexFormat);
-
- if (compressed) {
- datatype = GL_UNSIGNED_BYTE;
- comps = 4;
- }
- else {
- _mesa_format_to_type_and_comps(texObj->Image[face][baseLevel]->TexFormat,
- &datatype, &comps);
- assert(comps > 0 && "bad texture format in fallback_generate_mipmap()");
- }
-
- for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
- const uint srcLevel = dstLevel - 1;
- const uint srcWidth = u_minify(pt->width0, srcLevel);
- const uint srcHeight = u_minify(pt->height0, srcLevel);
- const uint srcDepth = u_minify(pt->depth0, srcLevel);
- const uint dstWidth = u_minify(pt->width0, dstLevel);
- const uint dstHeight = u_minify(pt->height0, dstLevel);
- const uint dstDepth = u_minify(pt->depth0, dstLevel);
- struct pipe_transfer *srcTrans, *dstTrans;
- const ubyte *srcData;
- ubyte *dstData;
- int srcStride, dstStride;
-
- srcTrans = pipe_get_transfer(st_context(ctx)->pipe, pt, srcLevel,
- face,
- PIPE_TRANSFER_READ, 0, 0,
- srcWidth, srcHeight);
-
- dstTrans = pipe_get_transfer(st_context(ctx)->pipe, pt, dstLevel,
- face,
- PIPE_TRANSFER_WRITE, 0, 0,
- dstWidth, dstHeight);
-
- srcData = (ubyte *) pipe_transfer_map(pipe, srcTrans);
- dstData = (ubyte *) pipe_transfer_map(pipe, dstTrans);
-
- srcStride = srcTrans->stride / util_format_get_blocksize(srcTrans->resource->format);
- dstStride = dstTrans->stride / util_format_get_blocksize(dstTrans->resource->format);
-
- /* this cannot work correctly for 3d since it does
- not respect layerStride. */
- if (compressed) {
- const enum pipe_format format = pt->format;
- const uint bw = util_format_get_blockwidth(format);
- const uint bh = util_format_get_blockheight(format);
- const uint srcWidth2 = align(srcWidth, bw);
- const uint srcHeight2 = align(srcHeight, bh);
- const uint dstWidth2 = align(dstWidth, bw);
- const uint dstHeight2 = align(dstHeight, bh);
- uint8_t *srcTemp, *dstTemp;
-
- assert(comps == 4);
-
- srcTemp = malloc(srcWidth2 * srcHeight2 * comps + 000);
- dstTemp = malloc(dstWidth2 * dstHeight2 * comps + 000);
-
- /* decompress the src image: srcData -> srcTemp */
- decompress_image(format, srcData, srcTemp, srcWidth, srcHeight, srcTrans->stride);
-
- _mesa_generate_mipmap_level(target, datatype, comps,
- 0 /*border*/,
- srcWidth2, srcHeight2, srcDepth,
- srcTemp,
- srcWidth2, /* stride in texels */
- dstWidth2, dstHeight2, dstDepth,
- dstTemp,
- dstWidth2); /* stride in texels */
-
- /* compress the new image: dstTemp -> dstData */
- compress_image(format, dstTemp, dstData, dstWidth, dstHeight, dstTrans->stride);
-
- free(srcTemp);
- free(dstTemp);
- }
- else {
- _mesa_generate_mipmap_level(target, datatype, comps,
- 0 /*border*/,
- srcWidth, srcHeight, srcDepth,
- srcData,
- srcStride, /* stride in texels */
- dstWidth, dstHeight, dstDepth,
- dstData,
- dstStride); /* stride in texels */
- }
-
- pipe_transfer_unmap(pipe, srcTrans);
- pipe_transfer_unmap(pipe, dstTrans);
-
- pipe->transfer_destroy(pipe, srcTrans);
- pipe->transfer_destroy(pipe, dstTrans);
- }
-}
-
-
-/**
- * Compute the expected number of mipmap levels in the texture given
- * the width/height/depth of the base image and the GL_TEXTURE_BASE_LEVEL/
- * GL_TEXTURE_MAX_LEVEL settings. This will tell us how many mipmap
- * levels should be generated.
- */
-static GLuint
-compute_num_levels(struct gl_context *ctx,
- struct gl_texture_object *texObj,
- GLenum target)
-{
- if (target == GL_TEXTURE_RECTANGLE_ARB) {
- return 1;
- }
- else {
- const struct gl_texture_image *baseImage =
- _mesa_get_tex_image(ctx, texObj, target, texObj->BaseLevel);
- GLuint size, numLevels;
-
- size = MAX2(baseImage->Width2, baseImage->Height2);
- size = MAX2(size, baseImage->Depth2);
-
- numLevels = texObj->BaseLevel;
-
- while (size > 0) {
- numLevels++;
- size >>= 1;
- }
-
- numLevels = MIN2(numLevels, texObj->MaxLevel + 1);
-
- assert(numLevels >= 1);
-
- return numLevels;
- }
-}
-
-
-/**
- * Called via ctx->Driver.GenerateMipmap().
- */
-void
-st_generate_mipmap(struct gl_context *ctx, GLenum target,
- struct gl_texture_object *texObj)
-{
- struct st_context *st = st_context(ctx);
- struct st_texture_object *stObj = st_texture_object(texObj);
- struct pipe_resource *pt = st_get_texobj_resource(texObj);
- const uint baseLevel = texObj->BaseLevel;
- uint lastLevel;
- uint dstLevel;
-
- if (!pt)
- return;
-
- /* not sure if this ultimately actually should work,
- but we're not supporting multisampled textures yet. */
- assert(pt->nr_samples < 2);
-
- /* find expected last mipmap level to generate*/
- lastLevel = compute_num_levels(ctx, texObj, target) - 1;
-
- if (lastLevel == 0)
- return;
-
- /* The texture isn't in a "complete" state yet so set the expected
- * lastLevel here, since it won't get done in st_finalize_texture().
- */
- stObj->lastLevel = lastLevel;
-
- if (pt->last_level < lastLevel) {
- /* The current gallium texture doesn't have space for all the
- * mipmap levels we need to generate. So allocate a new texture.
- */
- struct pipe_resource *oldTex = stObj->pt;
-
- /* create new texture with space for more levels */
- stObj->pt = st_texture_create(st,
- oldTex->target,
- oldTex->format,
- lastLevel,
- oldTex->width0,
- oldTex->height0,
- oldTex->depth0,
- oldTex->array_size,
- oldTex->bind);
-
- /* This will copy the old texture's base image into the new texture
- * which we just allocated.
- */
- st_finalize_texture(ctx, st->pipe, texObj);
-
- /* release the old tex (will likely be freed too) */
- pipe_resource_reference(&oldTex, NULL);
- pipe_sampler_view_reference(&stObj->sampler_view, NULL);
- }
- else {
- /* Make sure that the base texture image data is present in the
- * texture buffer.
- */
- st_finalize_texture(ctx, st->pipe, texObj);
- }
-
- pt = stObj->pt;
-
- assert(pt->last_level >= lastLevel);
-
- /* Try to generate the mipmap by rendering/texturing. If that fails,
- * use the software fallback.
- */
- if (!st_render_mipmap(st, target, stObj, baseLevel, lastLevel)) {
- /* since the util code actually also has a fallback, should
- probably make it never fail and kill this */
- fallback_generate_mipmap(ctx, target, texObj);
- }
-
- /* Fill in the Mesa gl_texture_image fields */
- for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
- const uint srcLevel = dstLevel - 1;
- const struct gl_texture_image *srcImage
- = _mesa_get_tex_image(ctx, texObj, target, srcLevel);
- struct gl_texture_image *dstImage;
- struct st_texture_image *stImage;
- uint dstWidth = u_minify(pt->width0, dstLevel);
- uint dstHeight = u_minify(pt->height0, dstLevel);
- uint dstDepth = u_minify(pt->depth0, dstLevel);
- uint border = srcImage->Border;
-
- dstImage = _mesa_get_tex_image(ctx, texObj, target, dstLevel);
- if (!dstImage) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "generating mipmaps");
- return;
- }
-
- /* Free old image data */
- if (dstImage->Data)
- ctx->Driver.FreeTexImageData(ctx, dstImage);
-
- /* initialize new image */
- _mesa_init_teximage_fields(ctx, target, dstImage, dstWidth, dstHeight,
- dstDepth, border, srcImage->InternalFormat,
- srcImage->TexFormat);
-
- stImage = st_texture_image(dstImage);
- stImage->level = dstLevel;
-
- pipe_resource_reference(&stImage->pt, pt);
- }
-}
+/**************************************************************************
+ *
+ * Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+
+#include "main/imports.h"
+#include "main/mipmap.h"
+#include "main/teximage.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "util/u_inlines.h"
+#include "util/u_format.h"
+#include "util/u_gen_mipmap.h"
+
+#include "st_debug.h"
+#include "st_context.h"
+#include "st_texture.h"
+#include "st_gen_mipmap.h"
+#include "st_cb_texture.h"
+
+
+/**
+ * one-time init for generate mipmap
+ * XXX Note: there may be other times we need no-op/simple state like this.
+ * In that case, some code refactoring would be good.
+ */
+void
+st_init_generate_mipmap(struct st_context *st)
+{
+ st->gen_mipmap = util_create_gen_mipmap(st->pipe, st->cso_context);
+}
+
+
+void
+st_destroy_generate_mipmap(struct st_context *st)
+{
+ util_destroy_gen_mipmap(st->gen_mipmap);
+ st->gen_mipmap = NULL;
+}
+
+
+/**
+ * Generate mipmap levels using hardware rendering.
+ * \return TRUE if successful, FALSE if not possible
+ */
+static boolean
+st_render_mipmap(struct st_context *st,
+ GLenum target,
+ struct st_texture_object *stObj,
+ uint baseLevel, uint lastLevel)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct pipe_screen *screen = pipe->screen;
+ struct pipe_sampler_view *psv = st_get_texture_sampler_view(stObj, pipe);
+ const uint face = _mesa_tex_target_to_face(target);
+
+ assert(psv->texture == stObj->pt);
+#if 0
+ assert(target != GL_TEXTURE_3D); /* implemented but untested */
+#endif
+
+ /* check if we can render in the texture's format */
+ /* XXX should probably kill this and always use util_gen_mipmap
+ since this implements a sw fallback as well */
+ if (!screen->is_format_supported(screen, psv->format, psv->texture->target,
+ 0, PIPE_BIND_RENDER_TARGET, 0)) {
+ return FALSE;
+ }
+
+ util_gen_mipmap(st->gen_mipmap, psv, face, baseLevel, lastLevel,
+ PIPE_TEX_FILTER_LINEAR);
+
+ return TRUE;
+}
+
+
+/**
+ * Helper function to decompress an image. The result is a 32-bpp RGBA
+ * image with stride==width.
+ */
+static void
+decompress_image(enum pipe_format format,
+ const uint8_t *src, uint8_t *dst,
+ unsigned width, unsigned height, unsigned src_stride)
+{
+ const struct util_format_description *desc = util_format_description(format);
+ const uint bw = util_format_get_blockwidth(format);
+ const uint bh = util_format_get_blockheight(format);
+ const uint dst_stride = 4 * MAX2(width, bw);
+
+ desc->unpack_rgba_8unorm(dst, dst_stride, src, src_stride, width, height);
+
+ if (width < bw || height < bh) {
+ /* We're decompressing an image smaller than the compression
+ * block size. We don't want garbage pixel values in the region
+ * outside (width x height) so replicate pixels from the (width
+ * x height) region to fill out the (bw x bh) block size.
+ */
+ uint x, y;
+ for (y = 0; y < bh; y++) {
+ for (x = 0; x < bw; x++) {
+ if (x >= width || y >= height) {
+ uint p = (y * bw + x) * 4;
+ dst[p + 0] = dst[0];
+ dst[p + 1] = dst[1];
+ dst[p + 2] = dst[2];
+ dst[p + 3] = dst[3];
+ }
+ }
+ }
+ }
+}
+
+
+/**
+ * Helper function to compress an image. The source is a 32-bpp RGBA image
+ * with stride==width.
+ */
+static void
+compress_image(enum pipe_format format,
+ const uint8_t *src, uint8_t *dst,
+ unsigned width, unsigned height, unsigned dst_stride)
+{
+ const struct util_format_description *desc = util_format_description(format);
+ const uint src_stride = 4 * width;
+
+ desc->pack_rgba_8unorm(dst, dst_stride, src, src_stride, width, height);
+}
+
+
+/**
+ * Software fallback for generate mipmap levels.
+ */
+static void
+fallback_generate_mipmap(struct gl_context *ctx, GLenum target,
+ struct gl_texture_object *texObj)
+{
+ struct pipe_context *pipe = st_context(ctx)->pipe;
+ struct pipe_resource *pt = st_get_texobj_resource(texObj);
+ const uint baseLevel = texObj->BaseLevel;
+ const uint lastLevel = pt->last_level;
+ const uint face = _mesa_tex_target_to_face(target);
+ uint dstLevel;
+ GLenum datatype;
+ GLuint comps;
+ GLboolean compressed;
+
+ if (ST_DEBUG & DEBUG_FALLBACK)
+ debug_printf("%s: fallback processing\n", __FUNCTION__);
+
+ assert(target != GL_TEXTURE_3D); /* not done yet */
+
+ compressed =
+ _mesa_is_format_compressed(texObj->Image[face][baseLevel]->TexFormat);
+
+ if (compressed) {
+ datatype = GL_UNSIGNED_BYTE;
+ comps = 4;
+ }
+ else {
+ _mesa_format_to_type_and_comps(texObj->Image[face][baseLevel]->TexFormat,
+ &datatype, &comps);
+ assert(comps > 0 && "bad texture format in fallback_generate_mipmap()");
+ }
+
+ for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
+ const uint srcLevel = dstLevel - 1;
+ const uint srcWidth = u_minify(pt->width0, srcLevel);
+ const uint srcHeight = u_minify(pt->height0, srcLevel);
+ const uint srcDepth = u_minify(pt->depth0, srcLevel);
+ const uint dstWidth = u_minify(pt->width0, dstLevel);
+ const uint dstHeight = u_minify(pt->height0, dstLevel);
+ const uint dstDepth = u_minify(pt->depth0, dstLevel);
+ struct pipe_transfer *srcTrans, *dstTrans;
+ const ubyte *srcData;
+ ubyte *dstData;
+ int srcStride, dstStride;
+
+ srcTrans = pipe_get_transfer(st_context(ctx)->pipe, pt, srcLevel,
+ face,
+ PIPE_TRANSFER_READ, 0, 0,
+ srcWidth, srcHeight);
+
+ dstTrans = pipe_get_transfer(st_context(ctx)->pipe, pt, dstLevel,
+ face,
+ PIPE_TRANSFER_WRITE, 0, 0,
+ dstWidth, dstHeight);
+
+ srcData = (ubyte *) pipe_transfer_map(pipe, srcTrans);
+ dstData = (ubyte *) pipe_transfer_map(pipe, dstTrans);
+
+ srcStride = srcTrans->stride / util_format_get_blocksize(srcTrans->resource->format);
+ dstStride = dstTrans->stride / util_format_get_blocksize(dstTrans->resource->format);
+
+ /* this cannot work correctly for 3d since it does
+ not respect layerStride. */
+ if (compressed) {
+ const enum pipe_format format = pt->format;
+ const uint bw = util_format_get_blockwidth(format);
+ const uint bh = util_format_get_blockheight(format);
+ const uint srcWidth2 = align(srcWidth, bw);
+ const uint srcHeight2 = align(srcHeight, bh);
+ const uint dstWidth2 = align(dstWidth, bw);
+ const uint dstHeight2 = align(dstHeight, bh);
+ uint8_t *srcTemp, *dstTemp;
+
+ assert(comps == 4);
+
+ srcTemp = malloc(srcWidth2 * srcHeight2 * comps + 000);
+ dstTemp = malloc(dstWidth2 * dstHeight2 * comps + 000);
+
+ /* decompress the src image: srcData -> srcTemp */
+ decompress_image(format, srcData, srcTemp, srcWidth, srcHeight, srcTrans->stride);
+
+ _mesa_generate_mipmap_level(target, datatype, comps,
+ 0 /*border*/,
+ srcWidth2, srcHeight2, srcDepth,
+ srcTemp,
+ srcWidth2, /* stride in texels */
+ dstWidth2, dstHeight2, dstDepth,
+ dstTemp,
+ dstWidth2); /* stride in texels */
+
+ /* compress the new image: dstTemp -> dstData */
+ compress_image(format, dstTemp, dstData, dstWidth, dstHeight, dstTrans->stride);
+
+ free(srcTemp);
+ free(dstTemp);
+ }
+ else {
+ _mesa_generate_mipmap_level(target, datatype, comps,
+ 0 /*border*/,
+ srcWidth, srcHeight, srcDepth,
+ srcData,
+ srcStride, /* stride in texels */
+ dstWidth, dstHeight, dstDepth,
+ dstData,
+ dstStride); /* stride in texels */
+ }
+
+ pipe_transfer_unmap(pipe, srcTrans);
+ pipe_transfer_unmap(pipe, dstTrans);
+
+ pipe->transfer_destroy(pipe, srcTrans);
+ pipe->transfer_destroy(pipe, dstTrans);
+ }
+}
+
+
+/**
+ * Compute the expected number of mipmap levels in the texture given
+ * the width/height/depth of the base image and the GL_TEXTURE_BASE_LEVEL/
+ * GL_TEXTURE_MAX_LEVEL settings. This will tell us how many mipmap
+ * levels should be generated.
+ */
+static GLuint
+compute_num_levels(struct gl_context *ctx,
+ struct gl_texture_object *texObj,
+ GLenum target)
+{
+ if (target == GL_TEXTURE_RECTANGLE_ARB) {
+ return 1;
+ }
+ else {
+ const struct gl_texture_image *baseImage =
+ _mesa_get_tex_image(ctx, texObj, target, texObj->BaseLevel);
+ GLuint size, numLevels;
+
+ size = MAX2(baseImage->Width2, baseImage->Height2);
+ size = MAX2(size, baseImage->Depth2);
+
+ numLevels = texObj->BaseLevel;
+
+ while (size > 0) {
+ numLevels++;
+ size >>= 1;
+ }
+
+ numLevels = MIN2(numLevels, texObj->MaxLevel + 1);
+
+ assert(numLevels >= 1);
+
+ return numLevels;
+ }
+}
+
+
+/**
+ * Called via ctx->Driver.GenerateMipmap().
+ */
+void
+st_generate_mipmap(struct gl_context *ctx, GLenum target,
+ struct gl_texture_object *texObj)
+{
+ struct st_context *st = st_context(ctx);
+ struct st_texture_object *stObj = st_texture_object(texObj);
+ struct pipe_resource *pt = st_get_texobj_resource(texObj);
+ const uint baseLevel = texObj->BaseLevel;
+ uint lastLevel;
+ uint dstLevel;
+
+ if (!pt)
+ return;
+
+ /* not sure if this ultimately actually should work,
+ but we're not supporting multisampled textures yet. */
+ assert(pt->nr_samples < 2);
+
+ /* find expected last mipmap level to generate*/
+ lastLevel = compute_num_levels(ctx, texObj, target) - 1;
+
+ if (lastLevel == 0)
+ return;
+
+ /* The texture isn't in a "complete" state yet so set the expected
+ * lastLevel here, since it won't get done in st_finalize_texture().
+ */
+ stObj->lastLevel = lastLevel;
+
+ if (pt->last_level < lastLevel) {
+ /* The current gallium texture doesn't have space for all the
+ * mipmap levels we need to generate. So allocate a new texture.
+ */
+ struct pipe_resource *oldTex = stObj->pt;
+
+ /* create new texture with space for more levels */
+ stObj->pt = st_texture_create(st,
+ oldTex->target,
+ oldTex->format,
+ lastLevel,
+ oldTex->width0,
+ oldTex->height0,
+ oldTex->depth0,
+ oldTex->array_size,
+ oldTex->bind);
+
+ /* This will copy the old texture's base image into the new texture
+ * which we just allocated.
+ */
+ st_finalize_texture(ctx, st->pipe, texObj);
+
+ /* release the old tex (will likely be freed too) */
+ pipe_resource_reference(&oldTex, NULL);
+ pipe_sampler_view_reference(&stObj->sampler_view, NULL);
+ }
+ else {
+ /* Make sure that the base texture image data is present in the
+ * texture buffer.
+ */
+ st_finalize_texture(ctx, st->pipe, texObj);
+ }
+
+ pt = stObj->pt;
+
+ assert(pt->last_level >= lastLevel);
+
+ /* Try to generate the mipmap by rendering/texturing. If that fails,
+ * use the software fallback.
+ */
+ if (!st_render_mipmap(st, target, stObj, baseLevel, lastLevel)) {
+ /* since the util code actually also has a fallback, should
+ probably make it never fail and kill this */
+ fallback_generate_mipmap(ctx, target, texObj);
+ }
+
+ /* Fill in the Mesa gl_texture_image fields */
+ for (dstLevel = baseLevel + 1; dstLevel <= lastLevel; dstLevel++) {
+ const uint srcLevel = dstLevel - 1;
+ const struct gl_texture_image *srcImage
+ = _mesa_get_tex_image(ctx, texObj, target, srcLevel);
+ struct gl_texture_image *dstImage;
+ struct st_texture_image *stImage;
+ uint dstWidth = u_minify(pt->width0, dstLevel);
+ uint dstHeight = u_minify(pt->height0, dstLevel);
+ uint dstDepth = u_minify(pt->depth0, dstLevel);
+ uint border = srcImage->Border;
+
+ dstImage = _mesa_get_tex_image(ctx, texObj, target, dstLevel);
+ if (!dstImage) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "generating mipmaps");
+ return;
+ }
+
+ /* Free old image data */
+ if (dstImage->Data)
+ ctx->Driver.FreeTexImageData(ctx, dstImage);
+
+ /* initialize new image */
+ _mesa_init_teximage_fields(ctx, target, dstImage, dstWidth, dstHeight,
+ dstDepth, border, srcImage->InternalFormat,
+ srcImage->TexFormat);
+
+ stImage = st_texture_image(dstImage);
+ stImage->level = dstLevel;
+
+ pipe_resource_reference(&stImage->pt, pt);
+ }
+}
diff --git a/mesalib/src/mesa/state_tracker/st_program.c b/mesalib/src/mesa/state_tracker/st_program.c
index fc1dfb3ef..e5c26c563 100644
--- a/mesalib/src/mesa/state_tracker/st_program.c
+++ b/mesalib/src/mesa/state_tracker/st_program.c
@@ -1,1165 +1,1165 @@
-/**************************************************************************
- *
- * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- * Brian Paul
- */
-
-
-#include "main/imports.h"
-#include "main/hash.h"
-#include "main/mfeatures.h"
-#include "main/mtypes.h"
-#include "program/prog_parameter.h"
-#include "program/prog_print.h"
-#include "program/programopt.h"
-
-#include "pipe/p_context.h"
-#include "pipe/p_defines.h"
-#include "pipe/p_shader_tokens.h"
-#include "draw/draw_context.h"
-#include "tgsi/tgsi_dump.h"
-#include "tgsi/tgsi_ureg.h"
-
-#include "st_debug.h"
-#include "st_cb_bitmap.h"
-#include "st_cb_drawpixels.h"
-#include "st_context.h"
-#include "st_program.h"
-#include "st_mesa_to_tgsi.h"
-#include "cso_cache/cso_context.h"
-
-
-
-/**
- * Delete a vertex program variant. Note the caller must unlink
- * the variant from the linked list.
- */
-static void
-delete_vp_variant(struct st_context *st, struct st_vp_variant *vpv)
-{
- if (vpv->driver_shader)
- cso_delete_vertex_shader(st->cso_context, vpv->driver_shader);
-
-#if FEATURE_feedback || FEATURE_rastpos
- if (vpv->draw_shader)
- draw_delete_vertex_shader( st->draw, vpv->draw_shader );
-#endif
-
- if (vpv->tgsi.tokens)
- st_free_tokens(vpv->tgsi.tokens);
-
- FREE( vpv );
-}
-
-
-
-/**
- * Clean out any old compilations:
- */
-void
-st_release_vp_variants( struct st_context *st,
- struct st_vertex_program *stvp )
-{
- struct st_vp_variant *vpv;
-
- for (vpv = stvp->variants; vpv; ) {
- struct st_vp_variant *next = vpv->next;
- delete_vp_variant(st, vpv);
- vpv = next;
- }
-
- stvp->variants = NULL;
-}
-
-
-
-/**
- * Delete a fragment program variant. Note the caller must unlink
- * the variant from the linked list.
- */
-static void
-delete_fp_variant(struct st_context *st, struct st_fp_variant *fpv)
-{
- if (fpv->driver_shader)
- cso_delete_fragment_shader(st->cso_context, fpv->driver_shader);
- if (fpv->parameters)
- _mesa_free_parameter_list(fpv->parameters);
-
- FREE(fpv);
-}
-
-
-/**
- * Free all variants of a fragment program.
- */
-void
-st_release_fp_variants(struct st_context *st, struct st_fragment_program *stfp)
-{
- struct st_fp_variant *fpv;
-
- for (fpv = stfp->variants; fpv; ) {
- struct st_fp_variant *next = fpv->next;
- delete_fp_variant(st, fpv);
- fpv = next;
- }
-
- stfp->variants = NULL;
-}
-
-
-/**
- * Delete a geometry program variant. Note the caller must unlink
- * the variant from the linked list.
- */
-static void
-delete_gp_variant(struct st_context *st, struct st_gp_variant *gpv)
-{
- if (gpv->driver_shader)
- cso_delete_geometry_shader(st->cso_context, gpv->driver_shader);
-
- FREE(gpv);
-}
-
-
-/**
- * Free all variants of a geometry program.
- */
-void
-st_release_gp_variants(struct st_context *st, struct st_geometry_program *stgp)
-{
- struct st_gp_variant *gpv;
-
- for (gpv = stgp->variants; gpv; ) {
- struct st_gp_variant *next = gpv->next;
- delete_gp_variant(st, gpv);
- gpv = next;
- }
-
- stgp->variants = NULL;
-}
-
-
-
-
-/**
- * Translate a Mesa vertex shader into a TGSI shader.
- * \param outputMapping to map vertex program output registers (VERT_RESULT_x)
- * to TGSI output slots
- * \param tokensOut destination for TGSI tokens
- * \return pointer to cached pipe_shader object.
- */
-static void
-st_prepare_vertex_program(struct st_context *st,
- struct st_vertex_program *stvp)
-{
- GLuint attr;
-
- stvp->num_inputs = 0;
- stvp->num_outputs = 0;
-
- if (stvp->Base.IsPositionInvariant)
- _mesa_insert_mvp_code(st->ctx, &stvp->Base);
-
- assert(stvp->Base.Base.NumInstructions > 1);
-
- /*
- * Determine number of inputs, the mappings between VERT_ATTRIB_x
- * and TGSI generic input indexes, plus input attrib semantic info.
- */
- for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
- if (stvp->Base.Base.InputsRead & (1 << attr)) {
- stvp->input_to_index[attr] = stvp->num_inputs;
- stvp->index_to_input[stvp->num_inputs] = attr;
- stvp->num_inputs++;
- }
- }
- /* bit of a hack, presetup potentially unused edgeflag input */
- stvp->input_to_index[VERT_ATTRIB_EDGEFLAG] = stvp->num_inputs;
- stvp->index_to_input[stvp->num_inputs] = VERT_ATTRIB_EDGEFLAG;
-
- /* Compute mapping of vertex program outputs to slots.
- */
- for (attr = 0; attr < VERT_RESULT_MAX; attr++) {
- if ((stvp->Base.Base.OutputsWritten & BITFIELD64_BIT(attr)) == 0) {
- stvp->result_to_output[attr] = ~0;
- }
- else {
- unsigned slot = stvp->num_outputs++;
-
- stvp->result_to_output[attr] = slot;
-
- switch (attr) {
- case VERT_RESULT_HPOS:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
- stvp->output_semantic_index[slot] = 0;
- break;
- case VERT_RESULT_COL0:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- stvp->output_semantic_index[slot] = 0;
- break;
- case VERT_RESULT_COL1:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- stvp->output_semantic_index[slot] = 1;
- break;
- case VERT_RESULT_BFC0:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
- stvp->output_semantic_index[slot] = 0;
- break;
- case VERT_RESULT_BFC1:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
- stvp->output_semantic_index[slot] = 1;
- break;
- case VERT_RESULT_FOGC:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_FOG;
- stvp->output_semantic_index[slot] = 0;
- break;
- case VERT_RESULT_PSIZ:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_PSIZE;
- stvp->output_semantic_index[slot] = 0;
- break;
- case VERT_RESULT_EDGE:
- assert(0);
- break;
-
- case VERT_RESULT_TEX0:
- case VERT_RESULT_TEX1:
- case VERT_RESULT_TEX2:
- case VERT_RESULT_TEX3:
- case VERT_RESULT_TEX4:
- case VERT_RESULT_TEX5:
- case VERT_RESULT_TEX6:
- case VERT_RESULT_TEX7:
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- stvp->output_semantic_index[slot] = attr - VERT_RESULT_TEX0;
- break;
-
- case VERT_RESULT_VAR0:
- default:
- assert(attr < VERT_RESULT_MAX);
- stvp->output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- stvp->output_semantic_index[slot] = (FRAG_ATTRIB_VAR0 -
- FRAG_ATTRIB_TEX0 +
- attr -
- VERT_RESULT_VAR0);
- break;
- }
- }
- }
- /* similar hack to above, presetup potentially unused edgeflag output */
- stvp->result_to_output[VERT_RESULT_EDGE] = stvp->num_outputs;
- stvp->output_semantic_name[stvp->num_outputs] = TGSI_SEMANTIC_EDGEFLAG;
- stvp->output_semantic_index[stvp->num_outputs] = 0;
-}
-
-
-/**
- * Translate a vertex program to create a new variant.
- */
-static struct st_vp_variant *
-st_translate_vertex_program(struct st_context *st,
- struct st_vertex_program *stvp,
- const struct st_vp_variant_key *key)
-{
- struct st_vp_variant *vpv = CALLOC_STRUCT(st_vp_variant);
- struct pipe_context *pipe = st->pipe;
- struct ureg_program *ureg;
- enum pipe_error error;
- unsigned num_outputs;
-
- st_prepare_vertex_program( st, stvp );
-
- _mesa_remove_output_reads(&stvp->Base.Base, PROGRAM_OUTPUT);
- _mesa_remove_output_reads(&stvp->Base.Base, PROGRAM_VARYING);
-
- ureg = ureg_create( TGSI_PROCESSOR_VERTEX );
- if (ureg == NULL) {
- FREE(vpv);
- return NULL;
- }
-
- vpv->key = *key;
-
- vpv->num_inputs = stvp->num_inputs;
- num_outputs = stvp->num_outputs;
- if (key->passthrough_edgeflags) {
- vpv->num_inputs++;
- num_outputs++;
- }
-
- if (ST_DEBUG & DEBUG_MESA) {
- _mesa_print_program(&stvp->Base.Base);
- _mesa_print_program_parameters(st->ctx, &stvp->Base.Base);
- debug_printf("\n");
- }
-
- error = st_translate_mesa_program(st->ctx,
- TGSI_PROCESSOR_VERTEX,
- ureg,
- &stvp->Base.Base,
- /* inputs */
- vpv->num_inputs,
- stvp->input_to_index,
- NULL, /* input semantic name */
- NULL, /* input semantic index */
- NULL,
- /* outputs */
- num_outputs,
- stvp->result_to_output,
- stvp->output_semantic_name,
- stvp->output_semantic_index,
- key->passthrough_edgeflags );
-
- if (error)
- goto fail;
-
- vpv->tgsi.tokens = ureg_get_tokens( ureg, NULL );
- if (!vpv->tgsi.tokens)
- goto fail;
-
- ureg_destroy( ureg );
-
- vpv->driver_shader = pipe->create_vs_state(pipe, &vpv->tgsi);
-
- if (ST_DEBUG & DEBUG_TGSI) {
- tgsi_dump( vpv->tgsi.tokens, 0 );
- debug_printf("\n");
- }
-
- return vpv;
-
-fail:
- debug_printf("%s: failed to translate Mesa program:\n", __FUNCTION__);
- _mesa_print_program(&stvp->Base.Base);
- debug_assert(0);
-
- ureg_destroy( ureg );
- return NULL;
-}
-
-
-/**
- * Find/create a vertex program variant.
- */
-struct st_vp_variant *
-st_get_vp_variant(struct st_context *st,
- struct st_vertex_program *stvp,
- const struct st_vp_variant_key *key)
-{
- struct st_vp_variant *vpv;
-
- /* Search for existing variant */
- for (vpv = stvp->variants; vpv; vpv = vpv->next) {
- if (memcmp(&vpv->key, key, sizeof(*key)) == 0) {
- break;
- }
- }
-
- if (!vpv) {
- /* create now */
- vpv = st_translate_vertex_program(st, stvp, key);
- if (vpv) {
- /* insert into list */
- vpv->next = stvp->variants;
- stvp->variants = vpv;
- }
- }
-
- return vpv;
-}
-
-
-/**
- * Translate a Mesa fragment shader into a TGSI shader using extra info in
- * the key.
- * \return new fragment program variant
- */
-static struct st_fp_variant *
-st_translate_fragment_program(struct st_context *st,
- struct st_fragment_program *stfp,
- const struct st_fp_variant_key *key)
-{
- struct pipe_context *pipe = st->pipe;
- struct st_fp_variant *variant = CALLOC_STRUCT(st_fp_variant);
- GLboolean deleteFP = GL_FALSE;
-
- if (!variant)
- return NULL;
-
- assert(!(key->bitmap && key->drawpixels));
-
-#if FEATURE_drawpix
- if (key->bitmap) {
- /* glBitmap drawing */
- struct gl_fragment_program *fp; /* we free this temp program below */
-
- st_make_bitmap_fragment_program(st, &stfp->Base,
- &fp, &variant->bitmap_sampler);
-
- variant->parameters = _mesa_clone_parameter_list(fp->Base.Parameters);
- stfp = st_fragment_program(fp);
- deleteFP = GL_TRUE;
- }
- else if (key->drawpixels) {
- /* glDrawPixels drawing */
- struct gl_fragment_program *fp; /* we free this temp program below */
-
- if (key->drawpixels_z || key->drawpixels_stencil) {
- fp = st_make_drawpix_z_stencil_program(st, key->drawpixels_z,
- key->drawpixels_stencil);
- }
- else {
- /* RGBA */
- st_make_drawpix_fragment_program(st, &stfp->Base, &fp);
- variant->parameters = _mesa_clone_parameter_list(fp->Base.Parameters);
- deleteFP = GL_TRUE;
- }
- stfp = st_fragment_program(fp);
- }
-#endif
-
- if (!stfp->tgsi.tokens) {
- /* need to translate Mesa instructions to TGSI now */
- GLuint outputMapping[FRAG_RESULT_MAX];
- GLuint inputMapping[FRAG_ATTRIB_MAX];
- GLuint interpMode[PIPE_MAX_SHADER_INPUTS]; /* XXX size? */
- GLuint attr;
- enum pipe_error error;
- const GLbitfield inputsRead = stfp->Base.Base.InputsRead;
- struct ureg_program *ureg;
- GLboolean write_all = GL_FALSE;
-
- ubyte input_semantic_name[PIPE_MAX_SHADER_INPUTS];
- ubyte input_semantic_index[PIPE_MAX_SHADER_INPUTS];
- uint fs_num_inputs = 0;
-
- ubyte fs_output_semantic_name[PIPE_MAX_SHADER_OUTPUTS];
- ubyte fs_output_semantic_index[PIPE_MAX_SHADER_OUTPUTS];
- uint fs_num_outputs = 0;
-
-
- _mesa_remove_output_reads(&stfp->Base.Base, PROGRAM_OUTPUT);
-
- /*
- * Convert Mesa program inputs to TGSI input register semantics.
- */
- for (attr = 0; attr < FRAG_ATTRIB_MAX; attr++) {
- if (inputsRead & (1 << attr)) {
- const GLuint slot = fs_num_inputs++;
-
- inputMapping[attr] = slot;
-
- switch (attr) {
- case FRAG_ATTRIB_WPOS:
- input_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
- input_semantic_index[slot] = 0;
- interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
- break;
- case FRAG_ATTRIB_COL0:
- input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- input_semantic_index[slot] = 0;
- interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
- break;
- case FRAG_ATTRIB_COL1:
- input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- input_semantic_index[slot] = 1;
- interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
- break;
- case FRAG_ATTRIB_FOGC:
- input_semantic_name[slot] = TGSI_SEMANTIC_FOG;
- input_semantic_index[slot] = 0;
- interpMode[slot] = TGSI_INTERPOLATE_PERSPECTIVE;
- break;
- case FRAG_ATTRIB_FACE:
- input_semantic_name[slot] = TGSI_SEMANTIC_FACE;
- input_semantic_index[slot] = 0;
- interpMode[slot] = TGSI_INTERPOLATE_CONSTANT;
- break;
- /* In most cases, there is nothing special about these
- * inputs, so adopt a convention to use the generic
- * semantic name and the mesa FRAG_ATTRIB_ number as the
- * index.
- *
- * All that is required is that the vertex shader labels
- * its own outputs similarly, and that the vertex shader
- * generates at least every output required by the
- * fragment shader plus fixed-function hardware (such as
- * BFC).
- *
- * There is no requirement that semantic indexes start at
- * zero or be restricted to a particular range -- nobody
- * should be building tables based on semantic index.
- */
- case FRAG_ATTRIB_PNTC:
- case FRAG_ATTRIB_TEX0:
- case FRAG_ATTRIB_TEX1:
- case FRAG_ATTRIB_TEX2:
- case FRAG_ATTRIB_TEX3:
- case FRAG_ATTRIB_TEX4:
- case FRAG_ATTRIB_TEX5:
- case FRAG_ATTRIB_TEX6:
- case FRAG_ATTRIB_TEX7:
- case FRAG_ATTRIB_VAR0:
- default:
- /* Actually, let's try and zero-base this just for
- * readability of the generated TGSI.
- */
- assert(attr >= FRAG_ATTRIB_TEX0);
- input_semantic_index[slot] = (attr - FRAG_ATTRIB_TEX0);
- input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- if (attr == FRAG_ATTRIB_PNTC)
- interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
- else
- interpMode[slot] = TGSI_INTERPOLATE_PERSPECTIVE;
- break;
- }
- }
- else {
- inputMapping[attr] = -1;
- }
- }
-
- /*
- * Semantics and mapping for outputs
- */
- {
- uint numColors = 0;
- GLbitfield64 outputsWritten = stfp->Base.Base.OutputsWritten;
-
- /* if z is written, emit that first */
- if (outputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
- fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_POSITION;
- fs_output_semantic_index[fs_num_outputs] = 0;
- outputMapping[FRAG_RESULT_DEPTH] = fs_num_outputs;
- fs_num_outputs++;
- outputsWritten &= ~(1 << FRAG_RESULT_DEPTH);
- }
-
- if (outputsWritten & BITFIELD64_BIT(FRAG_RESULT_STENCIL)) {
- fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_STENCIL;
- fs_output_semantic_index[fs_num_outputs] = 0;
- outputMapping[FRAG_RESULT_STENCIL] = fs_num_outputs;
- fs_num_outputs++;
- outputsWritten &= ~(1 << FRAG_RESULT_STENCIL);
- }
-
- /* handle remaning outputs (color) */
- for (attr = 0; attr < FRAG_RESULT_MAX; attr++) {
- if (outputsWritten & BITFIELD64_BIT(attr)) {
- switch (attr) {
- case FRAG_RESULT_DEPTH:
- case FRAG_RESULT_STENCIL:
- /* handled above */
- assert(0);
- break;
- case FRAG_RESULT_COLOR:
- write_all = GL_TRUE; /* fallthrough */
- default:
- assert(attr == FRAG_RESULT_COLOR ||
- (FRAG_RESULT_DATA0 <= attr && attr < FRAG_RESULT_MAX));
- fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_COLOR;
- fs_output_semantic_index[fs_num_outputs] = numColors;
- outputMapping[attr] = fs_num_outputs;
- numColors++;
- break;
- }
-
- fs_num_outputs++;
- }
- }
- }
-
- ureg = ureg_create( TGSI_PROCESSOR_FRAGMENT );
- if (ureg == NULL)
- return NULL;
-
- if (ST_DEBUG & DEBUG_MESA) {
- _mesa_print_program(&stfp->Base.Base);
- _mesa_print_program_parameters(st->ctx, &stfp->Base.Base);
- debug_printf("\n");
- }
- if (write_all == GL_TRUE)
- ureg_property_fs_color0_writes_all_cbufs(ureg, 1);
-
- error = st_translate_mesa_program(st->ctx,
- TGSI_PROCESSOR_FRAGMENT,
- ureg,
- &stfp->Base.Base,
- /* inputs */
- fs_num_inputs,
- inputMapping,
- input_semantic_name,
- input_semantic_index,
- interpMode,
- /* outputs */
- fs_num_outputs,
- outputMapping,
- fs_output_semantic_name,
- fs_output_semantic_index, FALSE );
-
- stfp->tgsi.tokens = ureg_get_tokens( ureg, NULL );
- ureg_destroy( ureg );
- }
-
- /* fill in variant */
- variant->driver_shader = pipe->create_fs_state(pipe, &stfp->tgsi);
- variant->key = *key;
-
- if (ST_DEBUG & DEBUG_TGSI) {
- tgsi_dump( stfp->tgsi.tokens, 0/*TGSI_DUMP_VERBOSE*/ );
- debug_printf("\n");
- }
-
- if (deleteFP) {
- /* Free the temporary program made above */
- struct gl_fragment_program *fp = &stfp->Base;
- _mesa_reference_fragprog(st->ctx, &fp, NULL);
- }
-
- return variant;
-}
-
-
-/**
- * Translate fragment program if needed.
- */
-struct st_fp_variant *
-st_get_fp_variant(struct st_context *st,
- struct st_fragment_program *stfp,
- const struct st_fp_variant_key *key)
-{
- struct st_fp_variant *fpv;
-
- /* Search for existing variant */
- for (fpv = stfp->variants; fpv; fpv = fpv->next) {
- if (memcmp(&fpv->key, key, sizeof(*key)) == 0) {
- break;
- }
- }
-
- if (!fpv) {
- /* create new */
- fpv = st_translate_fragment_program(st, stfp, key);
- if (fpv) {
- /* insert into list */
- fpv->next = stfp->variants;
- stfp->variants = fpv;
- }
- }
-
- return fpv;
-}
-
-
-/**
- * Translate a geometry program to create a new variant.
- */
-static struct st_gp_variant *
-st_translate_geometry_program(struct st_context *st,
- struct st_geometry_program *stgp,
- const struct st_gp_variant_key *key)
-{
- GLuint inputMapping[GEOM_ATTRIB_MAX];
- GLuint outputMapping[GEOM_RESULT_MAX];
- struct pipe_context *pipe = st->pipe;
- enum pipe_error error;
- GLuint attr;
- const GLbitfield inputsRead = stgp->Base.Base.InputsRead;
- GLuint vslot = 0;
- GLuint num_generic = 0;
-
- uint gs_num_inputs = 0;
- uint gs_builtin_inputs = 0;
- uint gs_array_offset = 0;
-
- ubyte gs_output_semantic_name[PIPE_MAX_SHADER_OUTPUTS];
- ubyte gs_output_semantic_index[PIPE_MAX_SHADER_OUTPUTS];
- uint gs_num_outputs = 0;
-
- GLint i;
- GLuint maxSlot = 0;
- struct ureg_program *ureg;
-
- struct st_gp_variant *gpv;
-
- gpv = CALLOC_STRUCT(st_gp_variant);
- if (!gpv)
- return NULL;
-
- _mesa_remove_output_reads(&stgp->Base.Base, PROGRAM_OUTPUT);
- _mesa_remove_output_reads(&stgp->Base.Base, PROGRAM_VARYING);
-
- ureg = ureg_create( TGSI_PROCESSOR_GEOMETRY );
- if (ureg == NULL) {
- FREE(gpv);
- return NULL;
- }
-
- /* which vertex output goes to the first geometry input */
- vslot = 0;
-
- memset(inputMapping, 0, sizeof(inputMapping));
- memset(outputMapping, 0, sizeof(outputMapping));
-
- /*
- * Convert Mesa program inputs to TGSI input register semantics.
- */
- for (attr = 0; attr < GEOM_ATTRIB_MAX; attr++) {
- if (inputsRead & (1 << attr)) {
- const GLuint slot = gs_num_inputs;
-
- gs_num_inputs++;
-
- inputMapping[attr] = slot;
-
- stgp->input_map[slot + gs_array_offset] = vslot - gs_builtin_inputs;
- stgp->input_to_index[attr] = vslot;
- stgp->index_to_input[vslot] = attr;
- ++vslot;
-
- if (attr != GEOM_ATTRIB_PRIMITIVE_ID) {
- gs_array_offset += 2;
- } else
- ++gs_builtin_inputs;
-
-#if 0
- debug_printf("input map at %d = %d\n",
- slot + gs_array_offset, stgp->input_map[slot + gs_array_offset]);
-#endif
-
- switch (attr) {
- case GEOM_ATTRIB_PRIMITIVE_ID:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_PRIMID;
- stgp->input_semantic_index[slot] = 0;
- break;
- case GEOM_ATTRIB_POSITION:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
- stgp->input_semantic_index[slot] = 0;
- break;
- case GEOM_ATTRIB_COLOR0:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- stgp->input_semantic_index[slot] = 0;
- break;
- case GEOM_ATTRIB_COLOR1:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- stgp->input_semantic_index[slot] = 1;
- break;
- case GEOM_ATTRIB_FOG_FRAG_COORD:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_FOG;
- stgp->input_semantic_index[slot] = 0;
- break;
- case GEOM_ATTRIB_TEX_COORD:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- stgp->input_semantic_index[slot] = num_generic++;
- break;
- case GEOM_ATTRIB_VAR0:
- /* fall-through */
- default:
- stgp->input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- stgp->input_semantic_index[slot] = num_generic++;
- }
- }
- }
-
- /* initialize output semantics to defaults */
- for (i = 0; i < PIPE_MAX_SHADER_OUTPUTS; i++) {
- gs_output_semantic_name[i] = TGSI_SEMANTIC_GENERIC;
- gs_output_semantic_index[i] = 0;
- }
-
- num_generic = 0;
- /*
- * Determine number of outputs, the (default) output register
- * mapping and the semantic information for each output.
- */
- for (attr = 0; attr < GEOM_RESULT_MAX; attr++) {
- if (stgp->Base.Base.OutputsWritten & (1 << attr)) {
- GLuint slot;
-
- slot = gs_num_outputs;
- gs_num_outputs++;
- outputMapping[attr] = slot;
-
- switch (attr) {
- case GEOM_RESULT_POS:
- assert(slot == 0);
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
- gs_output_semantic_index[slot] = 0;
- break;
- case GEOM_RESULT_COL0:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- gs_output_semantic_index[slot] = 0;
- break;
- case GEOM_RESULT_COL1:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
- gs_output_semantic_index[slot] = 1;
- break;
- case GEOM_RESULT_SCOL0:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
- gs_output_semantic_index[slot] = 0;
- break;
- case GEOM_RESULT_SCOL1:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
- gs_output_semantic_index[slot] = 1;
- break;
- case GEOM_RESULT_FOGC:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_FOG;
- gs_output_semantic_index[slot] = 0;
- break;
- case GEOM_RESULT_PSIZ:
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_PSIZE;
- gs_output_semantic_index[slot] = 0;
- break;
- case GEOM_RESULT_TEX0:
- case GEOM_RESULT_TEX1:
- case GEOM_RESULT_TEX2:
- case GEOM_RESULT_TEX3:
- case GEOM_RESULT_TEX4:
- case GEOM_RESULT_TEX5:
- case GEOM_RESULT_TEX6:
- case GEOM_RESULT_TEX7:
- /* fall-through */
- case GEOM_RESULT_VAR0:
- /* fall-through */
- default:
- assert(slot < Elements(gs_output_semantic_name));
- /* use default semantic info */
- gs_output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
- gs_output_semantic_index[slot] = num_generic++;
- }
- }
- }
-
- assert(gs_output_semantic_name[0] == TGSI_SEMANTIC_POSITION);
-
- /* find max output slot referenced to compute gs_num_outputs */
- for (attr = 0; attr < GEOM_RESULT_MAX; attr++) {
- if (outputMapping[attr] != ~0 && outputMapping[attr] > maxSlot)
- maxSlot = outputMapping[attr];
- }
- gs_num_outputs = maxSlot + 1;
-
-#if 0 /* debug */
- {
- GLuint i;
- printf("outputMapping? %d\n", outputMapping ? 1 : 0);
- if (outputMapping) {
- printf("attr -> slot\n");
- for (i = 0; i < 16; i++) {
- printf(" %2d %3d\n", i, outputMapping[i]);
- }
- }
- printf("slot sem_name sem_index\n");
- for (i = 0; i < gs_num_outputs; i++) {
- printf(" %2d %d %d\n",
- i,
- gs_output_semantic_name[i],
- gs_output_semantic_index[i]);
- }
- }
-#endif
-
- /* free old shader state, if any */
- if (stgp->tgsi.tokens) {
- st_free_tokens(stgp->tgsi.tokens);
- stgp->tgsi.tokens = NULL;
- }
-
- ureg_property_gs_input_prim(ureg, stgp->Base.InputType);
- ureg_property_gs_output_prim(ureg, stgp->Base.OutputType);
- ureg_property_gs_max_vertices(ureg, stgp->Base.VerticesOut);
-
- error = st_translate_mesa_program(st->ctx,
- TGSI_PROCESSOR_GEOMETRY,
- ureg,
- &stgp->Base.Base,
- /* inputs */
- gs_num_inputs,
- inputMapping,
- stgp->input_semantic_name,
- stgp->input_semantic_index,
- NULL,
- /* outputs */
- gs_num_outputs,
- outputMapping,
- gs_output_semantic_name,
- gs_output_semantic_index,
- FALSE);
-
- stgp->num_inputs = gs_num_inputs;
- stgp->tgsi.tokens = ureg_get_tokens( ureg, NULL );
- ureg_destroy( ureg );
-
- /* fill in new variant */
- gpv->driver_shader = pipe->create_gs_state(pipe, &stgp->tgsi);
- gpv->key = *key;
-
- if ((ST_DEBUG & DEBUG_TGSI) && (ST_DEBUG & DEBUG_MESA)) {
- _mesa_print_program(&stgp->Base.Base);
- debug_printf("\n");
- }
-
- if (ST_DEBUG & DEBUG_TGSI) {
- tgsi_dump(stgp->tgsi.tokens, 0);
- debug_printf("\n");
- }
-
- return gpv;
-}
-
-
-/**
- * Get/create geometry program variant.
- */
-struct st_gp_variant *
-st_get_gp_variant(struct st_context *st,
- struct st_geometry_program *stgp,
- const struct st_gp_variant_key *key)
-{
- struct st_gp_variant *gpv;
-
- /* Search for existing variant */
- for (gpv = stgp->variants; gpv; gpv = gpv->next) {
- if (memcmp(&gpv->key, key, sizeof(*key)) == 0) {
- break;
- }
- }
-
- if (!gpv) {
- /* create new */
- gpv = st_translate_geometry_program(st, stgp, key);
- if (gpv) {
- /* insert into list */
- gpv->next = stgp->variants;
- stgp->variants = gpv;
- }
- }
-
- return gpv;
-}
-
-
-
-
-/**
- * Debug- print current shader text
- */
-void
-st_print_shaders(struct gl_context *ctx)
-{
- struct gl_shader_program *shProg[3] = {
- ctx->Shader.CurrentVertexProgram,
- ctx->Shader.CurrentGeometryProgram,
- ctx->Shader.CurrentFragmentProgram,
- };
- unsigned j;
-
- for (j = 0; j < 3; j++) {
- unsigned i;
-
- if (shProg[j] == NULL)
- continue;
-
- for (i = 0; i < shProg[j]->NumShaders; i++) {
- struct gl_shader *sh;
-
- switch (shProg[j]->Shaders[i]->Type) {
- case GL_VERTEX_SHADER:
- sh = (i != 0) ? NULL : shProg[j]->Shaders[i];
- break;
- case GL_GEOMETRY_SHADER_ARB:
- sh = (i != 1) ? NULL : shProg[j]->Shaders[i];
- break;
- case GL_FRAGMENT_SHADER:
- sh = (i != 2) ? NULL : shProg[j]->Shaders[i];
- break;
- default:
- assert(0);
- sh = NULL;
- break;
- }
-
- if (sh != NULL) {
- printf("GLSL shader %u of %u:\n", i, shProg[j]->NumShaders);
- printf("%s\n", sh->Source);
- }
- }
- }
-}
-
-
-/**
- * Vert/Geom/Frag programs have per-context variants. Free all the
- * variants attached to the given program which match the given context.
- */
-static void
-destroy_program_variants(struct st_context *st, struct gl_program *program)
-{
- if (!program)
- return;
-
- switch (program->Target) {
- case GL_VERTEX_PROGRAM_ARB:
- {
- struct st_vertex_program *stvp = (struct st_vertex_program *) program;
- struct st_vp_variant *vpv, **prevPtr = &stvp->variants;
-
- for (vpv = stvp->variants; vpv; ) {
- struct st_vp_variant *next = vpv->next;
- if (vpv->key.st == st) {
- /* unlink from list */
- *prevPtr = next;
- /* destroy this variant */
- delete_vp_variant(st, vpv);
- }
- else {
- prevPtr = &vpv->next;
- }
- vpv = next;
- }
- }
- break;
- case GL_FRAGMENT_PROGRAM_ARB:
- {
- struct st_fragment_program *stfp =
- (struct st_fragment_program *) program;
- struct st_fp_variant *fpv, **prevPtr = &stfp->variants;
-
- for (fpv = stfp->variants; fpv; ) {
- struct st_fp_variant *next = fpv->next;
- if (fpv->key.st == st) {
- /* unlink from list */
- *prevPtr = next;
- /* destroy this variant */
- delete_fp_variant(st, fpv);
- }
- else {
- prevPtr = &fpv->next;
- }
- fpv = next;
- }
- }
- break;
- case MESA_GEOMETRY_PROGRAM:
- {
- struct st_geometry_program *stgp =
- (struct st_geometry_program *) program;
- struct st_gp_variant *gpv, **prevPtr = &stgp->variants;
-
- for (gpv = stgp->variants; gpv; ) {
- struct st_gp_variant *next = gpv->next;
- if (gpv->key.st == st) {
- /* unlink from list */
- *prevPtr = next;
- /* destroy this variant */
- delete_gp_variant(st, gpv);
- }
- else {
- prevPtr = &gpv->next;
- }
- gpv = next;
- }
- }
- break;
- default:
- _mesa_problem(NULL, "Unexpected program target in "
- "destroy_program_variants_cb()");
- }
-}
-
-
-/**
- * Callback for _mesa_HashWalk. Free all the shader's program variants
- * which match the given context.
- */
-static void
-destroy_shader_program_variants_cb(GLuint key, void *data, void *userData)
-{
- struct st_context *st = (struct st_context *) userData;
- struct gl_shader *shader = (struct gl_shader *) data;
-
- switch (shader->Type) {
- case GL_SHADER_PROGRAM_MESA:
- {
- struct gl_shader_program *shProg = (struct gl_shader_program *) data;
- GLuint i;
-
- for (i = 0; i < shProg->NumShaders; i++) {
- destroy_program_variants(st, shProg->Shaders[i]->Program);
- }
-
- destroy_program_variants(st, (struct gl_program *)
- shProg->VertexProgram);
- destroy_program_variants(st, (struct gl_program *)
- shProg->FragmentProgram);
- destroy_program_variants(st, (struct gl_program *)
- shProg->GeometryProgram);
- }
- break;
- case GL_VERTEX_SHADER:
- case GL_FRAGMENT_SHADER:
- case GL_GEOMETRY_SHADER:
- {
- destroy_program_variants(st, shader->Program);
- }
- break;
- default:
- assert(0);
- }
-}
-
-
-/**
- * Callback for _mesa_HashWalk. Free all the program variants which match
- * the given context.
- */
-static void
-destroy_program_variants_cb(GLuint key, void *data, void *userData)
-{
- struct st_context *st = (struct st_context *) userData;
- struct gl_program *program = (struct gl_program *) data;
- destroy_program_variants(st, program);
-}
-
-
-/**
- * Walk over all shaders and programs to delete any variants which
- * belong to the given context.
- * This is called during context tear-down.
- */
-void
-st_destroy_program_variants(struct st_context *st)
-{
- /* ARB vert/frag program */
- _mesa_HashWalk(st->ctx->Shared->Programs,
- destroy_program_variants_cb, st);
-
- /* GLSL vert/frag/geom shaders */
- _mesa_HashWalk(st->ctx->Shared->ShaderObjects,
- destroy_shader_program_variants_cb, st);
-}
+/**************************************************************************
+ *
+ * Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ * Brian Paul
+ */
+
+
+#include "main/imports.h"
+#include "main/hash.h"
+#include "main/mfeatures.h"
+#include "main/mtypes.h"
+#include "program/prog_parameter.h"
+#include "program/prog_print.h"
+#include "program/programopt.h"
+
+#include "pipe/p_context.h"
+#include "pipe/p_defines.h"
+#include "pipe/p_shader_tokens.h"
+#include "draw/draw_context.h"
+#include "tgsi/tgsi_dump.h"
+#include "tgsi/tgsi_ureg.h"
+
+#include "st_debug.h"
+#include "st_cb_bitmap.h"
+#include "st_cb_drawpixels.h"
+#include "st_context.h"
+#include "st_program.h"
+#include "st_mesa_to_tgsi.h"
+#include "cso_cache/cso_context.h"
+
+
+
+/**
+ * Delete a vertex program variant. Note the caller must unlink
+ * the variant from the linked list.
+ */
+static void
+delete_vp_variant(struct st_context *st, struct st_vp_variant *vpv)
+{
+ if (vpv->driver_shader)
+ cso_delete_vertex_shader(st->cso_context, vpv->driver_shader);
+
+#if FEATURE_feedback || FEATURE_rastpos
+ if (vpv->draw_shader)
+ draw_delete_vertex_shader( st->draw, vpv->draw_shader );
+#endif
+
+ if (vpv->tgsi.tokens)
+ st_free_tokens(vpv->tgsi.tokens);
+
+ FREE( vpv );
+}
+
+
+
+/**
+ * Clean out any old compilations:
+ */
+void
+st_release_vp_variants( struct st_context *st,
+ struct st_vertex_program *stvp )
+{
+ struct st_vp_variant *vpv;
+
+ for (vpv = stvp->variants; vpv; ) {
+ struct st_vp_variant *next = vpv->next;
+ delete_vp_variant(st, vpv);
+ vpv = next;
+ }
+
+ stvp->variants = NULL;
+}
+
+
+
+/**
+ * Delete a fragment program variant. Note the caller must unlink
+ * the variant from the linked list.
+ */
+static void
+delete_fp_variant(struct st_context *st, struct st_fp_variant *fpv)
+{
+ if (fpv->driver_shader)
+ cso_delete_fragment_shader(st->cso_context, fpv->driver_shader);
+ if (fpv->parameters)
+ _mesa_free_parameter_list(fpv->parameters);
+
+ FREE(fpv);
+}
+
+
+/**
+ * Free all variants of a fragment program.
+ */
+void
+st_release_fp_variants(struct st_context *st, struct st_fragment_program *stfp)
+{
+ struct st_fp_variant *fpv;
+
+ for (fpv = stfp->variants; fpv; ) {
+ struct st_fp_variant *next = fpv->next;
+ delete_fp_variant(st, fpv);
+ fpv = next;
+ }
+
+ stfp->variants = NULL;
+}
+
+
+/**
+ * Delete a geometry program variant. Note the caller must unlink
+ * the variant from the linked list.
+ */
+static void
+delete_gp_variant(struct st_context *st, struct st_gp_variant *gpv)
+{
+ if (gpv->driver_shader)
+ cso_delete_geometry_shader(st->cso_context, gpv->driver_shader);
+
+ FREE(gpv);
+}
+
+
+/**
+ * Free all variants of a geometry program.
+ */
+void
+st_release_gp_variants(struct st_context *st, struct st_geometry_program *stgp)
+{
+ struct st_gp_variant *gpv;
+
+ for (gpv = stgp->variants; gpv; ) {
+ struct st_gp_variant *next = gpv->next;
+ delete_gp_variant(st, gpv);
+ gpv = next;
+ }
+
+ stgp->variants = NULL;
+}
+
+
+
+
+/**
+ * Translate a Mesa vertex shader into a TGSI shader.
+ * \param outputMapping to map vertex program output registers (VERT_RESULT_x)
+ * to TGSI output slots
+ * \param tokensOut destination for TGSI tokens
+ * \return pointer to cached pipe_shader object.
+ */
+static void
+st_prepare_vertex_program(struct st_context *st,
+ struct st_vertex_program *stvp)
+{
+ GLuint attr;
+
+ stvp->num_inputs = 0;
+ stvp->num_outputs = 0;
+
+ if (stvp->Base.IsPositionInvariant)
+ _mesa_insert_mvp_code(st->ctx, &stvp->Base);
+
+ assert(stvp->Base.Base.NumInstructions > 1);
+
+ /*
+ * Determine number of inputs, the mappings between VERT_ATTRIB_x
+ * and TGSI generic input indexes, plus input attrib semantic info.
+ */
+ for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
+ if (stvp->Base.Base.InputsRead & (1 << attr)) {
+ stvp->input_to_index[attr] = stvp->num_inputs;
+ stvp->index_to_input[stvp->num_inputs] = attr;
+ stvp->num_inputs++;
+ }
+ }
+ /* bit of a hack, presetup potentially unused edgeflag input */
+ stvp->input_to_index[VERT_ATTRIB_EDGEFLAG] = stvp->num_inputs;
+ stvp->index_to_input[stvp->num_inputs] = VERT_ATTRIB_EDGEFLAG;
+
+ /* Compute mapping of vertex program outputs to slots.
+ */
+ for (attr = 0; attr < VERT_RESULT_MAX; attr++) {
+ if ((stvp->Base.Base.OutputsWritten & BITFIELD64_BIT(attr)) == 0) {
+ stvp->result_to_output[attr] = ~0;
+ }
+ else {
+ unsigned slot = stvp->num_outputs++;
+
+ stvp->result_to_output[attr] = slot;
+
+ switch (attr) {
+ case VERT_RESULT_HPOS:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
+ stvp->output_semantic_index[slot] = 0;
+ break;
+ case VERT_RESULT_COL0:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ stvp->output_semantic_index[slot] = 0;
+ break;
+ case VERT_RESULT_COL1:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ stvp->output_semantic_index[slot] = 1;
+ break;
+ case VERT_RESULT_BFC0:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
+ stvp->output_semantic_index[slot] = 0;
+ break;
+ case VERT_RESULT_BFC1:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
+ stvp->output_semantic_index[slot] = 1;
+ break;
+ case VERT_RESULT_FOGC:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_FOG;
+ stvp->output_semantic_index[slot] = 0;
+ break;
+ case VERT_RESULT_PSIZ:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_PSIZE;
+ stvp->output_semantic_index[slot] = 0;
+ break;
+ case VERT_RESULT_EDGE:
+ assert(0);
+ break;
+
+ case VERT_RESULT_TEX0:
+ case VERT_RESULT_TEX1:
+ case VERT_RESULT_TEX2:
+ case VERT_RESULT_TEX3:
+ case VERT_RESULT_TEX4:
+ case VERT_RESULT_TEX5:
+ case VERT_RESULT_TEX6:
+ case VERT_RESULT_TEX7:
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ stvp->output_semantic_index[slot] = attr - VERT_RESULT_TEX0;
+ break;
+
+ case VERT_RESULT_VAR0:
+ default:
+ assert(attr < VERT_RESULT_MAX);
+ stvp->output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ stvp->output_semantic_index[slot] = (FRAG_ATTRIB_VAR0 -
+ FRAG_ATTRIB_TEX0 +
+ attr -
+ VERT_RESULT_VAR0);
+ break;
+ }
+ }
+ }
+ /* similar hack to above, presetup potentially unused edgeflag output */
+ stvp->result_to_output[VERT_RESULT_EDGE] = stvp->num_outputs;
+ stvp->output_semantic_name[stvp->num_outputs] = TGSI_SEMANTIC_EDGEFLAG;
+ stvp->output_semantic_index[stvp->num_outputs] = 0;
+}
+
+
+/**
+ * Translate a vertex program to create a new variant.
+ */
+static struct st_vp_variant *
+st_translate_vertex_program(struct st_context *st,
+ struct st_vertex_program *stvp,
+ const struct st_vp_variant_key *key)
+{
+ struct st_vp_variant *vpv = CALLOC_STRUCT(st_vp_variant);
+ struct pipe_context *pipe = st->pipe;
+ struct ureg_program *ureg;
+ enum pipe_error error;
+ unsigned num_outputs;
+
+ st_prepare_vertex_program( st, stvp );
+
+ _mesa_remove_output_reads(&stvp->Base.Base, PROGRAM_OUTPUT);
+ _mesa_remove_output_reads(&stvp->Base.Base, PROGRAM_VARYING);
+
+ ureg = ureg_create( TGSI_PROCESSOR_VERTEX );
+ if (ureg == NULL) {
+ FREE(vpv);
+ return NULL;
+ }
+
+ vpv->key = *key;
+
+ vpv->num_inputs = stvp->num_inputs;
+ num_outputs = stvp->num_outputs;
+ if (key->passthrough_edgeflags) {
+ vpv->num_inputs++;
+ num_outputs++;
+ }
+
+ if (ST_DEBUG & DEBUG_MESA) {
+ _mesa_print_program(&stvp->Base.Base);
+ _mesa_print_program_parameters(st->ctx, &stvp->Base.Base);
+ debug_printf("\n");
+ }
+
+ error = st_translate_mesa_program(st->ctx,
+ TGSI_PROCESSOR_VERTEX,
+ ureg,
+ &stvp->Base.Base,
+ /* inputs */
+ vpv->num_inputs,
+ stvp->input_to_index,
+ NULL, /* input semantic name */
+ NULL, /* input semantic index */
+ NULL,
+ /* outputs */
+ num_outputs,
+ stvp->result_to_output,
+ stvp->output_semantic_name,
+ stvp->output_semantic_index,
+ key->passthrough_edgeflags );
+
+ if (error)
+ goto fail;
+
+ vpv->tgsi.tokens = ureg_get_tokens( ureg, NULL );
+ if (!vpv->tgsi.tokens)
+ goto fail;
+
+ ureg_destroy( ureg );
+
+ vpv->driver_shader = pipe->create_vs_state(pipe, &vpv->tgsi);
+
+ if (ST_DEBUG & DEBUG_TGSI) {
+ tgsi_dump( vpv->tgsi.tokens, 0 );
+ debug_printf("\n");
+ }
+
+ return vpv;
+
+fail:
+ debug_printf("%s: failed to translate Mesa program:\n", __FUNCTION__);
+ _mesa_print_program(&stvp->Base.Base);
+ debug_assert(0);
+
+ ureg_destroy( ureg );
+ return NULL;
+}
+
+
+/**
+ * Find/create a vertex program variant.
+ */
+struct st_vp_variant *
+st_get_vp_variant(struct st_context *st,
+ struct st_vertex_program *stvp,
+ const struct st_vp_variant_key *key)
+{
+ struct st_vp_variant *vpv;
+
+ /* Search for existing variant */
+ for (vpv = stvp->variants; vpv; vpv = vpv->next) {
+ if (memcmp(&vpv->key, key, sizeof(*key)) == 0) {
+ break;
+ }
+ }
+
+ if (!vpv) {
+ /* create now */
+ vpv = st_translate_vertex_program(st, stvp, key);
+ if (vpv) {
+ /* insert into list */
+ vpv->next = stvp->variants;
+ stvp->variants = vpv;
+ }
+ }
+
+ return vpv;
+}
+
+
+/**
+ * Translate a Mesa fragment shader into a TGSI shader using extra info in
+ * the key.
+ * \return new fragment program variant
+ */
+static struct st_fp_variant *
+st_translate_fragment_program(struct st_context *st,
+ struct st_fragment_program *stfp,
+ const struct st_fp_variant_key *key)
+{
+ struct pipe_context *pipe = st->pipe;
+ struct st_fp_variant *variant = CALLOC_STRUCT(st_fp_variant);
+ GLboolean deleteFP = GL_FALSE;
+
+ if (!variant)
+ return NULL;
+
+ assert(!(key->bitmap && key->drawpixels));
+
+#if FEATURE_drawpix
+ if (key->bitmap) {
+ /* glBitmap drawing */
+ struct gl_fragment_program *fp; /* we free this temp program below */
+
+ st_make_bitmap_fragment_program(st, &stfp->Base,
+ &fp, &variant->bitmap_sampler);
+
+ variant->parameters = _mesa_clone_parameter_list(fp->Base.Parameters);
+ stfp = st_fragment_program(fp);
+ deleteFP = GL_TRUE;
+ }
+ else if (key->drawpixels) {
+ /* glDrawPixels drawing */
+ struct gl_fragment_program *fp; /* we free this temp program below */
+
+ if (key->drawpixels_z || key->drawpixels_stencil) {
+ fp = st_make_drawpix_z_stencil_program(st, key->drawpixels_z,
+ key->drawpixels_stencil);
+ }
+ else {
+ /* RGBA */
+ st_make_drawpix_fragment_program(st, &stfp->Base, &fp);
+ variant->parameters = _mesa_clone_parameter_list(fp->Base.Parameters);
+ deleteFP = GL_TRUE;
+ }
+ stfp = st_fragment_program(fp);
+ }
+#endif
+
+ if (!stfp->tgsi.tokens) {
+ /* need to translate Mesa instructions to TGSI now */
+ GLuint outputMapping[FRAG_RESULT_MAX];
+ GLuint inputMapping[FRAG_ATTRIB_MAX];
+ GLuint interpMode[PIPE_MAX_SHADER_INPUTS]; /* XXX size? */
+ GLuint attr;
+ enum pipe_error error;
+ const GLbitfield inputsRead = stfp->Base.Base.InputsRead;
+ struct ureg_program *ureg;
+ GLboolean write_all = GL_FALSE;
+
+ ubyte input_semantic_name[PIPE_MAX_SHADER_INPUTS];
+ ubyte input_semantic_index[PIPE_MAX_SHADER_INPUTS];
+ uint fs_num_inputs = 0;
+
+ ubyte fs_output_semantic_name[PIPE_MAX_SHADER_OUTPUTS];
+ ubyte fs_output_semantic_index[PIPE_MAX_SHADER_OUTPUTS];
+ uint fs_num_outputs = 0;
+
+
+ _mesa_remove_output_reads(&stfp->Base.Base, PROGRAM_OUTPUT);
+
+ /*
+ * Convert Mesa program inputs to TGSI input register semantics.
+ */
+ for (attr = 0; attr < FRAG_ATTRIB_MAX; attr++) {
+ if (inputsRead & (1 << attr)) {
+ const GLuint slot = fs_num_inputs++;
+
+ inputMapping[attr] = slot;
+
+ switch (attr) {
+ case FRAG_ATTRIB_WPOS:
+ input_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
+ input_semantic_index[slot] = 0;
+ interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
+ break;
+ case FRAG_ATTRIB_COL0:
+ input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ input_semantic_index[slot] = 0;
+ interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
+ break;
+ case FRAG_ATTRIB_COL1:
+ input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ input_semantic_index[slot] = 1;
+ interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
+ break;
+ case FRAG_ATTRIB_FOGC:
+ input_semantic_name[slot] = TGSI_SEMANTIC_FOG;
+ input_semantic_index[slot] = 0;
+ interpMode[slot] = TGSI_INTERPOLATE_PERSPECTIVE;
+ break;
+ case FRAG_ATTRIB_FACE:
+ input_semantic_name[slot] = TGSI_SEMANTIC_FACE;
+ input_semantic_index[slot] = 0;
+ interpMode[slot] = TGSI_INTERPOLATE_CONSTANT;
+ break;
+ /* In most cases, there is nothing special about these
+ * inputs, so adopt a convention to use the generic
+ * semantic name and the mesa FRAG_ATTRIB_ number as the
+ * index.
+ *
+ * All that is required is that the vertex shader labels
+ * its own outputs similarly, and that the vertex shader
+ * generates at least every output required by the
+ * fragment shader plus fixed-function hardware (such as
+ * BFC).
+ *
+ * There is no requirement that semantic indexes start at
+ * zero or be restricted to a particular range -- nobody
+ * should be building tables based on semantic index.
+ */
+ case FRAG_ATTRIB_PNTC:
+ case FRAG_ATTRIB_TEX0:
+ case FRAG_ATTRIB_TEX1:
+ case FRAG_ATTRIB_TEX2:
+ case FRAG_ATTRIB_TEX3:
+ case FRAG_ATTRIB_TEX4:
+ case FRAG_ATTRIB_TEX5:
+ case FRAG_ATTRIB_TEX6:
+ case FRAG_ATTRIB_TEX7:
+ case FRAG_ATTRIB_VAR0:
+ default:
+ /* Actually, let's try and zero-base this just for
+ * readability of the generated TGSI.
+ */
+ assert(attr >= FRAG_ATTRIB_TEX0);
+ input_semantic_index[slot] = (attr - FRAG_ATTRIB_TEX0);
+ input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ if (attr == FRAG_ATTRIB_PNTC)
+ interpMode[slot] = TGSI_INTERPOLATE_LINEAR;
+ else
+ interpMode[slot] = TGSI_INTERPOLATE_PERSPECTIVE;
+ break;
+ }
+ }
+ else {
+ inputMapping[attr] = -1;
+ }
+ }
+
+ /*
+ * Semantics and mapping for outputs
+ */
+ {
+ uint numColors = 0;
+ GLbitfield64 outputsWritten = stfp->Base.Base.OutputsWritten;
+
+ /* if z is written, emit that first */
+ if (outputsWritten & BITFIELD64_BIT(FRAG_RESULT_DEPTH)) {
+ fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_POSITION;
+ fs_output_semantic_index[fs_num_outputs] = 0;
+ outputMapping[FRAG_RESULT_DEPTH] = fs_num_outputs;
+ fs_num_outputs++;
+ outputsWritten &= ~(1 << FRAG_RESULT_DEPTH);
+ }
+
+ if (outputsWritten & BITFIELD64_BIT(FRAG_RESULT_STENCIL)) {
+ fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_STENCIL;
+ fs_output_semantic_index[fs_num_outputs] = 0;
+ outputMapping[FRAG_RESULT_STENCIL] = fs_num_outputs;
+ fs_num_outputs++;
+ outputsWritten &= ~(1 << FRAG_RESULT_STENCIL);
+ }
+
+ /* handle remaning outputs (color) */
+ for (attr = 0; attr < FRAG_RESULT_MAX; attr++) {
+ if (outputsWritten & BITFIELD64_BIT(attr)) {
+ switch (attr) {
+ case FRAG_RESULT_DEPTH:
+ case FRAG_RESULT_STENCIL:
+ /* handled above */
+ assert(0);
+ break;
+ case FRAG_RESULT_COLOR:
+ write_all = GL_TRUE; /* fallthrough */
+ default:
+ assert(attr == FRAG_RESULT_COLOR ||
+ (FRAG_RESULT_DATA0 <= attr && attr < FRAG_RESULT_MAX));
+ fs_output_semantic_name[fs_num_outputs] = TGSI_SEMANTIC_COLOR;
+ fs_output_semantic_index[fs_num_outputs] = numColors;
+ outputMapping[attr] = fs_num_outputs;
+ numColors++;
+ break;
+ }
+
+ fs_num_outputs++;
+ }
+ }
+ }
+
+ ureg = ureg_create( TGSI_PROCESSOR_FRAGMENT );
+ if (ureg == NULL)
+ return NULL;
+
+ if (ST_DEBUG & DEBUG_MESA) {
+ _mesa_print_program(&stfp->Base.Base);
+ _mesa_print_program_parameters(st->ctx, &stfp->Base.Base);
+ debug_printf("\n");
+ }
+ if (write_all == GL_TRUE)
+ ureg_property_fs_color0_writes_all_cbufs(ureg, 1);
+
+ error = st_translate_mesa_program(st->ctx,
+ TGSI_PROCESSOR_FRAGMENT,
+ ureg,
+ &stfp->Base.Base,
+ /* inputs */
+ fs_num_inputs,
+ inputMapping,
+ input_semantic_name,
+ input_semantic_index,
+ interpMode,
+ /* outputs */
+ fs_num_outputs,
+ outputMapping,
+ fs_output_semantic_name,
+ fs_output_semantic_index, FALSE );
+
+ stfp->tgsi.tokens = ureg_get_tokens( ureg, NULL );
+ ureg_destroy( ureg );
+ }
+
+ /* fill in variant */
+ variant->driver_shader = pipe->create_fs_state(pipe, &stfp->tgsi);
+ variant->key = *key;
+
+ if (ST_DEBUG & DEBUG_TGSI) {
+ tgsi_dump( stfp->tgsi.tokens, 0/*TGSI_DUMP_VERBOSE*/ );
+ debug_printf("\n");
+ }
+
+ if (deleteFP) {
+ /* Free the temporary program made above */
+ struct gl_fragment_program *fp = &stfp->Base;
+ _mesa_reference_fragprog(st->ctx, &fp, NULL);
+ }
+
+ return variant;
+}
+
+
+/**
+ * Translate fragment program if needed.
+ */
+struct st_fp_variant *
+st_get_fp_variant(struct st_context *st,
+ struct st_fragment_program *stfp,
+ const struct st_fp_variant_key *key)
+{
+ struct st_fp_variant *fpv;
+
+ /* Search for existing variant */
+ for (fpv = stfp->variants; fpv; fpv = fpv->next) {
+ if (memcmp(&fpv->key, key, sizeof(*key)) == 0) {
+ break;
+ }
+ }
+
+ if (!fpv) {
+ /* create new */
+ fpv = st_translate_fragment_program(st, stfp, key);
+ if (fpv) {
+ /* insert into list */
+ fpv->next = stfp->variants;
+ stfp->variants = fpv;
+ }
+ }
+
+ return fpv;
+}
+
+
+/**
+ * Translate a geometry program to create a new variant.
+ */
+static struct st_gp_variant *
+st_translate_geometry_program(struct st_context *st,
+ struct st_geometry_program *stgp,
+ const struct st_gp_variant_key *key)
+{
+ GLuint inputMapping[GEOM_ATTRIB_MAX];
+ GLuint outputMapping[GEOM_RESULT_MAX];
+ struct pipe_context *pipe = st->pipe;
+ enum pipe_error error;
+ GLuint attr;
+ const GLbitfield inputsRead = stgp->Base.Base.InputsRead;
+ GLuint vslot = 0;
+ GLuint num_generic = 0;
+
+ uint gs_num_inputs = 0;
+ uint gs_builtin_inputs = 0;
+ uint gs_array_offset = 0;
+
+ ubyte gs_output_semantic_name[PIPE_MAX_SHADER_OUTPUTS];
+ ubyte gs_output_semantic_index[PIPE_MAX_SHADER_OUTPUTS];
+ uint gs_num_outputs = 0;
+
+ GLint i;
+ GLuint maxSlot = 0;
+ struct ureg_program *ureg;
+
+ struct st_gp_variant *gpv;
+
+ gpv = CALLOC_STRUCT(st_gp_variant);
+ if (!gpv)
+ return NULL;
+
+ _mesa_remove_output_reads(&stgp->Base.Base, PROGRAM_OUTPUT);
+ _mesa_remove_output_reads(&stgp->Base.Base, PROGRAM_VARYING);
+
+ ureg = ureg_create( TGSI_PROCESSOR_GEOMETRY );
+ if (ureg == NULL) {
+ FREE(gpv);
+ return NULL;
+ }
+
+ /* which vertex output goes to the first geometry input */
+ vslot = 0;
+
+ memset(inputMapping, 0, sizeof(inputMapping));
+ memset(outputMapping, 0, sizeof(outputMapping));
+
+ /*
+ * Convert Mesa program inputs to TGSI input register semantics.
+ */
+ for (attr = 0; attr < GEOM_ATTRIB_MAX; attr++) {
+ if (inputsRead & (1 << attr)) {
+ const GLuint slot = gs_num_inputs;
+
+ gs_num_inputs++;
+
+ inputMapping[attr] = slot;
+
+ stgp->input_map[slot + gs_array_offset] = vslot - gs_builtin_inputs;
+ stgp->input_to_index[attr] = vslot;
+ stgp->index_to_input[vslot] = attr;
+ ++vslot;
+
+ if (attr != GEOM_ATTRIB_PRIMITIVE_ID) {
+ gs_array_offset += 2;
+ } else
+ ++gs_builtin_inputs;
+
+#if 0
+ debug_printf("input map at %d = %d\n",
+ slot + gs_array_offset, stgp->input_map[slot + gs_array_offset]);
+#endif
+
+ switch (attr) {
+ case GEOM_ATTRIB_PRIMITIVE_ID:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_PRIMID;
+ stgp->input_semantic_index[slot] = 0;
+ break;
+ case GEOM_ATTRIB_POSITION:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
+ stgp->input_semantic_index[slot] = 0;
+ break;
+ case GEOM_ATTRIB_COLOR0:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ stgp->input_semantic_index[slot] = 0;
+ break;
+ case GEOM_ATTRIB_COLOR1:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ stgp->input_semantic_index[slot] = 1;
+ break;
+ case GEOM_ATTRIB_FOG_FRAG_COORD:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_FOG;
+ stgp->input_semantic_index[slot] = 0;
+ break;
+ case GEOM_ATTRIB_TEX_COORD:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ stgp->input_semantic_index[slot] = num_generic++;
+ break;
+ case GEOM_ATTRIB_VAR0:
+ /* fall-through */
+ default:
+ stgp->input_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ stgp->input_semantic_index[slot] = num_generic++;
+ }
+ }
+ }
+
+ /* initialize output semantics to defaults */
+ for (i = 0; i < PIPE_MAX_SHADER_OUTPUTS; i++) {
+ gs_output_semantic_name[i] = TGSI_SEMANTIC_GENERIC;
+ gs_output_semantic_index[i] = 0;
+ }
+
+ num_generic = 0;
+ /*
+ * Determine number of outputs, the (default) output register
+ * mapping and the semantic information for each output.
+ */
+ for (attr = 0; attr < GEOM_RESULT_MAX; attr++) {
+ if (stgp->Base.Base.OutputsWritten & (1 << attr)) {
+ GLuint slot;
+
+ slot = gs_num_outputs;
+ gs_num_outputs++;
+ outputMapping[attr] = slot;
+
+ switch (attr) {
+ case GEOM_RESULT_POS:
+ assert(slot == 0);
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_POSITION;
+ gs_output_semantic_index[slot] = 0;
+ break;
+ case GEOM_RESULT_COL0:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ gs_output_semantic_index[slot] = 0;
+ break;
+ case GEOM_RESULT_COL1:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_COLOR;
+ gs_output_semantic_index[slot] = 1;
+ break;
+ case GEOM_RESULT_SCOL0:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
+ gs_output_semantic_index[slot] = 0;
+ break;
+ case GEOM_RESULT_SCOL1:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_BCOLOR;
+ gs_output_semantic_index[slot] = 1;
+ break;
+ case GEOM_RESULT_FOGC:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_FOG;
+ gs_output_semantic_index[slot] = 0;
+ break;
+ case GEOM_RESULT_PSIZ:
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_PSIZE;
+ gs_output_semantic_index[slot] = 0;
+ break;
+ case GEOM_RESULT_TEX0:
+ case GEOM_RESULT_TEX1:
+ case GEOM_RESULT_TEX2:
+ case GEOM_RESULT_TEX3:
+ case GEOM_RESULT_TEX4:
+ case GEOM_RESULT_TEX5:
+ case GEOM_RESULT_TEX6:
+ case GEOM_RESULT_TEX7:
+ /* fall-through */
+ case GEOM_RESULT_VAR0:
+ /* fall-through */
+ default:
+ assert(slot < Elements(gs_output_semantic_name));
+ /* use default semantic info */
+ gs_output_semantic_name[slot] = TGSI_SEMANTIC_GENERIC;
+ gs_output_semantic_index[slot] = num_generic++;
+ }
+ }
+ }
+
+ assert(gs_output_semantic_name[0] == TGSI_SEMANTIC_POSITION);
+
+ /* find max output slot referenced to compute gs_num_outputs */
+ for (attr = 0; attr < GEOM_RESULT_MAX; attr++) {
+ if (outputMapping[attr] != ~0 && outputMapping[attr] > maxSlot)
+ maxSlot = outputMapping[attr];
+ }
+ gs_num_outputs = maxSlot + 1;
+
+#if 0 /* debug */
+ {
+ GLuint i;
+ printf("outputMapping? %d\n", outputMapping ? 1 : 0);
+ if (outputMapping) {
+ printf("attr -> slot\n");
+ for (i = 0; i < 16; i++) {
+ printf(" %2d %3d\n", i, outputMapping[i]);
+ }
+ }
+ printf("slot sem_name sem_index\n");
+ for (i = 0; i < gs_num_outputs; i++) {
+ printf(" %2d %d %d\n",
+ i,
+ gs_output_semantic_name[i],
+ gs_output_semantic_index[i]);
+ }
+ }
+#endif
+
+ /* free old shader state, if any */
+ if (stgp->tgsi.tokens) {
+ st_free_tokens(stgp->tgsi.tokens);
+ stgp->tgsi.tokens = NULL;
+ }
+
+ ureg_property_gs_input_prim(ureg, stgp->Base.InputType);
+ ureg_property_gs_output_prim(ureg, stgp->Base.OutputType);
+ ureg_property_gs_max_vertices(ureg, stgp->Base.VerticesOut);
+
+ error = st_translate_mesa_program(st->ctx,
+ TGSI_PROCESSOR_GEOMETRY,
+ ureg,
+ &stgp->Base.Base,
+ /* inputs */
+ gs_num_inputs,
+ inputMapping,
+ stgp->input_semantic_name,
+ stgp->input_semantic_index,
+ NULL,
+ /* outputs */
+ gs_num_outputs,
+ outputMapping,
+ gs_output_semantic_name,
+ gs_output_semantic_index,
+ FALSE);
+
+ stgp->num_inputs = gs_num_inputs;
+ stgp->tgsi.tokens = ureg_get_tokens( ureg, NULL );
+ ureg_destroy( ureg );
+
+ /* fill in new variant */
+ gpv->driver_shader = pipe->create_gs_state(pipe, &stgp->tgsi);
+ gpv->key = *key;
+
+ if ((ST_DEBUG & DEBUG_TGSI) && (ST_DEBUG & DEBUG_MESA)) {
+ _mesa_print_program(&stgp->Base.Base);
+ debug_printf("\n");
+ }
+
+ if (ST_DEBUG & DEBUG_TGSI) {
+ tgsi_dump(stgp->tgsi.tokens, 0);
+ debug_printf("\n");
+ }
+
+ return gpv;
+}
+
+
+/**
+ * Get/create geometry program variant.
+ */
+struct st_gp_variant *
+st_get_gp_variant(struct st_context *st,
+ struct st_geometry_program *stgp,
+ const struct st_gp_variant_key *key)
+{
+ struct st_gp_variant *gpv;
+
+ /* Search for existing variant */
+ for (gpv = stgp->variants; gpv; gpv = gpv->next) {
+ if (memcmp(&gpv->key, key, sizeof(*key)) == 0) {
+ break;
+ }
+ }
+
+ if (!gpv) {
+ /* create new */
+ gpv = st_translate_geometry_program(st, stgp, key);
+ if (gpv) {
+ /* insert into list */
+ gpv->next = stgp->variants;
+ stgp->variants = gpv;
+ }
+ }
+
+ return gpv;
+}
+
+
+
+
+/**
+ * Debug- print current shader text
+ */
+void
+st_print_shaders(struct gl_context *ctx)
+{
+ struct gl_shader_program *shProg[3] = {
+ ctx->Shader.CurrentVertexProgram,
+ ctx->Shader.CurrentGeometryProgram,
+ ctx->Shader.CurrentFragmentProgram,
+ };
+ unsigned j;
+
+ for (j = 0; j < 3; j++) {
+ unsigned i;
+
+ if (shProg[j] == NULL)
+ continue;
+
+ for (i = 0; i < shProg[j]->NumShaders; i++) {
+ struct gl_shader *sh;
+
+ switch (shProg[j]->Shaders[i]->Type) {
+ case GL_VERTEX_SHADER:
+ sh = (i != 0) ? NULL : shProg[j]->Shaders[i];
+ break;
+ case GL_GEOMETRY_SHADER_ARB:
+ sh = (i != 1) ? NULL : shProg[j]->Shaders[i];
+ break;
+ case GL_FRAGMENT_SHADER:
+ sh = (i != 2) ? NULL : shProg[j]->Shaders[i];
+ break;
+ default:
+ assert(0);
+ sh = NULL;
+ break;
+ }
+
+ if (sh != NULL) {
+ printf("GLSL shader %u of %u:\n", i, shProg[j]->NumShaders);
+ printf("%s\n", sh->Source);
+ }
+ }
+ }
+}
+
+
+/**
+ * Vert/Geom/Frag programs have per-context variants. Free all the
+ * variants attached to the given program which match the given context.
+ */
+static void
+destroy_program_variants(struct st_context *st, struct gl_program *program)
+{
+ if (!program)
+ return;
+
+ switch (program->Target) {
+ case GL_VERTEX_PROGRAM_ARB:
+ {
+ struct st_vertex_program *stvp = (struct st_vertex_program *) program;
+ struct st_vp_variant *vpv, **prevPtr = &stvp->variants;
+
+ for (vpv = stvp->variants; vpv; ) {
+ struct st_vp_variant *next = vpv->next;
+ if (vpv->key.st == st) {
+ /* unlink from list */
+ *prevPtr = next;
+ /* destroy this variant */
+ delete_vp_variant(st, vpv);
+ }
+ else {
+ prevPtr = &vpv->next;
+ }
+ vpv = next;
+ }
+ }
+ break;
+ case GL_FRAGMENT_PROGRAM_ARB:
+ {
+ struct st_fragment_program *stfp =
+ (struct st_fragment_program *) program;
+ struct st_fp_variant *fpv, **prevPtr = &stfp->variants;
+
+ for (fpv = stfp->variants; fpv; ) {
+ struct st_fp_variant *next = fpv->next;
+ if (fpv->key.st == st) {
+ /* unlink from list */
+ *prevPtr = next;
+ /* destroy this variant */
+ delete_fp_variant(st, fpv);
+ }
+ else {
+ prevPtr = &fpv->next;
+ }
+ fpv = next;
+ }
+ }
+ break;
+ case MESA_GEOMETRY_PROGRAM:
+ {
+ struct st_geometry_program *stgp =
+ (struct st_geometry_program *) program;
+ struct st_gp_variant *gpv, **prevPtr = &stgp->variants;
+
+ for (gpv = stgp->variants; gpv; ) {
+ struct st_gp_variant *next = gpv->next;
+ if (gpv->key.st == st) {
+ /* unlink from list */
+ *prevPtr = next;
+ /* destroy this variant */
+ delete_gp_variant(st, gpv);
+ }
+ else {
+ prevPtr = &gpv->next;
+ }
+ gpv = next;
+ }
+ }
+ break;
+ default:
+ _mesa_problem(NULL, "Unexpected program target in "
+ "destroy_program_variants_cb()");
+ }
+}
+
+
+/**
+ * Callback for _mesa_HashWalk. Free all the shader's program variants
+ * which match the given context.
+ */
+static void
+destroy_shader_program_variants_cb(GLuint key, void *data, void *userData)
+{
+ struct st_context *st = (struct st_context *) userData;
+ struct gl_shader *shader = (struct gl_shader *) data;
+
+ switch (shader->Type) {
+ case GL_SHADER_PROGRAM_MESA:
+ {
+ struct gl_shader_program *shProg = (struct gl_shader_program *) data;
+ GLuint i;
+
+ for (i = 0; i < shProg->NumShaders; i++) {
+ destroy_program_variants(st, shProg->Shaders[i]->Program);
+ }
+
+ destroy_program_variants(st, (struct gl_program *)
+ shProg->VertexProgram);
+ destroy_program_variants(st, (struct gl_program *)
+ shProg->FragmentProgram);
+ destroy_program_variants(st, (struct gl_program *)
+ shProg->GeometryProgram);
+ }
+ break;
+ case GL_VERTEX_SHADER:
+ case GL_FRAGMENT_SHADER:
+ case GL_GEOMETRY_SHADER:
+ {
+ destroy_program_variants(st, shader->Program);
+ }
+ break;
+ default:
+ assert(0);
+ }
+}
+
+
+/**
+ * Callback for _mesa_HashWalk. Free all the program variants which match
+ * the given context.
+ */
+static void
+destroy_program_variants_cb(GLuint key, void *data, void *userData)
+{
+ struct st_context *st = (struct st_context *) userData;
+ struct gl_program *program = (struct gl_program *) data;
+ destroy_program_variants(st, program);
+}
+
+
+/**
+ * Walk over all shaders and programs to delete any variants which
+ * belong to the given context.
+ * This is called during context tear-down.
+ */
+void
+st_destroy_program_variants(struct st_context *st)
+{
+ /* ARB vert/frag program */
+ _mesa_HashWalk(st->ctx->Shared->Programs,
+ destroy_program_variants_cb, st);
+
+ /* GLSL vert/frag/geom shaders */
+ _mesa_HashWalk(st->ctx->Shared->ShaderObjects,
+ destroy_shader_program_variants_cb, st);
+}
diff --git a/mesalib/src/mesa/tnl/t_draw.c b/mesalib/src/mesa/tnl/t_draw.c
index b1967e654..a2ca6225b 100644
--- a/mesalib/src/mesa/tnl/t_draw.c
+++ b/mesalib/src/mesa/tnl/t_draw.c
@@ -1,534 +1,534 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.1
- *
- * Copyright (C) 1999-2007 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- */
-
-#include "main/glheader.h"
-#include "main/condrender.h"
-#include "main/context.h"
-#include "main/imports.h"
-#include "main/mtypes.h"
-#include "main/macros.h"
-#include "main/enums.h"
-
-#include "t_context.h"
-#include "tnl.h"
-
-
-
-static GLubyte *get_space(struct gl_context *ctx, GLuint bytes)
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- GLubyte *space = malloc(bytes);
-
- tnl->block[tnl->nr_blocks++] = space;
- return space;
-}
-
-
-static void free_space(struct gl_context *ctx)
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- GLuint i;
- for (i = 0; i < tnl->nr_blocks; i++)
- free(tnl->block[i]);
- tnl->nr_blocks = 0;
-}
-
-
-/* Convert the incoming array to GLfloats. Understands the
- * array->Normalized flag and selects the correct conversion method.
- */
-#define CONVERT( TYPE, MACRO ) do { \
- GLuint i, j; \
- if (input->Normalized) { \
- for (i = 0; i < count; i++) { \
- const TYPE *in = (TYPE *)ptr; \
- for (j = 0; j < sz; j++) { \
- *fptr++ = MACRO(*in); \
- in++; \
- } \
- ptr += input->StrideB; \
- } \
- } else { \
- for (i = 0; i < count; i++) { \
- const TYPE *in = (TYPE *)ptr; \
- for (j = 0; j < sz; j++) { \
- *fptr++ = (GLfloat)(*in); \
- in++; \
- } \
- ptr += input->StrideB; \
- } \
- } \
-} while (0)
-
-
-/**
- * Convert array of BGRA/GLubyte[4] values to RGBA/float[4]
- * \param ptr input/ubyte array
- * \param fptr output/float array
- */
-static void
-convert_bgra_to_float(const struct gl_client_array *input,
- const GLubyte *ptr, GLfloat *fptr,
- GLuint count )
-{
- GLuint i;
- assert(input->Normalized);
- assert(input->Size == 4);
- for (i = 0; i < count; i++) {
- const GLubyte *in = (GLubyte *) ptr; /* in is in BGRA order */
- *fptr++ = UBYTE_TO_FLOAT(in[2]); /* red */
- *fptr++ = UBYTE_TO_FLOAT(in[1]); /* green */
- *fptr++ = UBYTE_TO_FLOAT(in[0]); /* blue */
- *fptr++ = UBYTE_TO_FLOAT(in[3]); /* alpha */
- ptr += input->StrideB;
- }
-}
-
-static void
-convert_half_to_float(const struct gl_client_array *input,
- const GLubyte *ptr, GLfloat *fptr,
- GLuint count, GLuint sz)
-{
- GLuint i, j;
-
- for (i = 0; i < count; i++) {
- GLhalfARB *in = (GLhalfARB *)ptr;
-
- for (j = 0; j < sz; j++) {
- *fptr++ = _mesa_half_to_float(in[j]);
- }
- ptr += input->StrideB;
- }
-}
-
-/**
- * \brief Convert fixed-point to floating-point.
- *
- * In OpenGL, a fixed-point number is a "signed 2's complement 16.16 scaled
- * integer" (Table 2.2 of the OpenGL ES 2.0 spec).
- *
- * If the buffer has the \c normalized flag set, the formula
- * \code normalize(x) := (2*x + 1) / (2^16 - 1) \endcode
- * is used to map the fixed-point numbers into the range [-1, 1].
- */
-static void
-convert_fixed_to_float(const struct gl_client_array *input,
- const GLubyte *ptr, GLfloat *fptr,
- GLuint count)
-{
- GLuint i, j;
- const GLint size = input->Size;
-
- if (input->Normalized) {
- for (i = 0; i < count; ++i) {
- const GLfixed *in = (GLfixed *) ptr;
- for (j = 0; j < size; ++j) {
- *fptr++ = (GLfloat) (2 * in[j] + 1) / (GLfloat) ((1 << 16) - 1);
- }
- ptr += input->StrideB;
- }
- } else {
- for (i = 0; i < count; ++i) {
- const GLfixed *in = (GLfixed *) ptr;
- for (j = 0; j < size; ++j) {
- *fptr++ = in[j] / (GLfloat) (1 << 16);
- }
- ptr += input->StrideB;
- }
- }
-}
-
-/* Adjust pointer to point at first requested element, convert to
- * floating point, populate VB->AttribPtr[].
- */
-static void _tnl_import_array( struct gl_context *ctx,
- GLuint attrib,
- GLuint count,
- const struct gl_client_array *input,
- const GLubyte *ptr )
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- struct vertex_buffer *VB = &tnl->vb;
- GLuint stride = input->StrideB;
-
- if (input->Type != GL_FLOAT) {
- const GLuint sz = input->Size;
- GLubyte *buf = get_space(ctx, count * sz * sizeof(GLfloat));
- GLfloat *fptr = (GLfloat *)buf;
-
- switch (input->Type) {
- case GL_BYTE:
- CONVERT(GLbyte, BYTE_TO_FLOAT);
- break;
- case GL_UNSIGNED_BYTE:
- if (input->Format == GL_BGRA) {
- /* See GL_EXT_vertex_array_bgra */
- convert_bgra_to_float(input, ptr, fptr, count);
- }
- else {
- CONVERT(GLubyte, UBYTE_TO_FLOAT);
- }
- break;
- case GL_SHORT:
- CONVERT(GLshort, SHORT_TO_FLOAT);
- break;
- case GL_UNSIGNED_SHORT:
- CONVERT(GLushort, USHORT_TO_FLOAT);
- break;
- case GL_INT:
- CONVERT(GLint, INT_TO_FLOAT);
- break;
- case GL_UNSIGNED_INT:
- CONVERT(GLuint, UINT_TO_FLOAT);
- break;
- case GL_DOUBLE:
- CONVERT(GLdouble, (GLfloat));
- break;
- case GL_HALF_FLOAT:
- convert_half_to_float(input, ptr, fptr, count, sz);
- break;
- case GL_FIXED:
- convert_fixed_to_float(input, ptr, fptr, count);
- break;
- default:
- assert(0);
- break;
- }
-
- ptr = buf;
- stride = sz * sizeof(GLfloat);
- }
-
- VB->AttribPtr[attrib] = &tnl->tmp_inputs[attrib];
- VB->AttribPtr[attrib]->data = (GLfloat (*)[4])ptr;
- VB->AttribPtr[attrib]->start = (GLfloat *)ptr;
- VB->AttribPtr[attrib]->count = count;
- VB->AttribPtr[attrib]->stride = stride;
- VB->AttribPtr[attrib]->size = input->Size;
-
- /* This should die, but so should the whole GLvector4f concept:
- */
- VB->AttribPtr[attrib]->flags = (((1<<input->Size)-1) |
- VEC_NOT_WRITEABLE |
- (stride == 4*sizeof(GLfloat) ? 0 : VEC_BAD_STRIDE));
-
- VB->AttribPtr[attrib]->storage = NULL;
-}
-
-#define CLIPVERTS ((6 + MAX_CLIP_PLANES) * 2)
-
-
-static GLboolean *_tnl_import_edgeflag( struct gl_context *ctx,
- const GLvector4f *input,
- GLuint count)
-{
- const GLubyte *ptr = (const GLubyte *)input->data;
- const GLuint stride = input->stride;
- GLboolean *space = (GLboolean *)get_space(ctx, count + CLIPVERTS);
- GLboolean *bptr = space;
- GLuint i;
-
- for (i = 0; i < count; i++) {
- *bptr++ = ((GLfloat *)ptr)[0] == 1.0;
- ptr += stride;
- }
-
- return space;
-}
-
-
-static void bind_inputs( struct gl_context *ctx,
- const struct gl_client_array *inputs[],
- GLint count,
- struct gl_buffer_object **bo,
- GLuint *nr_bo )
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- struct vertex_buffer *VB = &tnl->vb;
- GLuint i;
-
- /* Map all the VBOs
- */
- for (i = 0; i < VERT_ATTRIB_MAX; i++) {
- const void *ptr;
-
- if (inputs[i]->BufferObj->Name) {
- if (!inputs[i]->BufferObj->Pointer) {
- bo[*nr_bo] = inputs[i]->BufferObj;
- (*nr_bo)++;
- ctx->Driver.MapBuffer(ctx,
- GL_ARRAY_BUFFER,
- GL_READ_ONLY_ARB,
- inputs[i]->BufferObj);
-
- assert(inputs[i]->BufferObj->Pointer);
- }
-
- ptr = ADD_POINTERS(inputs[i]->BufferObj->Pointer,
- inputs[i]->Ptr);
- }
- else
- ptr = inputs[i]->Ptr;
-
- /* Just make sure the array is floating point, otherwise convert to
- * temporary storage.
- *
- * XXX: remove the GLvector4f type at some stage and just use
- * client arrays.
- */
- _tnl_import_array(ctx, i, count, inputs[i], ptr);
- }
-
- /* We process only the vertices between min & max index:
- */
- VB->Count = count;
-
- /* These should perhaps be part of _TNL_ATTRIB_* */
- VB->BackfaceColorPtr = NULL;
- VB->BackfaceIndexPtr = NULL;
- VB->BackfaceSecondaryColorPtr = NULL;
-
- /* Clipping and drawing code still requires this to be a packed
- * array of ubytes which can be written into. TODO: Fix and
- * remove.
- */
- if (ctx->Polygon.FrontMode != GL_FILL ||
- ctx->Polygon.BackMode != GL_FILL)
- {
- VB->EdgeFlag = _tnl_import_edgeflag( ctx,
- VB->AttribPtr[_TNL_ATTRIB_EDGEFLAG],
- VB->Count );
- }
- else {
- /* the data previously pointed to by EdgeFlag may have been freed */
- VB->EdgeFlag = NULL;
- }
-}
-
-
-/* Translate indices to GLuints and store in VB->Elts.
- */
-static void bind_indices( struct gl_context *ctx,
- const struct _mesa_index_buffer *ib,
- struct gl_buffer_object **bo,
- GLuint *nr_bo)
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- struct vertex_buffer *VB = &tnl->vb;
- GLuint i;
- void *ptr;
-
- if (!ib) {
- VB->Elts = NULL;
- return;
- }
-
- if (ib->obj->Name && !ib->obj->Pointer) {
- bo[*nr_bo] = ib->obj;
- (*nr_bo)++;
- ctx->Driver.MapBuffer(ctx,
- GL_ELEMENT_ARRAY_BUFFER,
- GL_READ_ONLY_ARB,
- ib->obj);
-
- assert(ib->obj->Pointer);
- }
-
- ptr = ADD_POINTERS(ib->obj->Pointer, ib->ptr);
-
- if (ib->type == GL_UNSIGNED_INT && VB->Primitive[0].basevertex == 0) {
- VB->Elts = (GLuint *) ptr;
- }
- else {
- GLuint *elts = (GLuint *)get_space(ctx, ib->count * sizeof(GLuint));
- VB->Elts = elts;
-
- if (ib->type == GL_UNSIGNED_INT) {
- const GLuint *in = (GLuint *)ptr;
- for (i = 0; i < ib->count; i++)
- *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
- }
- else if (ib->type == GL_UNSIGNED_SHORT) {
- const GLushort *in = (GLushort *)ptr;
- for (i = 0; i < ib->count; i++)
- *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
- }
- else {
- const GLubyte *in = (GLubyte *)ptr;
- for (i = 0; i < ib->count; i++)
- *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
- }
- }
-}
-
-static void bind_prims( struct gl_context *ctx,
- const struct _mesa_prim *prim,
- GLuint nr_prims )
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- struct vertex_buffer *VB = &tnl->vb;
-
- VB->Primitive = prim;
- VB->PrimitiveCount = nr_prims;
-}
-
-static void unmap_vbos( struct gl_context *ctx,
- struct gl_buffer_object **bo,
- GLuint nr_bo )
-{
- GLuint i;
- for (i = 0; i < nr_bo; i++) {
- ctx->Driver.UnmapBuffer(ctx,
- 0, /* target -- I don't see why this would be needed */
- bo[i]);
- }
-}
-
-
-void _tnl_vbo_draw_prims(struct gl_context *ctx,
- const struct gl_client_array *arrays[],
- const struct _mesa_prim *prim,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLboolean index_bounds_valid,
- GLuint min_index,
- GLuint max_index)
-{
- if (!index_bounds_valid)
- vbo_get_minmax_index(ctx, prim, ib, &min_index, &max_index);
-
- _tnl_draw_prims(ctx, arrays, prim, nr_prims, ib, min_index, max_index);
-}
-
-/* This is the main entrypoint into the slimmed-down software tnl
- * module. In a regular swtnl driver, this can be plugged straight
- * into the vbo->Driver.DrawPrims() callback.
- */
-void _tnl_draw_prims( struct gl_context *ctx,
- const struct gl_client_array *arrays[],
- const struct _mesa_prim *prim,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLuint min_index,
- GLuint max_index)
-{
- TNLcontext *tnl = TNL_CONTEXT(ctx);
- const GLuint TEST_SPLIT = 0;
- const GLint max = TEST_SPLIT ? 8 : tnl->vb.Size - MAX_CLIPPED_VERTICES;
- GLint max_basevertex = prim->basevertex;
- GLuint i;
-
- /* Mesa core state should have been validated already */
- assert(ctx->NewState == 0x0);
-
- if (!_mesa_check_conditional_render(ctx))
- return; /* don't draw */
-
- for (i = 1; i < nr_prims; i++)
- max_basevertex = MAX2(max_basevertex, prim[i].basevertex);
-
- if (0)
- {
- printf("%s %d..%d\n", __FUNCTION__, min_index, max_index);
- for (i = 0; i < nr_prims; i++)
- printf("prim %d: %s start %d count %d\n", i,
- _mesa_lookup_enum_by_nr(prim[i].mode),
- prim[i].start,
- prim[i].count);
- }
-
- if (min_index) {
- /* We always translate away calls with min_index != 0.
- */
- vbo_rebase_prims( ctx, arrays, prim, nr_prims, ib,
- min_index, max_index,
- _tnl_vbo_draw_prims );
- return;
- }
- else if ((GLint)max_index + max_basevertex > max) {
- /* The software TNL pipeline has a fixed amount of storage for
- * vertices and it is necessary to split incoming drawing commands
- * if they exceed that limit.
- */
- struct split_limits limits;
- limits.max_verts = max;
- limits.max_vb_size = ~0;
- limits.max_indices = ~0;
-
- /* This will split the buffers one way or another and
- * recursively call back into this function.
- */
- vbo_split_prims( ctx, arrays, prim, nr_prims, ib,
- 0, max_index + prim->basevertex,
- _tnl_vbo_draw_prims,
- &limits );
- }
- else {
- /* May need to map a vertex buffer object for every attribute plus
- * one for the index buffer.
- */
- struct gl_buffer_object *bo[VERT_ATTRIB_MAX + 1];
- GLuint nr_bo = 0;
- GLuint inst;
-
- for (i = 0; i < nr_prims;) {
- GLuint this_nr_prims;
-
- /* Our SW TNL pipeline doesn't handle basevertex yet, so bind_indices
- * will rebase the elements to the basevertex, and we'll only
- * emit strings of prims with the same basevertex in one draw call.
- */
- for (this_nr_prims = 1; i + this_nr_prims < nr_prims;
- this_nr_prims++) {
- if (prim[i].basevertex != prim[i + this_nr_prims].basevertex)
- break;
- }
-
- assert(prim[i].num_instances > 0);
-
- /* Binding inputs may imply mapping some vertex buffer objects.
- * They will need to be unmapped below.
- */
- for (inst = 0; inst < prim[i].num_instances; inst++) {
-
- bind_prims(ctx, &prim[i], this_nr_prims);
- bind_inputs(ctx, arrays, max_index + prim[i].basevertex + 1,
- bo, &nr_bo);
- bind_indices(ctx, ib, bo, &nr_bo);
-
- tnl->CurInstance = inst;
- TNL_CONTEXT(ctx)->Driver.RunPipeline(ctx);
-
- unmap_vbos(ctx, bo, nr_bo);
- free_space(ctx);
- }
-
- i += this_nr_prims;
- }
- }
-}
-
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.1
+ *
+ * Copyright (C) 1999-2007 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ */
+
+#include "main/glheader.h"
+#include "main/condrender.h"
+#include "main/context.h"
+#include "main/imports.h"
+#include "main/mtypes.h"
+#include "main/macros.h"
+#include "main/enums.h"
+
+#include "t_context.h"
+#include "tnl.h"
+
+
+
+static GLubyte *get_space(struct gl_context *ctx, GLuint bytes)
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ GLubyte *space = malloc(bytes);
+
+ tnl->block[tnl->nr_blocks++] = space;
+ return space;
+}
+
+
+static void free_space(struct gl_context *ctx)
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ GLuint i;
+ for (i = 0; i < tnl->nr_blocks; i++)
+ free(tnl->block[i]);
+ tnl->nr_blocks = 0;
+}
+
+
+/* Convert the incoming array to GLfloats. Understands the
+ * array->Normalized flag and selects the correct conversion method.
+ */
+#define CONVERT( TYPE, MACRO ) do { \
+ GLuint i, j; \
+ if (input->Normalized) { \
+ for (i = 0; i < count; i++) { \
+ const TYPE *in = (TYPE *)ptr; \
+ for (j = 0; j < sz; j++) { \
+ *fptr++ = MACRO(*in); \
+ in++; \
+ } \
+ ptr += input->StrideB; \
+ } \
+ } else { \
+ for (i = 0; i < count; i++) { \
+ const TYPE *in = (TYPE *)ptr; \
+ for (j = 0; j < sz; j++) { \
+ *fptr++ = (GLfloat)(*in); \
+ in++; \
+ } \
+ ptr += input->StrideB; \
+ } \
+ } \
+} while (0)
+
+
+/**
+ * Convert array of BGRA/GLubyte[4] values to RGBA/float[4]
+ * \param ptr input/ubyte array
+ * \param fptr output/float array
+ */
+static void
+convert_bgra_to_float(const struct gl_client_array *input,
+ const GLubyte *ptr, GLfloat *fptr,
+ GLuint count )
+{
+ GLuint i;
+ assert(input->Normalized);
+ assert(input->Size == 4);
+ for (i = 0; i < count; i++) {
+ const GLubyte *in = (GLubyte *) ptr; /* in is in BGRA order */
+ *fptr++ = UBYTE_TO_FLOAT(in[2]); /* red */
+ *fptr++ = UBYTE_TO_FLOAT(in[1]); /* green */
+ *fptr++ = UBYTE_TO_FLOAT(in[0]); /* blue */
+ *fptr++ = UBYTE_TO_FLOAT(in[3]); /* alpha */
+ ptr += input->StrideB;
+ }
+}
+
+static void
+convert_half_to_float(const struct gl_client_array *input,
+ const GLubyte *ptr, GLfloat *fptr,
+ GLuint count, GLuint sz)
+{
+ GLuint i, j;
+
+ for (i = 0; i < count; i++) {
+ GLhalfARB *in = (GLhalfARB *)ptr;
+
+ for (j = 0; j < sz; j++) {
+ *fptr++ = _mesa_half_to_float(in[j]);
+ }
+ ptr += input->StrideB;
+ }
+}
+
+/**
+ * \brief Convert fixed-point to floating-point.
+ *
+ * In OpenGL, a fixed-point number is a "signed 2's complement 16.16 scaled
+ * integer" (Table 2.2 of the OpenGL ES 2.0 spec).
+ *
+ * If the buffer has the \c normalized flag set, the formula
+ * \code normalize(x) := (2*x + 1) / (2^16 - 1) \endcode
+ * is used to map the fixed-point numbers into the range [-1, 1].
+ */
+static void
+convert_fixed_to_float(const struct gl_client_array *input,
+ const GLubyte *ptr, GLfloat *fptr,
+ GLuint count)
+{
+ GLuint i, j;
+ const GLint size = input->Size;
+
+ if (input->Normalized) {
+ for (i = 0; i < count; ++i) {
+ const GLfixed *in = (GLfixed *) ptr;
+ for (j = 0; j < size; ++j) {
+ *fptr++ = (GLfloat) (2 * in[j] + 1) / (GLfloat) ((1 << 16) - 1);
+ }
+ ptr += input->StrideB;
+ }
+ } else {
+ for (i = 0; i < count; ++i) {
+ const GLfixed *in = (GLfixed *) ptr;
+ for (j = 0; j < size; ++j) {
+ *fptr++ = in[j] / (GLfloat) (1 << 16);
+ }
+ ptr += input->StrideB;
+ }
+ }
+}
+
+/* Adjust pointer to point at first requested element, convert to
+ * floating point, populate VB->AttribPtr[].
+ */
+static void _tnl_import_array( struct gl_context *ctx,
+ GLuint attrib,
+ GLuint count,
+ const struct gl_client_array *input,
+ const GLubyte *ptr )
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ struct vertex_buffer *VB = &tnl->vb;
+ GLuint stride = input->StrideB;
+
+ if (input->Type != GL_FLOAT) {
+ const GLuint sz = input->Size;
+ GLubyte *buf = get_space(ctx, count * sz * sizeof(GLfloat));
+ GLfloat *fptr = (GLfloat *)buf;
+
+ switch (input->Type) {
+ case GL_BYTE:
+ CONVERT(GLbyte, BYTE_TO_FLOAT);
+ break;
+ case GL_UNSIGNED_BYTE:
+ if (input->Format == GL_BGRA) {
+ /* See GL_EXT_vertex_array_bgra */
+ convert_bgra_to_float(input, ptr, fptr, count);
+ }
+ else {
+ CONVERT(GLubyte, UBYTE_TO_FLOAT);
+ }
+ break;
+ case GL_SHORT:
+ CONVERT(GLshort, SHORT_TO_FLOAT);
+ break;
+ case GL_UNSIGNED_SHORT:
+ CONVERT(GLushort, USHORT_TO_FLOAT);
+ break;
+ case GL_INT:
+ CONVERT(GLint, INT_TO_FLOAT);
+ break;
+ case GL_UNSIGNED_INT:
+ CONVERT(GLuint, UINT_TO_FLOAT);
+ break;
+ case GL_DOUBLE:
+ CONVERT(GLdouble, (GLfloat));
+ break;
+ case GL_HALF_FLOAT:
+ convert_half_to_float(input, ptr, fptr, count, sz);
+ break;
+ case GL_FIXED:
+ convert_fixed_to_float(input, ptr, fptr, count);
+ break;
+ default:
+ assert(0);
+ break;
+ }
+
+ ptr = buf;
+ stride = sz * sizeof(GLfloat);
+ }
+
+ VB->AttribPtr[attrib] = &tnl->tmp_inputs[attrib];
+ VB->AttribPtr[attrib]->data = (GLfloat (*)[4])ptr;
+ VB->AttribPtr[attrib]->start = (GLfloat *)ptr;
+ VB->AttribPtr[attrib]->count = count;
+ VB->AttribPtr[attrib]->stride = stride;
+ VB->AttribPtr[attrib]->size = input->Size;
+
+ /* This should die, but so should the whole GLvector4f concept:
+ */
+ VB->AttribPtr[attrib]->flags = (((1<<input->Size)-1) |
+ VEC_NOT_WRITEABLE |
+ (stride == 4*sizeof(GLfloat) ? 0 : VEC_BAD_STRIDE));
+
+ VB->AttribPtr[attrib]->storage = NULL;
+}
+
+#define CLIPVERTS ((6 + MAX_CLIP_PLANES) * 2)
+
+
+static GLboolean *_tnl_import_edgeflag( struct gl_context *ctx,
+ const GLvector4f *input,
+ GLuint count)
+{
+ const GLubyte *ptr = (const GLubyte *)input->data;
+ const GLuint stride = input->stride;
+ GLboolean *space = (GLboolean *)get_space(ctx, count + CLIPVERTS);
+ GLboolean *bptr = space;
+ GLuint i;
+
+ for (i = 0; i < count; i++) {
+ *bptr++ = ((GLfloat *)ptr)[0] == 1.0;
+ ptr += stride;
+ }
+
+ return space;
+}
+
+
+static void bind_inputs( struct gl_context *ctx,
+ const struct gl_client_array *inputs[],
+ GLint count,
+ struct gl_buffer_object **bo,
+ GLuint *nr_bo )
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ struct vertex_buffer *VB = &tnl->vb;
+ GLuint i;
+
+ /* Map all the VBOs
+ */
+ for (i = 0; i < VERT_ATTRIB_MAX; i++) {
+ const void *ptr;
+
+ if (inputs[i]->BufferObj->Name) {
+ if (!inputs[i]->BufferObj->Pointer) {
+ bo[*nr_bo] = inputs[i]->BufferObj;
+ (*nr_bo)++;
+ ctx->Driver.MapBuffer(ctx,
+ GL_ARRAY_BUFFER,
+ GL_READ_ONLY_ARB,
+ inputs[i]->BufferObj);
+
+ assert(inputs[i]->BufferObj->Pointer);
+ }
+
+ ptr = ADD_POINTERS(inputs[i]->BufferObj->Pointer,
+ inputs[i]->Ptr);
+ }
+ else
+ ptr = inputs[i]->Ptr;
+
+ /* Just make sure the array is floating point, otherwise convert to
+ * temporary storage.
+ *
+ * XXX: remove the GLvector4f type at some stage and just use
+ * client arrays.
+ */
+ _tnl_import_array(ctx, i, count, inputs[i], ptr);
+ }
+
+ /* We process only the vertices between min & max index:
+ */
+ VB->Count = count;
+
+ /* These should perhaps be part of _TNL_ATTRIB_* */
+ VB->BackfaceColorPtr = NULL;
+ VB->BackfaceIndexPtr = NULL;
+ VB->BackfaceSecondaryColorPtr = NULL;
+
+ /* Clipping and drawing code still requires this to be a packed
+ * array of ubytes which can be written into. TODO: Fix and
+ * remove.
+ */
+ if (ctx->Polygon.FrontMode != GL_FILL ||
+ ctx->Polygon.BackMode != GL_FILL)
+ {
+ VB->EdgeFlag = _tnl_import_edgeflag( ctx,
+ VB->AttribPtr[_TNL_ATTRIB_EDGEFLAG],
+ VB->Count );
+ }
+ else {
+ /* the data previously pointed to by EdgeFlag may have been freed */
+ VB->EdgeFlag = NULL;
+ }
+}
+
+
+/* Translate indices to GLuints and store in VB->Elts.
+ */
+static void bind_indices( struct gl_context *ctx,
+ const struct _mesa_index_buffer *ib,
+ struct gl_buffer_object **bo,
+ GLuint *nr_bo)
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ struct vertex_buffer *VB = &tnl->vb;
+ GLuint i;
+ void *ptr;
+
+ if (!ib) {
+ VB->Elts = NULL;
+ return;
+ }
+
+ if (ib->obj->Name && !ib->obj->Pointer) {
+ bo[*nr_bo] = ib->obj;
+ (*nr_bo)++;
+ ctx->Driver.MapBuffer(ctx,
+ GL_ELEMENT_ARRAY_BUFFER,
+ GL_READ_ONLY_ARB,
+ ib->obj);
+
+ assert(ib->obj->Pointer);
+ }
+
+ ptr = ADD_POINTERS(ib->obj->Pointer, ib->ptr);
+
+ if (ib->type == GL_UNSIGNED_INT && VB->Primitive[0].basevertex == 0) {
+ VB->Elts = (GLuint *) ptr;
+ }
+ else {
+ GLuint *elts = (GLuint *)get_space(ctx, ib->count * sizeof(GLuint));
+ VB->Elts = elts;
+
+ if (ib->type == GL_UNSIGNED_INT) {
+ const GLuint *in = (GLuint *)ptr;
+ for (i = 0; i < ib->count; i++)
+ *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
+ }
+ else if (ib->type == GL_UNSIGNED_SHORT) {
+ const GLushort *in = (GLushort *)ptr;
+ for (i = 0; i < ib->count; i++)
+ *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
+ }
+ else {
+ const GLubyte *in = (GLubyte *)ptr;
+ for (i = 0; i < ib->count; i++)
+ *elts++ = (GLuint)(*in++) + VB->Primitive[0].basevertex;
+ }
+ }
+}
+
+static void bind_prims( struct gl_context *ctx,
+ const struct _mesa_prim *prim,
+ GLuint nr_prims )
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ struct vertex_buffer *VB = &tnl->vb;
+
+ VB->Primitive = prim;
+ VB->PrimitiveCount = nr_prims;
+}
+
+static void unmap_vbos( struct gl_context *ctx,
+ struct gl_buffer_object **bo,
+ GLuint nr_bo )
+{
+ GLuint i;
+ for (i = 0; i < nr_bo; i++) {
+ ctx->Driver.UnmapBuffer(ctx,
+ 0, /* target -- I don't see why this would be needed */
+ bo[i]);
+ }
+}
+
+
+void _tnl_vbo_draw_prims(struct gl_context *ctx,
+ const struct gl_client_array *arrays[],
+ const struct _mesa_prim *prim,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLboolean index_bounds_valid,
+ GLuint min_index,
+ GLuint max_index)
+{
+ if (!index_bounds_valid)
+ vbo_get_minmax_index(ctx, prim, ib, &min_index, &max_index);
+
+ _tnl_draw_prims(ctx, arrays, prim, nr_prims, ib, min_index, max_index);
+}
+
+/* This is the main entrypoint into the slimmed-down software tnl
+ * module. In a regular swtnl driver, this can be plugged straight
+ * into the vbo->Driver.DrawPrims() callback.
+ */
+void _tnl_draw_prims( struct gl_context *ctx,
+ const struct gl_client_array *arrays[],
+ const struct _mesa_prim *prim,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLuint min_index,
+ GLuint max_index)
+{
+ TNLcontext *tnl = TNL_CONTEXT(ctx);
+ const GLuint TEST_SPLIT = 0;
+ const GLint max = TEST_SPLIT ? 8 : tnl->vb.Size - MAX_CLIPPED_VERTICES;
+ GLint max_basevertex = prim->basevertex;
+ GLuint i;
+
+ /* Mesa core state should have been validated already */
+ assert(ctx->NewState == 0x0);
+
+ if (!_mesa_check_conditional_render(ctx))
+ return; /* don't draw */
+
+ for (i = 1; i < nr_prims; i++)
+ max_basevertex = MAX2(max_basevertex, prim[i].basevertex);
+
+ if (0)
+ {
+ printf("%s %d..%d\n", __FUNCTION__, min_index, max_index);
+ for (i = 0; i < nr_prims; i++)
+ printf("prim %d: %s start %d count %d\n", i,
+ _mesa_lookup_enum_by_nr(prim[i].mode),
+ prim[i].start,
+ prim[i].count);
+ }
+
+ if (min_index) {
+ /* We always translate away calls with min_index != 0.
+ */
+ vbo_rebase_prims( ctx, arrays, prim, nr_prims, ib,
+ min_index, max_index,
+ _tnl_vbo_draw_prims );
+ return;
+ }
+ else if ((GLint)max_index + max_basevertex > max) {
+ /* The software TNL pipeline has a fixed amount of storage for
+ * vertices and it is necessary to split incoming drawing commands
+ * if they exceed that limit.
+ */
+ struct split_limits limits;
+ limits.max_verts = max;
+ limits.max_vb_size = ~0;
+ limits.max_indices = ~0;
+
+ /* This will split the buffers one way or another and
+ * recursively call back into this function.
+ */
+ vbo_split_prims( ctx, arrays, prim, nr_prims, ib,
+ 0, max_index + prim->basevertex,
+ _tnl_vbo_draw_prims,
+ &limits );
+ }
+ else {
+ /* May need to map a vertex buffer object for every attribute plus
+ * one for the index buffer.
+ */
+ struct gl_buffer_object *bo[VERT_ATTRIB_MAX + 1];
+ GLuint nr_bo = 0;
+ GLuint inst;
+
+ for (i = 0; i < nr_prims;) {
+ GLuint this_nr_prims;
+
+ /* Our SW TNL pipeline doesn't handle basevertex yet, so bind_indices
+ * will rebase the elements to the basevertex, and we'll only
+ * emit strings of prims with the same basevertex in one draw call.
+ */
+ for (this_nr_prims = 1; i + this_nr_prims < nr_prims;
+ this_nr_prims++) {
+ if (prim[i].basevertex != prim[i + this_nr_prims].basevertex)
+ break;
+ }
+
+ assert(prim[i].num_instances > 0);
+
+ /* Binding inputs may imply mapping some vertex buffer objects.
+ * They will need to be unmapped below.
+ */
+ for (inst = 0; inst < prim[i].num_instances; inst++) {
+
+ bind_prims(ctx, &prim[i], this_nr_prims);
+ bind_inputs(ctx, arrays, max_index + prim[i].basevertex + 1,
+ bo, &nr_bo);
+ bind_indices(ctx, ib, bo, &nr_bo);
+
+ tnl->CurInstance = inst;
+ TNL_CONTEXT(ctx)->Driver.RunPipeline(ctx);
+
+ unmap_vbos(ctx, bo, nr_bo);
+ free_space(ctx);
+ }
+
+ i += this_nr_prims;
+ }
+ }
+}
+
diff --git a/mesalib/src/mesa/vbo/vbo.h b/mesalib/src/mesa/vbo/vbo.h
index 6834f3b5a..b94d58f3d 100644
--- a/mesalib/src/mesa/vbo/vbo.h
+++ b/mesalib/src/mesa/vbo/vbo.h
@@ -1,175 +1,175 @@
-/*
- * mesa 3-D graphics library
- * Version: 6.5
- *
- * Copyright (C) 1999-2006 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 vbo_context.h
- * \brief VBO builder module datatypes and definitions.
- * \author Keith Whitwell
- */
-
-
-#ifndef _VBO_H
-#define _VBO_H
-
-#include "main/glheader.h"
-
-struct gl_client_array;
-struct gl_context;
-
-struct _mesa_prim {
- GLuint mode:8; /**< GL_POINTS, GL_LINES, GL_QUAD_STRIP, etc */
- GLuint indexed:1;
- GLuint begin:1;
- GLuint end:1;
- GLuint weak:1;
- GLuint no_current_update:1;
- GLuint pad:19;
-
- GLuint start;
- GLuint count;
- GLint basevertex;
- GLsizei num_instances;
-};
-
-/* Would like to call this a "vbo_index_buffer", but this would be
- * confusing as the indices are not neccessarily yet in a non-null
- * buffer object.
- */
-struct _mesa_index_buffer {
- GLuint count;
- GLenum type;
- struct gl_buffer_object *obj;
- const void *ptr;
-};
-
-
-
-GLboolean _vbo_CreateContext( struct gl_context *ctx );
-void _vbo_DestroyContext( struct gl_context *ctx );
-void _vbo_InvalidateState( struct gl_context *ctx, GLuint new_state );
-
-
-typedef void (*vbo_draw_func)( struct gl_context *ctx,
- const struct gl_client_array **arrays,
- const struct _mesa_prim *prims,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLboolean index_bounds_valid,
- GLuint min_index,
- GLuint max_index );
-
-
-
-
-/* Utility function to cope with various constraints on tnl modules or
- * hardware. This can be used to split an incoming set of arrays and
- * primitives against the following constraints:
- * - Maximum number of indices in index buffer.
- * - Maximum number of vertices referenced by index buffer.
- * - Maximum hardware vertex buffer size.
- */
-struct split_limits {
- GLuint max_verts;
- GLuint max_indices;
- GLuint max_vb_size; /* bytes */
-};
-
-
-void vbo_split_prims( struct gl_context *ctx,
- const struct gl_client_array *arrays[],
- const struct _mesa_prim *prim,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLuint min_index,
- GLuint max_index,
- vbo_draw_func draw,
- const struct split_limits *limits );
-
-
-/* Helpers for dealing translating away non-zero min_index.
- */
-GLboolean vbo_all_varyings_in_vbos( const struct gl_client_array *arrays[] );
-GLboolean vbo_any_varyings_in_vbos( const struct gl_client_array *arrays[] );
-
-void vbo_rebase_prims( struct gl_context *ctx,
- const struct gl_client_array *arrays[],
- const struct _mesa_prim *prim,
- GLuint nr_prims,
- const struct _mesa_index_buffer *ib,
- GLuint min_index,
- GLuint max_index,
- vbo_draw_func draw );
-void
-vbo_get_minmax_index(struct gl_context *ctx, const struct _mesa_prim *prim,
- const struct _mesa_index_buffer *ib,
- GLuint *min_index, GLuint *max_index);
-
-void vbo_use_buffer_objects(struct gl_context *ctx);
-
-
-void vbo_set_draw_func(struct gl_context *ctx, vbo_draw_func func);
-
-void vbo_check_buffers_are_unmapped(struct gl_context *ctx);
-
-
-void GLAPIENTRY
-_es_Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
-
-void GLAPIENTRY
-_es_Normal3f(GLfloat x, GLfloat y, GLfloat z);
-
-void GLAPIENTRY
-_es_MultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
-
-void GLAPIENTRY
-_es_Materialfv(GLenum face, GLenum pname, const GLfloat *params);
-
-void GLAPIENTRY
-_es_Materialf(GLenum face, GLenum pname, GLfloat param);
-
-void GLAPIENTRY
-_es_VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
-
-void GLAPIENTRY
-_es_VertexAttrib1f(GLuint indx, GLfloat x);
-
-void GLAPIENTRY
-_es_VertexAttrib1fv(GLuint indx, const GLfloat* values);
-
-void GLAPIENTRY
-_es_VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
-
-void GLAPIENTRY
-_es_VertexAttrib2fv(GLuint indx, const GLfloat* values);
-
-void GLAPIENTRY
-_es_VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
-
-void GLAPIENTRY
-_es_VertexAttrib3fv(GLuint indx, const GLfloat* values);
-
-void GLAPIENTRY
-_es_VertexAttrib4fv(GLuint indx, const GLfloat* values);
-
-#endif
+/*
+ * mesa 3-D graphics library
+ * Version: 6.5
+ *
+ * Copyright (C) 1999-2006 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 vbo_context.h
+ * \brief VBO builder module datatypes and definitions.
+ * \author Keith Whitwell
+ */
+
+
+#ifndef _VBO_H
+#define _VBO_H
+
+#include "main/glheader.h"
+
+struct gl_client_array;
+struct gl_context;
+
+struct _mesa_prim {
+ GLuint mode:8; /**< GL_POINTS, GL_LINES, GL_QUAD_STRIP, etc */
+ GLuint indexed:1;
+ GLuint begin:1;
+ GLuint end:1;
+ GLuint weak:1;
+ GLuint no_current_update:1;
+ GLuint pad:19;
+
+ GLuint start;
+ GLuint count;
+ GLint basevertex;
+ GLsizei num_instances;
+};
+
+/* Would like to call this a "vbo_index_buffer", but this would be
+ * confusing as the indices are not neccessarily yet in a non-null
+ * buffer object.
+ */
+struct _mesa_index_buffer {
+ GLuint count;
+ GLenum type;
+ struct gl_buffer_object *obj;
+ const void *ptr;
+};
+
+
+
+GLboolean _vbo_CreateContext( struct gl_context *ctx );
+void _vbo_DestroyContext( struct gl_context *ctx );
+void _vbo_InvalidateState( struct gl_context *ctx, GLuint new_state );
+
+
+typedef void (*vbo_draw_func)( struct gl_context *ctx,
+ const struct gl_client_array **arrays,
+ const struct _mesa_prim *prims,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLboolean index_bounds_valid,
+ GLuint min_index,
+ GLuint max_index );
+
+
+
+
+/* Utility function to cope with various constraints on tnl modules or
+ * hardware. This can be used to split an incoming set of arrays and
+ * primitives against the following constraints:
+ * - Maximum number of indices in index buffer.
+ * - Maximum number of vertices referenced by index buffer.
+ * - Maximum hardware vertex buffer size.
+ */
+struct split_limits {
+ GLuint max_verts;
+ GLuint max_indices;
+ GLuint max_vb_size; /* bytes */
+};
+
+
+void vbo_split_prims( struct gl_context *ctx,
+ const struct gl_client_array *arrays[],
+ const struct _mesa_prim *prim,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLuint min_index,
+ GLuint max_index,
+ vbo_draw_func draw,
+ const struct split_limits *limits );
+
+
+/* Helpers for dealing translating away non-zero min_index.
+ */
+GLboolean vbo_all_varyings_in_vbos( const struct gl_client_array *arrays[] );
+GLboolean vbo_any_varyings_in_vbos( const struct gl_client_array *arrays[] );
+
+void vbo_rebase_prims( struct gl_context *ctx,
+ const struct gl_client_array *arrays[],
+ const struct _mesa_prim *prim,
+ GLuint nr_prims,
+ const struct _mesa_index_buffer *ib,
+ GLuint min_index,
+ GLuint max_index,
+ vbo_draw_func draw );
+void
+vbo_get_minmax_index(struct gl_context *ctx, const struct _mesa_prim *prim,
+ const struct _mesa_index_buffer *ib,
+ GLuint *min_index, GLuint *max_index);
+
+void vbo_use_buffer_objects(struct gl_context *ctx);
+
+
+void vbo_set_draw_func(struct gl_context *ctx, vbo_draw_func func);
+
+void vbo_check_buffers_are_unmapped(struct gl_context *ctx);
+
+
+void GLAPIENTRY
+_es_Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a);
+
+void GLAPIENTRY
+_es_Normal3f(GLfloat x, GLfloat y, GLfloat z);
+
+void GLAPIENTRY
+_es_MultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q);
+
+void GLAPIENTRY
+_es_Materialfv(GLenum face, GLenum pname, const GLfloat *params);
+
+void GLAPIENTRY
+_es_Materialf(GLenum face, GLenum pname, GLfloat param);
+
+void GLAPIENTRY
+_es_VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w);
+
+void GLAPIENTRY
+_es_VertexAttrib1f(GLuint indx, GLfloat x);
+
+void GLAPIENTRY
+_es_VertexAttrib1fv(GLuint indx, const GLfloat* values);
+
+void GLAPIENTRY
+_es_VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y);
+
+void GLAPIENTRY
+_es_VertexAttrib2fv(GLuint indx, const GLfloat* values);
+
+void GLAPIENTRY
+_es_VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z);
+
+void GLAPIENTRY
+_es_VertexAttrib3fv(GLuint indx, const GLfloat* values);
+
+void GLAPIENTRY
+_es_VertexAttrib4fv(GLuint indx, const GLfloat* values);
+
+#endif
diff --git a/mesalib/src/mesa/vbo/vbo_exec.h b/mesalib/src/mesa/vbo/vbo_exec.h
index 1b0ed7947..2531f20f5 100644
--- a/mesalib/src/mesa/vbo/vbo_exec.h
+++ b/mesalib/src/mesa/vbo/vbo_exec.h
@@ -1,201 +1,201 @@
-/**************************************************************************
-
-Copyright 2002 Tungsten Graphics Inc., Cedar Park, Texas.
-
-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
-on the rights to use, copy, modify, merge, publish, distribute, sub
-license, 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 (including the next
-paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL
-TUNGSTEN GRAPHICS AND/OR THEIR SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- *
- */
-
-#ifndef __VBO_EXEC_H__
-#define __VBO_EXEC_H__
-
-#include "main/mfeatures.h"
-#include "main/mtypes.h"
-#include "vbo.h"
-#include "vbo_attrib.h"
-
-
-/**
- * Max number of primitives (number of glBegin/End pairs) per VBO.
- */
-#define VBO_MAX_PRIM 64
-
-
-/**
- * Size of the VBO to use for glBegin/glVertex/glEnd-style rendering.
- */
-#define VBO_VERT_BUFFER_SIZE (1024*64) /* bytes */
-
-
-/** Current vertex program mode */
-enum vp_mode {
- VP_NONE, /**< fixed function */
- VP_NV, /**< NV vertex program */
- VP_ARB /**< ARB vertex program or GLSL vertex shader */
-};
-
-
-struct vbo_exec_eval1_map {
- struct gl_1d_map *map;
- GLuint sz;
-};
-
-struct vbo_exec_eval2_map {
- struct gl_2d_map *map;
- GLuint sz;
-};
-
-
-
-struct vbo_exec_copied_vtx {
- GLfloat buffer[VBO_ATTRIB_MAX * 4 * VBO_MAX_COPIED_VERTS];
- GLuint nr;
-};
-
-
-typedef void (*vbo_attrfv_func)( const GLfloat * );
-
-
-struct vbo_exec_context
-{
- struct gl_context *ctx;
- GLvertexformat vtxfmt;
-
- struct {
- struct gl_buffer_object *bufferobj;
-
- GLuint vertex_size; /* in dwords */
-
- struct _mesa_prim prim[VBO_MAX_PRIM];
- GLuint prim_count;
-
- GLfloat *buffer_map;
- GLfloat *buffer_ptr; /* cursor, points into buffer */
- GLuint buffer_used; /* in bytes */
- GLfloat vertex[VBO_ATTRIB_MAX*4]; /* current vertex */
-
- GLuint vert_count;
- GLuint max_vert;
- struct vbo_exec_copied_vtx copied;
-
- GLubyte attrsz[VBO_ATTRIB_MAX];
- GLubyte active_sz[VBO_ATTRIB_MAX];
-
- GLfloat *attrptr[VBO_ATTRIB_MAX];
- struct gl_client_array arrays[VERT_ATTRIB_MAX];
-
- /* According to program mode, the values above plus current
- * values are squashed down to the 32 attributes passed to the
- * vertex program below:
- */
- enum vp_mode program_mode;
- GLuint enabled_flags;
- const struct gl_client_array *inputs[VERT_ATTRIB_MAX];
- } vtx;
-
-
- struct {
- GLboolean recalculate_maps;
- struct vbo_exec_eval1_map map1[VERT_ATTRIB_MAX];
- struct vbo_exec_eval2_map map2[VERT_ATTRIB_MAX];
- } eval;
-
- struct {
- enum vp_mode program_mode;
- GLuint enabled_flags;
- GLuint array_obj;
-
- /* These just mirror the current arrayobj (todo: make arrayobj
- * look like this and remove the mirror):
- */
- const struct gl_client_array *legacy_array[16];
- const struct gl_client_array *generic_array[16];
-
- /* Arrays and current values manipulated according to program
- * mode, etc. These are the attributes as seen by vertex
- * programs:
- */
- const struct gl_client_array *inputs[VERT_ATTRIB_MAX];
- } array;
-
-#ifdef DEBUG
- GLint flush_call_depth;
-#endif
-};
-
-
-
-/* External API:
- */
-void vbo_exec_init( struct gl_context *ctx );
-void vbo_exec_destroy( struct gl_context *ctx );
-void vbo_exec_invalidate_state( struct gl_context *ctx, GLuint new_state );
-
-void vbo_exec_BeginVertices( struct gl_context *ctx );
-void vbo_exec_FlushVertices( struct gl_context *ctx, GLuint flags );
-
-
-/* Internal functions:
- */
-void vbo_exec_array_init( struct vbo_exec_context *exec );
-void vbo_exec_array_destroy( struct vbo_exec_context *exec );
-
-
-void vbo_exec_vtx_init( struct vbo_exec_context *exec );
-void vbo_exec_vtx_destroy( struct vbo_exec_context *exec );
-
-#if FEATURE_beginend
-
-void vbo_exec_vtx_flush( struct vbo_exec_context *exec, GLboolean unmap );
-void vbo_exec_vtx_map( struct vbo_exec_context *exec );
-
-#else /* FEATURE_beginend */
-
-static INLINE void
-vbo_exec_vtx_flush( struct vbo_exec_context *exec, GLboolean unmap )
-{
-}
-
-static INLINE void
-vbo_exec_vtx_map( struct vbo_exec_context *exec )
-{
-}
-
-#endif /* FEATURE_beginend */
-
-void vbo_exec_vtx_wrap( struct vbo_exec_context *exec );
-
-void vbo_exec_eval_update( struct vbo_exec_context *exec );
-
-void vbo_exec_do_EvalCoord2f( struct vbo_exec_context *exec,
- GLfloat u, GLfloat v );
-
-void vbo_exec_do_EvalCoord1f( struct vbo_exec_context *exec,
- GLfloat u);
-
-#endif
+/**************************************************************************
+
+Copyright 2002 Tungsten Graphics Inc., Cedar Park, Texas.
+
+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
+on the rights to use, copy, modify, merge, publish, distribute, sub
+license, 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 (including the next
+paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL
+TUNGSTEN GRAPHICS AND/OR THEIR SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ *
+ */
+
+#ifndef __VBO_EXEC_H__
+#define __VBO_EXEC_H__
+
+#include "main/mfeatures.h"
+#include "main/mtypes.h"
+#include "vbo.h"
+#include "vbo_attrib.h"
+
+
+/**
+ * Max number of primitives (number of glBegin/End pairs) per VBO.
+ */
+#define VBO_MAX_PRIM 64
+
+
+/**
+ * Size of the VBO to use for glBegin/glVertex/glEnd-style rendering.
+ */
+#define VBO_VERT_BUFFER_SIZE (1024*64) /* bytes */
+
+
+/** Current vertex program mode */
+enum vp_mode {
+ VP_NONE, /**< fixed function */
+ VP_NV, /**< NV vertex program */
+ VP_ARB /**< ARB vertex program or GLSL vertex shader */
+};
+
+
+struct vbo_exec_eval1_map {
+ struct gl_1d_map *map;
+ GLuint sz;
+};
+
+struct vbo_exec_eval2_map {
+ struct gl_2d_map *map;
+ GLuint sz;
+};
+
+
+
+struct vbo_exec_copied_vtx {
+ GLfloat buffer[VBO_ATTRIB_MAX * 4 * VBO_MAX_COPIED_VERTS];
+ GLuint nr;
+};
+
+
+typedef void (*vbo_attrfv_func)( const GLfloat * );
+
+
+struct vbo_exec_context
+{
+ struct gl_context *ctx;
+ GLvertexformat vtxfmt;
+
+ struct {
+ struct gl_buffer_object *bufferobj;
+
+ GLuint vertex_size; /* in dwords */
+
+ struct _mesa_prim prim[VBO_MAX_PRIM];
+ GLuint prim_count;
+
+ GLfloat *buffer_map;
+ GLfloat *buffer_ptr; /* cursor, points into buffer */
+ GLuint buffer_used; /* in bytes */
+ GLfloat vertex[VBO_ATTRIB_MAX*4]; /* current vertex */
+
+ GLuint vert_count;
+ GLuint max_vert;
+ struct vbo_exec_copied_vtx copied;
+
+ GLubyte attrsz[VBO_ATTRIB_MAX];
+ GLubyte active_sz[VBO_ATTRIB_MAX];
+
+ GLfloat *attrptr[VBO_ATTRIB_MAX];
+ struct gl_client_array arrays[VERT_ATTRIB_MAX];
+
+ /* According to program mode, the values above plus current
+ * values are squashed down to the 32 attributes passed to the
+ * vertex program below:
+ */
+ enum vp_mode program_mode;
+ GLuint enabled_flags;
+ const struct gl_client_array *inputs[VERT_ATTRIB_MAX];
+ } vtx;
+
+
+ struct {
+ GLboolean recalculate_maps;
+ struct vbo_exec_eval1_map map1[VERT_ATTRIB_MAX];
+ struct vbo_exec_eval2_map map2[VERT_ATTRIB_MAX];
+ } eval;
+
+ struct {
+ enum vp_mode program_mode;
+ GLuint enabled_flags;
+ GLuint array_obj;
+
+ /* These just mirror the current arrayobj (todo: make arrayobj
+ * look like this and remove the mirror):
+ */
+ const struct gl_client_array *legacy_array[16];
+ const struct gl_client_array *generic_array[16];
+
+ /* Arrays and current values manipulated according to program
+ * mode, etc. These are the attributes as seen by vertex
+ * programs:
+ */
+ const struct gl_client_array *inputs[VERT_ATTRIB_MAX];
+ } array;
+
+#ifdef DEBUG
+ GLint flush_call_depth;
+#endif
+};
+
+
+
+/* External API:
+ */
+void vbo_exec_init( struct gl_context *ctx );
+void vbo_exec_destroy( struct gl_context *ctx );
+void vbo_exec_invalidate_state( struct gl_context *ctx, GLuint new_state );
+
+void vbo_exec_BeginVertices( struct gl_context *ctx );
+void vbo_exec_FlushVertices( struct gl_context *ctx, GLuint flags );
+
+
+/* Internal functions:
+ */
+void vbo_exec_array_init( struct vbo_exec_context *exec );
+void vbo_exec_array_destroy( struct vbo_exec_context *exec );
+
+
+void vbo_exec_vtx_init( struct vbo_exec_context *exec );
+void vbo_exec_vtx_destroy( struct vbo_exec_context *exec );
+
+#if FEATURE_beginend
+
+void vbo_exec_vtx_flush( struct vbo_exec_context *exec, GLboolean unmap );
+void vbo_exec_vtx_map( struct vbo_exec_context *exec );
+
+#else /* FEATURE_beginend */
+
+static INLINE void
+vbo_exec_vtx_flush( struct vbo_exec_context *exec, GLboolean unmap )
+{
+}
+
+static INLINE void
+vbo_exec_vtx_map( struct vbo_exec_context *exec )
+{
+}
+
+#endif /* FEATURE_beginend */
+
+void vbo_exec_vtx_wrap( struct vbo_exec_context *exec );
+
+void vbo_exec_eval_update( struct vbo_exec_context *exec );
+
+void vbo_exec_do_EvalCoord2f( struct vbo_exec_context *exec,
+ GLfloat u, GLfloat v );
+
+void vbo_exec_do_EvalCoord1f( struct vbo_exec_context *exec,
+ GLfloat u);
+
+#endif
diff --git a/mesalib/src/mesa/vbo/vbo_exec_api.c b/mesalib/src/mesa/vbo/vbo_exec_api.c
index 2f9f3ec7c..bb366b272 100644
--- a/mesalib/src/mesa/vbo/vbo_exec_api.c
+++ b/mesalib/src/mesa/vbo/vbo_exec_api.c
@@ -1,1104 +1,1104 @@
-/**************************************************************************
-
-Copyright 2002-2008 Tungsten Graphics Inc., Cedar Park, Texas.
-
-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
-on the rights to use, copy, modify, merge, publish, distribute, sub
-license, 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 (including the next
-paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL
-TUNGSTEN GRAPHICS AND/OR THEIR SUPPLIERS 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- */
-
-#include "main/glheader.h"
-#include "main/bufferobj.h"
-#include "main/context.h"
-#include "main/macros.h"
-#include "main/mfeatures.h"
-#include "main/vtxfmt.h"
-#include "main/dlist.h"
-#include "main/eval.h"
-#include "main/state.h"
-#include "main/light.h"
-#include "main/api_arrayelt.h"
-#include "main/api_noop.h"
-#include "main/dispatch.h"
-
-#include "vbo_context.h"
-
-#ifdef ERROR
-#undef ERROR
-#endif
-
-
-/** ID/name for immediate-mode VBO */
-#define IMM_BUFFER_NAME 0xaabbccdd
-
-
-static void reset_attrfv( struct vbo_exec_context *exec );
-
-
-/**
- * Close off the last primitive, execute the buffer, restart the
- * primitive.
- */
-static void vbo_exec_wrap_buffers( struct vbo_exec_context *exec )
-{
- if (exec->vtx.prim_count == 0) {
- exec->vtx.copied.nr = 0;
- exec->vtx.vert_count = 0;
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
- }
- else {
- GLuint last_begin = exec->vtx.prim[exec->vtx.prim_count-1].begin;
- GLuint last_count;
-
- if (exec->ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
- GLint i = exec->vtx.prim_count - 1;
- assert(i >= 0);
- exec->vtx.prim[i].count = (exec->vtx.vert_count -
- exec->vtx.prim[i].start);
- }
-
- last_count = exec->vtx.prim[exec->vtx.prim_count-1].count;
-
- /* Execute the buffer and save copied vertices.
- */
- if (exec->vtx.vert_count)
- vbo_exec_vtx_flush( exec, GL_FALSE );
- else {
- exec->vtx.prim_count = 0;
- exec->vtx.copied.nr = 0;
- }
-
- /* Emit a glBegin to start the new list.
- */
- assert(exec->vtx.prim_count == 0);
-
- if (exec->ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
- exec->vtx.prim[0].mode = exec->ctx->Driver.CurrentExecPrimitive;
- exec->vtx.prim[0].start = 0;
- exec->vtx.prim[0].count = 0;
- exec->vtx.prim_count++;
-
- if (exec->vtx.copied.nr == last_count)
- exec->vtx.prim[0].begin = last_begin;
- }
- }
-}
-
-
-/**
- * Deal with buffer wrapping where provoked by the vertex buffer
- * filling up, as opposed to upgrade_vertex().
- */
-void vbo_exec_vtx_wrap( struct vbo_exec_context *exec )
-{
- GLfloat *data = exec->vtx.copied.buffer;
- GLuint i;
-
- /* Run pipeline on current vertices, copy wrapped vertices
- * to exec->vtx.copied.
- */
- vbo_exec_wrap_buffers( exec );
-
- /* Copy stored stored vertices to start of new list.
- */
- assert(exec->vtx.max_vert - exec->vtx.vert_count > exec->vtx.copied.nr);
-
- for (i = 0 ; i < exec->vtx.copied.nr ; i++) {
- memcpy( exec->vtx.buffer_ptr, data,
- exec->vtx.vertex_size * sizeof(GLfloat));
- exec->vtx.buffer_ptr += exec->vtx.vertex_size;
- data += exec->vtx.vertex_size;
- exec->vtx.vert_count++;
- }
-
- exec->vtx.copied.nr = 0;
-}
-
-
-/**
- * Copy the active vertex's values to the ctx->Current fields.
- */
-static void vbo_exec_copy_to_current( struct vbo_exec_context *exec )
-{
- struct gl_context *ctx = exec->ctx;
- struct vbo_context *vbo = vbo_context(ctx);
- GLuint i;
-
- for (i = VBO_ATTRIB_POS+1 ; i < VBO_ATTRIB_MAX ; i++) {
- if (exec->vtx.attrsz[i]) {
- /* Note: the exec->vtx.current[i] pointers point into the
- * ctx->Current.Attrib and ctx->Light.Material.Attrib arrays.
- */
- GLfloat *current = (GLfloat *)vbo->currval[i].Ptr;
- GLfloat tmp[4];
-
- COPY_CLEAN_4V(tmp,
- exec->vtx.attrsz[i],
- exec->vtx.attrptr[i]);
-
- if (memcmp(current, tmp, sizeof(tmp)) != 0) {
- memcpy(current, tmp, sizeof(tmp));
-
- /* Given that we explicitly state size here, there is no need
- * for the COPY_CLEAN above, could just copy 16 bytes and be
- * done. The only problem is when Mesa accesses ctx->Current
- * directly.
- */
- vbo->currval[i].Size = exec->vtx.attrsz[i];
-
- /* This triggers rather too much recalculation of Mesa state
- * that doesn't get used (eg light positions).
- */
- if (i >= VBO_ATTRIB_MAT_FRONT_AMBIENT &&
- i <= VBO_ATTRIB_MAT_BACK_INDEXES)
- ctx->NewState |= _NEW_LIGHT;
-
- ctx->NewState |= _NEW_CURRENT_ATTRIB;
- }
- }
- }
-
- /* Colormaterial -- this kindof sucks.
- */
- if (ctx->Light.ColorMaterialEnabled &&
- exec->vtx.attrsz[VBO_ATTRIB_COLOR0]) {
- _mesa_update_color_material(ctx,
- ctx->Current.Attrib[VBO_ATTRIB_COLOR0]);
- }
-}
-
-
-/**
- * Copy current vertex attribute values into the current vertex.
- */
-static void
-vbo_exec_copy_from_current(struct vbo_exec_context *exec)
-{
- struct gl_context *ctx = exec->ctx;
- struct vbo_context *vbo = vbo_context(ctx);
- GLint i;
-
- for (i = VBO_ATTRIB_POS + 1; i < VBO_ATTRIB_MAX; i++) {
- const GLfloat *current = (GLfloat *) vbo->currval[i].Ptr;
- switch (exec->vtx.attrsz[i]) {
- case 4: exec->vtx.attrptr[i][3] = current[3];
- case 3: exec->vtx.attrptr[i][2] = current[2];
- case 2: exec->vtx.attrptr[i][1] = current[1];
- case 1: exec->vtx.attrptr[i][0] = current[0];
- break;
- }
- }
-}
-
-
-/**
- * Flush existing data, set new attrib size, replay copied vertices.
- * This is called when we transition from a small vertex attribute size
- * to a larger one. Ex: glTexCoord2f -> glTexCoord4f.
- * We need to go back over the previous 2-component texcoords and insert
- * zero and one values.
- */
-static void
-vbo_exec_wrap_upgrade_vertex(struct vbo_exec_context *exec,
- GLuint attr, GLuint newSize )
-{
- struct gl_context *ctx = exec->ctx;
- struct vbo_context *vbo = vbo_context(ctx);
- const GLint lastcount = exec->vtx.vert_count;
- GLfloat *old_attrptr[VBO_ATTRIB_MAX];
- const GLuint old_vtx_size = exec->vtx.vertex_size; /* floats per vertex */
- const GLuint oldSize = exec->vtx.attrsz[attr];
- GLuint i;
-
- /* Run pipeline on current vertices, copy wrapped vertices
- * to exec->vtx.copied.
- */
- vbo_exec_wrap_buffers( exec );
-
- if (unlikely(exec->vtx.copied.nr)) {
- /* We're in the middle of a primitive, keep the old vertex
- * format around to be able to translate the copied vertices to
- * the new format.
- */
- memcpy(old_attrptr, exec->vtx.attrptr, sizeof(old_attrptr));
- }
-
- if (unlikely(oldSize)) {
- /* Do a COPY_TO_CURRENT to ensure back-copying works for the
- * case when the attribute already exists in the vertex and is
- * having its size increased.
- */
- vbo_exec_copy_to_current( exec );
- }
-
- /* Heuristic: Attempt to isolate attributes received outside
- * begin/end so that they don't bloat the vertices.
- */
- if (ctx->Driver.CurrentExecPrimitive == PRIM_OUTSIDE_BEGIN_END &&
- !oldSize && lastcount > 8 && exec->vtx.vertex_size) {
- vbo_exec_copy_to_current( exec );
- reset_attrfv( exec );
- }
-
- /* Fix up sizes:
- */
- exec->vtx.attrsz[attr] = newSize;
- exec->vtx.vertex_size += newSize - oldSize;
- exec->vtx.max_vert = ((VBO_VERT_BUFFER_SIZE - exec->vtx.buffer_used) /
- (exec->vtx.vertex_size * sizeof(GLfloat)));
- exec->vtx.vert_count = 0;
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
-
- if (unlikely(oldSize)) {
- /* Size changed, recalculate all the attrptr[] values
- */
- GLfloat *tmp = exec->vtx.vertex;
-
- for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
- if (exec->vtx.attrsz[i]) {
- exec->vtx.attrptr[i] = tmp;
- tmp += exec->vtx.attrsz[i];
- }
- else
- exec->vtx.attrptr[i] = NULL; /* will not be dereferenced */
- }
-
- /* Copy from current to repopulate the vertex with correct
- * values.
- */
- vbo_exec_copy_from_current( exec );
- }
- else {
- /* Just have to append the new attribute at the end */
- exec->vtx.attrptr[attr] = exec->vtx.vertex +
- exec->vtx.vertex_size - newSize;
- }
-
- /* Replay stored vertices to translate them
- * to new format here.
- *
- * -- No need to replay - just copy piecewise
- */
- if (unlikely(exec->vtx.copied.nr)) {
- GLfloat *data = exec->vtx.copied.buffer;
- GLfloat *dest = exec->vtx.buffer_ptr;
- GLuint j;
-
- assert(exec->vtx.buffer_ptr == exec->vtx.buffer_map);
-
- for (i = 0 ; i < exec->vtx.copied.nr ; i++) {
- for (j = 0 ; j < VBO_ATTRIB_MAX ; j++) {
- GLuint sz = exec->vtx.attrsz[j];
-
- if (sz) {
- GLint old_offset = old_attrptr[j] - exec->vtx.vertex;
- GLint new_offset = exec->vtx.attrptr[j] - exec->vtx.vertex;
-
- if (j == attr) {
- if (oldSize) {
- GLfloat tmp[4];
- COPY_CLEAN_4V(tmp, oldSize, data + old_offset);
- COPY_SZ_4V(dest + new_offset, newSize, tmp);
- } else {
- GLfloat *current = (GLfloat *)vbo->currval[j].Ptr;
- COPY_SZ_4V(dest + new_offset, sz, current);
- }
- }
- else {
- COPY_SZ_4V(dest + new_offset, sz, data + old_offset);
- }
- }
- }
-
- data += old_vtx_size;
- dest += exec->vtx.vertex_size;
- }
-
- exec->vtx.buffer_ptr = dest;
- exec->vtx.vert_count += exec->vtx.copied.nr;
- exec->vtx.copied.nr = 0;
- }
-}
-
-
-/**
- * This is when a vertex attribute transitions to a different size.
- * For example, we saw a bunch of glTexCoord2f() calls and now we got a
- * glTexCoord4f() call. We promote the array from size=2 to size=4.
- */
-static void
-vbo_exec_fixup_vertex(struct gl_context *ctx, GLuint attr, GLuint newSize)
-{
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
-
- if (newSize > exec->vtx.attrsz[attr]) {
- /* New size is larger. Need to flush existing vertices and get
- * an enlarged vertex format.
- */
- vbo_exec_wrap_upgrade_vertex( exec, attr, newSize );
- }
- else if (newSize < exec->vtx.active_sz[attr]) {
- static const GLfloat id[4] = { 0, 0, 0, 1 };
- GLuint i;
-
- /* New size is smaller - just need to fill in some
- * zeros. Don't need to flush or wrap.
- */
- for (i = newSize; i <= exec->vtx.attrsz[attr]; i++)
- exec->vtx.attrptr[attr][i-1] = id[i-1];
- }
-
- exec->vtx.active_sz[attr] = newSize;
-
- /* Does setting NeedFlush belong here? Necessitates resetting
- * vtxfmt on each flush (otherwise flags won't get reset
- * afterwards).
- */
- if (attr == 0)
- ctx->Driver.NeedFlush |= FLUSH_STORED_VERTICES;
-}
-
-
-/**
- * This macro is used to implement all the glVertex, glColor, glTexCoord,
- * glVertexAttrib, etc functions.
- */
-#define ATTR( A, N, V0, V1, V2, V3 ) \
-do { \
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec; \
- \
- if (unlikely(!(ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT))) \
- ctx->Driver.BeginVertices( ctx ); \
- \
- if (unlikely(exec->vtx.active_sz[A] != N)) \
- vbo_exec_fixup_vertex(ctx, A, N); \
- \
- { \
- GLfloat *dest = exec->vtx.attrptr[A]; \
- if (N>0) dest[0] = V0; \
- if (N>1) dest[1] = V1; \
- if (N>2) dest[2] = V2; \
- if (N>3) dest[3] = V3; \
- } \
- \
- if ((A) == 0) { \
- /* This is a glVertex call */ \
- GLuint i; \
- \
- for (i = 0; i < exec->vtx.vertex_size; i++) \
- exec->vtx.buffer_ptr[i] = exec->vtx.vertex[i]; \
- \
- exec->vtx.buffer_ptr += exec->vtx.vertex_size; \
- \
- /* Set FLUSH_STORED_VERTICES to indicate that there's now */ \
- /* something to draw (not just updating a color or texcoord).*/ \
- ctx->Driver.NeedFlush |= FLUSH_STORED_VERTICES; \
- \
- if (++exec->vtx.vert_count >= exec->vtx.max_vert) \
- vbo_exec_vtx_wrap( exec ); \
- } \
-} while (0)
-
-
-#define ERROR() _mesa_error( ctx, GL_INVALID_ENUM, __FUNCTION__ )
-#define TAG(x) vbo_##x
-
-#include "vbo_attrib_tmp.h"
-
-
-#if FEATURE_beginend
-
-
-#if FEATURE_evaluators
-
-static void GLAPIENTRY vbo_exec_EvalCoord1f( GLfloat u )
-{
- GET_CURRENT_CONTEXT( ctx );
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
-
- {
- GLint i;
- if (exec->eval.recalculate_maps)
- vbo_exec_eval_update( exec );
-
- for (i = 0; i <= VBO_ATTRIB_TEX7; i++) {
- if (exec->eval.map1[i].map)
- if (exec->vtx.active_sz[i] != exec->eval.map1[i].sz)
- vbo_exec_fixup_vertex( ctx, i, exec->eval.map1[i].sz );
- }
- }
-
-
- memcpy( exec->vtx.copied.buffer, exec->vtx.vertex,
- exec->vtx.vertex_size * sizeof(GLfloat));
-
- vbo_exec_do_EvalCoord1f( exec, u );
-
- memcpy( exec->vtx.vertex, exec->vtx.copied.buffer,
- exec->vtx.vertex_size * sizeof(GLfloat));
-}
-
-static void GLAPIENTRY vbo_exec_EvalCoord2f( GLfloat u, GLfloat v )
-{
- GET_CURRENT_CONTEXT( ctx );
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
-
- {
- GLint i;
- if (exec->eval.recalculate_maps)
- vbo_exec_eval_update( exec );
-
- for (i = 0; i <= VBO_ATTRIB_TEX7; i++) {
- if (exec->eval.map2[i].map)
- if (exec->vtx.active_sz[i] != exec->eval.map2[i].sz)
- vbo_exec_fixup_vertex( ctx, i, exec->eval.map2[i].sz );
- }
-
- if (ctx->Eval.AutoNormal)
- if (exec->vtx.active_sz[VBO_ATTRIB_NORMAL] != 3)
- vbo_exec_fixup_vertex( ctx, VBO_ATTRIB_NORMAL, 3 );
- }
-
- memcpy( exec->vtx.copied.buffer, exec->vtx.vertex,
- exec->vtx.vertex_size * sizeof(GLfloat));
-
- vbo_exec_do_EvalCoord2f( exec, u, v );
-
- memcpy( exec->vtx.vertex, exec->vtx.copied.buffer,
- exec->vtx.vertex_size * sizeof(GLfloat));
-}
-
-static void GLAPIENTRY vbo_exec_EvalCoord1fv( const GLfloat *u )
-{
- vbo_exec_EvalCoord1f( u[0] );
-}
-
-static void GLAPIENTRY vbo_exec_EvalCoord2fv( const GLfloat *u )
-{
- vbo_exec_EvalCoord2f( u[0], u[1] );
-}
-
-static void GLAPIENTRY vbo_exec_EvalPoint1( GLint i )
-{
- GET_CURRENT_CONTEXT( ctx );
- GLfloat du = ((ctx->Eval.MapGrid1u2 - ctx->Eval.MapGrid1u1) /
- (GLfloat) ctx->Eval.MapGrid1un);
- GLfloat u = i * du + ctx->Eval.MapGrid1u1;
-
- vbo_exec_EvalCoord1f( u );
-}
-
-
-static void GLAPIENTRY vbo_exec_EvalPoint2( GLint i, GLint j )
-{
- GET_CURRENT_CONTEXT( ctx );
- GLfloat du = ((ctx->Eval.MapGrid2u2 - ctx->Eval.MapGrid2u1) /
- (GLfloat) ctx->Eval.MapGrid2un);
- GLfloat dv = ((ctx->Eval.MapGrid2v2 - ctx->Eval.MapGrid2v1) /
- (GLfloat) ctx->Eval.MapGrid2vn);
- GLfloat u = i * du + ctx->Eval.MapGrid2u1;
- GLfloat v = j * dv + ctx->Eval.MapGrid2v1;
-
- vbo_exec_EvalCoord2f( u, v );
-}
-
-/* use noop eval mesh */
-#define vbo_exec_EvalMesh1 _mesa_noop_EvalMesh1
-#define vbo_exec_EvalMesh2 _mesa_noop_EvalMesh2
-
-#endif /* FEATURE_evaluators */
-
-
-/**
- * Flush (draw) vertices.
- * \param unmap - leave VBO unmapped after flushing?
- */
-static void
-vbo_exec_FlushVertices_internal(struct vbo_exec_context *exec, GLboolean unmap)
-{
- if (exec->vtx.vert_count || unmap) {
- vbo_exec_vtx_flush( exec, unmap );
- }
-
- if (exec->vtx.vertex_size) {
- vbo_exec_copy_to_current( exec );
- reset_attrfv( exec );
- }
-}
-
-
-/**
- * Called via glBegin.
- */
-static void GLAPIENTRY vbo_exec_Begin( GLenum mode )
-{
- GET_CURRENT_CONTEXT( ctx );
-
- if (ctx->Driver.CurrentExecPrimitive == PRIM_OUTSIDE_BEGIN_END) {
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
- int i;
-
- if (ctx->NewState) {
- _mesa_update_state( ctx );
-
- CALL_Begin(ctx->Exec, (mode));
- return;
- }
-
- if (!_mesa_valid_to_render(ctx, "glBegin")) {
- return;
- }
-
- /* Heuristic: attempt to isolate attributes occuring outside
- * begin/end pairs.
- */
- if (exec->vtx.vertex_size && !exec->vtx.attrsz[0])
- vbo_exec_FlushVertices_internal(exec, GL_FALSE);
-
- i = exec->vtx.prim_count++;
- exec->vtx.prim[i].mode = mode;
- exec->vtx.prim[i].begin = 1;
- exec->vtx.prim[i].end = 0;
- exec->vtx.prim[i].indexed = 0;
- exec->vtx.prim[i].weak = 0;
- exec->vtx.prim[i].pad = 0;
- exec->vtx.prim[i].start = exec->vtx.vert_count;
- exec->vtx.prim[i].count = 0;
- exec->vtx.prim[i].num_instances = 1;
-
- ctx->Driver.CurrentExecPrimitive = mode;
- }
- else
- _mesa_error( ctx, GL_INVALID_OPERATION, "glBegin" );
-
-}
-
-
-/**
- * Called via glEnd.
- */
-static void GLAPIENTRY vbo_exec_End( void )
-{
- GET_CURRENT_CONTEXT( ctx );
-
- if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
- int idx = exec->vtx.vert_count;
- int i = exec->vtx.prim_count - 1;
-
- exec->vtx.prim[i].end = 1;
- exec->vtx.prim[i].count = idx - exec->vtx.prim[i].start;
-
- ctx->Driver.CurrentExecPrimitive = PRIM_OUTSIDE_BEGIN_END;
-
- if (exec->vtx.prim_count == VBO_MAX_PRIM)
- vbo_exec_vtx_flush( exec, GL_FALSE );
- }
- else
- _mesa_error( ctx, GL_INVALID_OPERATION, "glEnd" );
-}
-
-
-/**
- * Called via glPrimitiveRestartNV()
- */
-static void GLAPIENTRY
-vbo_exec_PrimitiveRestartNV(void)
-{
- GLenum curPrim;
- GET_CURRENT_CONTEXT( ctx );
-
- curPrim = ctx->Driver.CurrentExecPrimitive;
-
- if (curPrim == PRIM_OUTSIDE_BEGIN_END) {
- _mesa_error( ctx, GL_INVALID_OPERATION, "glPrimitiveRestartNV" );
- }
- else {
- vbo_exec_End();
- vbo_exec_Begin(curPrim);
- }
-}
-
-
-
-static void vbo_exec_vtxfmt_init( struct vbo_exec_context *exec )
-{
- GLvertexformat *vfmt = &exec->vtxfmt;
-
- _MESA_INIT_ARRAYELT_VTXFMT(vfmt, _ae_);
-
- vfmt->Begin = vbo_exec_Begin;
- vfmt->End = vbo_exec_End;
- vfmt->PrimitiveRestartNV = vbo_exec_PrimitiveRestartNV;
-
- _MESA_INIT_DLIST_VTXFMT(vfmt, _mesa_);
- _MESA_INIT_EVAL_VTXFMT(vfmt, vbo_exec_);
-
- vfmt->Rectf = _mesa_noop_Rectf;
-
- /* from attrib_tmp.h:
- */
- vfmt->Color3f = vbo_Color3f;
- vfmt->Color3fv = vbo_Color3fv;
- vfmt->Color4f = vbo_Color4f;
- vfmt->Color4fv = vbo_Color4fv;
- vfmt->FogCoordfEXT = vbo_FogCoordfEXT;
- vfmt->FogCoordfvEXT = vbo_FogCoordfvEXT;
- vfmt->MultiTexCoord1fARB = vbo_MultiTexCoord1f;
- vfmt->MultiTexCoord1fvARB = vbo_MultiTexCoord1fv;
- vfmt->MultiTexCoord2fARB = vbo_MultiTexCoord2f;
- vfmt->MultiTexCoord2fvARB = vbo_MultiTexCoord2fv;
- vfmt->MultiTexCoord3fARB = vbo_MultiTexCoord3f;
- vfmt->MultiTexCoord3fvARB = vbo_MultiTexCoord3fv;
- vfmt->MultiTexCoord4fARB = vbo_MultiTexCoord4f;
- vfmt->MultiTexCoord4fvARB = vbo_MultiTexCoord4fv;
- vfmt->Normal3f = vbo_Normal3f;
- vfmt->Normal3fv = vbo_Normal3fv;
- vfmt->SecondaryColor3fEXT = vbo_SecondaryColor3fEXT;
- vfmt->SecondaryColor3fvEXT = vbo_SecondaryColor3fvEXT;
- vfmt->TexCoord1f = vbo_TexCoord1f;
- vfmt->TexCoord1fv = vbo_TexCoord1fv;
- vfmt->TexCoord2f = vbo_TexCoord2f;
- vfmt->TexCoord2fv = vbo_TexCoord2fv;
- vfmt->TexCoord3f = vbo_TexCoord3f;
- vfmt->TexCoord3fv = vbo_TexCoord3fv;
- vfmt->TexCoord4f = vbo_TexCoord4f;
- vfmt->TexCoord4fv = vbo_TexCoord4fv;
- vfmt->Vertex2f = vbo_Vertex2f;
- vfmt->Vertex2fv = vbo_Vertex2fv;
- vfmt->Vertex3f = vbo_Vertex3f;
- vfmt->Vertex3fv = vbo_Vertex3fv;
- vfmt->Vertex4f = vbo_Vertex4f;
- vfmt->Vertex4fv = vbo_Vertex4fv;
-
- vfmt->VertexAttrib1fARB = vbo_VertexAttrib1fARB;
- vfmt->VertexAttrib1fvARB = vbo_VertexAttrib1fvARB;
- vfmt->VertexAttrib2fARB = vbo_VertexAttrib2fARB;
- vfmt->VertexAttrib2fvARB = vbo_VertexAttrib2fvARB;
- vfmt->VertexAttrib3fARB = vbo_VertexAttrib3fARB;
- vfmt->VertexAttrib3fvARB = vbo_VertexAttrib3fvARB;
- vfmt->VertexAttrib4fARB = vbo_VertexAttrib4fARB;
- vfmt->VertexAttrib4fvARB = vbo_VertexAttrib4fvARB;
-
- vfmt->VertexAttrib1fNV = vbo_VertexAttrib1fNV;
- vfmt->VertexAttrib1fvNV = vbo_VertexAttrib1fvNV;
- vfmt->VertexAttrib2fNV = vbo_VertexAttrib2fNV;
- vfmt->VertexAttrib2fvNV = vbo_VertexAttrib2fvNV;
- vfmt->VertexAttrib3fNV = vbo_VertexAttrib3fNV;
- vfmt->VertexAttrib3fvNV = vbo_VertexAttrib3fvNV;
- vfmt->VertexAttrib4fNV = vbo_VertexAttrib4fNV;
- vfmt->VertexAttrib4fvNV = vbo_VertexAttrib4fvNV;
-
- /* integer-valued */
- vfmt->VertexAttribI1i = vbo_VertexAttribI1i;
- vfmt->VertexAttribI2i = vbo_VertexAttribI2i;
- vfmt->VertexAttribI3i = vbo_VertexAttribI3i;
- vfmt->VertexAttribI4i = vbo_VertexAttribI4i;
- vfmt->VertexAttribI2iv = vbo_VertexAttribI2iv;
- vfmt->VertexAttribI3iv = vbo_VertexAttribI3iv;
- vfmt->VertexAttribI4iv = vbo_VertexAttribI4iv;
-
- /* unsigned integer-valued */
- vfmt->VertexAttribI1ui = vbo_VertexAttribI1ui;
- vfmt->VertexAttribI2ui = vbo_VertexAttribI2ui;
- vfmt->VertexAttribI3ui = vbo_VertexAttribI3ui;
- vfmt->VertexAttribI4ui = vbo_VertexAttribI4ui;
- vfmt->VertexAttribI2uiv = vbo_VertexAttribI2uiv;
- vfmt->VertexAttribI3uiv = vbo_VertexAttribI3uiv;
- vfmt->VertexAttribI4uiv = vbo_VertexAttribI4uiv;
-
- vfmt->Materialfv = vbo_Materialfv;
-
- vfmt->EdgeFlag = vbo_EdgeFlag;
- vfmt->Indexf = vbo_Indexf;
- vfmt->Indexfv = vbo_Indexfv;
-
-}
-
-
-#else /* FEATURE_beginend */
-
-
-static void vbo_exec_vtxfmt_init( struct vbo_exec_context *exec )
-{
- /* silence warnings */
- (void) vbo_Color3f;
- (void) vbo_Color3fv;
- (void) vbo_Color4f;
- (void) vbo_Color4fv;
- (void) vbo_FogCoordfEXT;
- (void) vbo_FogCoordfvEXT;
- (void) vbo_MultiTexCoord1f;
- (void) vbo_MultiTexCoord1fv;
- (void) vbo_MultiTexCoord2f;
- (void) vbo_MultiTexCoord2fv;
- (void) vbo_MultiTexCoord3f;
- (void) vbo_MultiTexCoord3fv;
- (void) vbo_MultiTexCoord4f;
- (void) vbo_MultiTexCoord4fv;
- (void) vbo_Normal3f;
- (void) vbo_Normal3fv;
- (void) vbo_SecondaryColor3fEXT;
- (void) vbo_SecondaryColor3fvEXT;
- (void) vbo_TexCoord1f;
- (void) vbo_TexCoord1fv;
- (void) vbo_TexCoord2f;
- (void) vbo_TexCoord2fv;
- (void) vbo_TexCoord3f;
- (void) vbo_TexCoord3fv;
- (void) vbo_TexCoord4f;
- (void) vbo_TexCoord4fv;
- (void) vbo_Vertex2f;
- (void) vbo_Vertex2fv;
- (void) vbo_Vertex3f;
- (void) vbo_Vertex3fv;
- (void) vbo_Vertex4f;
- (void) vbo_Vertex4fv;
-
- (void) vbo_VertexAttrib1fARB;
- (void) vbo_VertexAttrib1fvARB;
- (void) vbo_VertexAttrib2fARB;
- (void) vbo_VertexAttrib2fvARB;
- (void) vbo_VertexAttrib3fARB;
- (void) vbo_VertexAttrib3fvARB;
- (void) vbo_VertexAttrib4fARB;
- (void) vbo_VertexAttrib4fvARB;
-
- (void) vbo_VertexAttrib1fNV;
- (void) vbo_VertexAttrib1fvNV;
- (void) vbo_VertexAttrib2fNV;
- (void) vbo_VertexAttrib2fvNV;
- (void) vbo_VertexAttrib3fNV;
- (void) vbo_VertexAttrib3fvNV;
- (void) vbo_VertexAttrib4fNV;
- (void) vbo_VertexAttrib4fvNV;
-
- (void) vbo_Materialfv;
-
- (void) vbo_EdgeFlag;
- (void) vbo_Indexf;
- (void) vbo_Indexfv;
-}
-
-
-#endif /* FEATURE_beginend */
-
-
-/**
- * Tell the VBO module to use a real OpenGL vertex buffer object to
- * store accumulated immediate-mode vertex data.
- * This replaces the malloced buffer which was created in
- * vb_exec_vtx_init() below.
- */
-void vbo_use_buffer_objects(struct gl_context *ctx)
-{
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
- /* Any buffer name but 0 can be used here since this bufferobj won't
- * go into the bufferobj hashtable.
- */
- GLuint bufName = IMM_BUFFER_NAME;
- GLenum target = GL_ARRAY_BUFFER_ARB;
- GLenum usage = GL_STREAM_DRAW_ARB;
- GLsizei size = VBO_VERT_BUFFER_SIZE;
-
- /* Make sure this func is only used once */
- assert(exec->vtx.bufferobj == ctx->Shared->NullBufferObj);
- if (exec->vtx.buffer_map) {
- _mesa_align_free(exec->vtx.buffer_map);
- exec->vtx.buffer_map = NULL;
- exec->vtx.buffer_ptr = NULL;
- }
-
- /* Allocate a real buffer object now */
- _mesa_reference_buffer_object(ctx, &exec->vtx.bufferobj, NULL);
- exec->vtx.bufferobj = ctx->Driver.NewBufferObject(ctx, bufName, target);
- ctx->Driver.BufferData(ctx, target, size, NULL, usage, exec->vtx.bufferobj);
-}
-
-
-
-void vbo_exec_vtx_init( struct vbo_exec_context *exec )
-{
- struct gl_context *ctx = exec->ctx;
- struct vbo_context *vbo = vbo_context(ctx);
- GLuint i;
-
- /* Allocate a buffer object. Will just reuse this object
- * continuously, unless vbo_use_buffer_objects() is called to enable
- * use of real VBOs.
- */
- _mesa_reference_buffer_object(ctx,
- &exec->vtx.bufferobj,
- ctx->Shared->NullBufferObj);
-
- ASSERT(!exec->vtx.buffer_map);
- exec->vtx.buffer_map = (GLfloat *)_mesa_align_malloc(VBO_VERT_BUFFER_SIZE, 64);
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
-
- vbo_exec_vtxfmt_init( exec );
-
- /* Hook our functions into the dispatch table.
- */
- _mesa_install_exec_vtxfmt( ctx, &exec->vtxfmt );
-
- for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
- ASSERT(i < Elements(exec->vtx.attrsz));
- exec->vtx.attrsz[i] = 0;
- ASSERT(i < Elements(exec->vtx.active_sz));
- exec->vtx.active_sz[i] = 0;
- }
- for (i = 0 ; i < VERT_ATTRIB_MAX; i++) {
- ASSERT(i < Elements(exec->vtx.inputs));
- ASSERT(i < Elements(exec->vtx.arrays));
- exec->vtx.inputs[i] = &exec->vtx.arrays[i];
- }
-
- {
- struct gl_client_array *arrays = exec->vtx.arrays;
- unsigned i;
-
- memcpy(arrays, vbo->legacy_currval, 16 * sizeof(arrays[0]));
- memcpy(arrays + 16, vbo->generic_currval, 16 * sizeof(arrays[0]));
-
- for (i = 0; i < 16; ++i) {
- arrays[i ].BufferObj = NULL;
- arrays[i + 16].BufferObj = NULL;
- _mesa_reference_buffer_object(ctx, &arrays[i ].BufferObj,
- vbo->legacy_currval[i].BufferObj);
- _mesa_reference_buffer_object(ctx, &arrays[i + 16].BufferObj,
- vbo->generic_currval[i].BufferObj);
- }
- }
-
- exec->vtx.vertex_size = 0;
-}
-
-
-void vbo_exec_vtx_destroy( struct vbo_exec_context *exec )
-{
- /* using a real VBO for vertex data */
- struct gl_context *ctx = exec->ctx;
- unsigned i;
-
- /* True VBOs should already be unmapped
- */
- if (exec->vtx.buffer_map) {
- ASSERT(exec->vtx.bufferobj->Name == 0 ||
- exec->vtx.bufferobj->Name == IMM_BUFFER_NAME);
- if (exec->vtx.bufferobj->Name == 0) {
- _mesa_align_free(exec->vtx.buffer_map);
- exec->vtx.buffer_map = NULL;
- exec->vtx.buffer_ptr = NULL;
- }
- }
-
- /* Drop any outstanding reference to the vertex buffer
- */
- for (i = 0; i < Elements(exec->vtx.arrays); i++) {
- _mesa_reference_buffer_object(ctx,
- &exec->vtx.arrays[i].BufferObj,
- NULL);
- }
-
- /* Free the vertex buffer. Unmap first if needed.
- */
- if (_mesa_bufferobj_mapped(exec->vtx.bufferobj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER, exec->vtx.bufferobj);
- }
- _mesa_reference_buffer_object(ctx, &exec->vtx.bufferobj, NULL);
-}
-
-
-/**
- * Called upon first glVertex, glColor, glTexCoord, etc.
- */
-void vbo_exec_BeginVertices( struct gl_context *ctx )
-{
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
-
- vbo_exec_vtx_map( exec );
-
- assert((ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT) == 0);
- ctx->Driver.NeedFlush |= FLUSH_UPDATE_CURRENT;
-}
-
-
-/**
- * Called via ctx->Driver.FlushVertices()
- * \param flags bitmask of FLUSH_STORED_VERTICES, FLUSH_UPDATE_CURRENT
- */
-void vbo_exec_FlushVertices( struct gl_context *ctx, GLuint flags )
-{
- struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
-
-#ifdef DEBUG
- /* debug check: make sure we don't get called recursively */
- exec->flush_call_depth++;
- assert(exec->flush_call_depth == 1);
-#endif
-
- if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
- /* We've had glBegin but not glEnd! */
-#ifdef DEBUG
- exec->flush_call_depth--;
- assert(exec->flush_call_depth == 0);
-#endif
- return;
- }
-
- /* Flush (draw), and make sure VBO is left unmapped when done */
- vbo_exec_FlushVertices_internal(exec, GL_TRUE);
-
- /* Need to do this to ensure BeginVertices gets called again:
- */
- ctx->Driver.NeedFlush &= ~(FLUSH_UPDATE_CURRENT | flags);
-
-#ifdef DEBUG
- exec->flush_call_depth--;
- assert(exec->flush_call_depth == 0);
-#endif
-}
-
-
-static void reset_attrfv( struct vbo_exec_context *exec )
-{
- GLuint i;
-
- for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
- exec->vtx.attrsz[i] = 0;
- exec->vtx.active_sz[i] = 0;
- }
-
- exec->vtx.vertex_size = 0;
-}
-
-
-void GLAPIENTRY
-_es_Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
-{
- vbo_Color4f(r, g, b, a);
-}
-
-
-void GLAPIENTRY
-_es_Normal3f(GLfloat x, GLfloat y, GLfloat z)
-{
- vbo_Normal3f(x, y, z);
-}
-
-
-void GLAPIENTRY
-_es_MultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
-{
- vbo_MultiTexCoord4f(target, s, t, r, q);
-}
-
-
-void GLAPIENTRY
-_es_Materialfv(GLenum face, GLenum pname, const GLfloat *params)
-{
- vbo_Materialfv(face, pname, params);
-}
-
-
-void GLAPIENTRY
-_es_Materialf(GLenum face, GLenum pname, GLfloat param)
-{
- GLfloat p[4];
- p[0] = param;
- p[1] = p[2] = p[3] = 0.0F;
- vbo_Materialfv(face, pname, p);
-}
-
-
-/**
- * A special version of glVertexAttrib4f that does not treat index 0 as
- * VBO_ATTRIB_POS.
- */
-static void
-VertexAttrib4f_nopos(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- GET_CURRENT_CONTEXT(ctx);
- if (index < MAX_VERTEX_GENERIC_ATTRIBS)
- ATTR(VBO_ATTRIB_GENERIC0 + index, 4, x, y, z, w);
- else
- ERROR();
-}
-
-void GLAPIENTRY
-_es_VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
-{
- VertexAttrib4f_nopos(index, x, y, z, w);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib1f(GLuint indx, GLfloat x)
-{
- VertexAttrib4f_nopos(indx, x, 0.0f, 0.0f, 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib1fv(GLuint indx, const GLfloat* values)
-{
- VertexAttrib4f_nopos(indx, values[0], 0.0f, 0.0f, 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
-{
- VertexAttrib4f_nopos(indx, x, y, 0.0f, 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib2fv(GLuint indx, const GLfloat* values)
-{
- VertexAttrib4f_nopos(indx, values[0], values[1], 0.0f, 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
-{
- VertexAttrib4f_nopos(indx, x, y, z, 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib3fv(GLuint indx, const GLfloat* values)
-{
- VertexAttrib4f_nopos(indx, values[0], values[1], values[2], 1.0f);
-}
-
-
-void GLAPIENTRY
-_es_VertexAttrib4fv(GLuint indx, const GLfloat* values)
-{
- VertexAttrib4f_nopos(indx, values[0], values[1], values[2], values[3]);
-}
+/**************************************************************************
+
+Copyright 2002-2008 Tungsten Graphics Inc., Cedar Park, Texas.
+
+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
+on the rights to use, copy, modify, merge, publish, distribute, sub
+license, 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 (including the next
+paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL
+TUNGSTEN GRAPHICS AND/OR THEIR SUPPLIERS 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ */
+
+#include "main/glheader.h"
+#include "main/bufferobj.h"
+#include "main/context.h"
+#include "main/macros.h"
+#include "main/mfeatures.h"
+#include "main/vtxfmt.h"
+#include "main/dlist.h"
+#include "main/eval.h"
+#include "main/state.h"
+#include "main/light.h"
+#include "main/api_arrayelt.h"
+#include "main/api_noop.h"
+#include "main/dispatch.h"
+
+#include "vbo_context.h"
+
+#ifdef ERROR
+#undef ERROR
+#endif
+
+
+/** ID/name for immediate-mode VBO */
+#define IMM_BUFFER_NAME 0xaabbccdd
+
+
+static void reset_attrfv( struct vbo_exec_context *exec );
+
+
+/**
+ * Close off the last primitive, execute the buffer, restart the
+ * primitive.
+ */
+static void vbo_exec_wrap_buffers( struct vbo_exec_context *exec )
+{
+ if (exec->vtx.prim_count == 0) {
+ exec->vtx.copied.nr = 0;
+ exec->vtx.vert_count = 0;
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+ }
+ else {
+ GLuint last_begin = exec->vtx.prim[exec->vtx.prim_count-1].begin;
+ GLuint last_count;
+
+ if (exec->ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
+ GLint i = exec->vtx.prim_count - 1;
+ assert(i >= 0);
+ exec->vtx.prim[i].count = (exec->vtx.vert_count -
+ exec->vtx.prim[i].start);
+ }
+
+ last_count = exec->vtx.prim[exec->vtx.prim_count-1].count;
+
+ /* Execute the buffer and save copied vertices.
+ */
+ if (exec->vtx.vert_count)
+ vbo_exec_vtx_flush( exec, GL_FALSE );
+ else {
+ exec->vtx.prim_count = 0;
+ exec->vtx.copied.nr = 0;
+ }
+
+ /* Emit a glBegin to start the new list.
+ */
+ assert(exec->vtx.prim_count == 0);
+
+ if (exec->ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
+ exec->vtx.prim[0].mode = exec->ctx->Driver.CurrentExecPrimitive;
+ exec->vtx.prim[0].start = 0;
+ exec->vtx.prim[0].count = 0;
+ exec->vtx.prim_count++;
+
+ if (exec->vtx.copied.nr == last_count)
+ exec->vtx.prim[0].begin = last_begin;
+ }
+ }
+}
+
+
+/**
+ * Deal with buffer wrapping where provoked by the vertex buffer
+ * filling up, as opposed to upgrade_vertex().
+ */
+void vbo_exec_vtx_wrap( struct vbo_exec_context *exec )
+{
+ GLfloat *data = exec->vtx.copied.buffer;
+ GLuint i;
+
+ /* Run pipeline on current vertices, copy wrapped vertices
+ * to exec->vtx.copied.
+ */
+ vbo_exec_wrap_buffers( exec );
+
+ /* Copy stored stored vertices to start of new list.
+ */
+ assert(exec->vtx.max_vert - exec->vtx.vert_count > exec->vtx.copied.nr);
+
+ for (i = 0 ; i < exec->vtx.copied.nr ; i++) {
+ memcpy( exec->vtx.buffer_ptr, data,
+ exec->vtx.vertex_size * sizeof(GLfloat));
+ exec->vtx.buffer_ptr += exec->vtx.vertex_size;
+ data += exec->vtx.vertex_size;
+ exec->vtx.vert_count++;
+ }
+
+ exec->vtx.copied.nr = 0;
+}
+
+
+/**
+ * Copy the active vertex's values to the ctx->Current fields.
+ */
+static void vbo_exec_copy_to_current( struct vbo_exec_context *exec )
+{
+ struct gl_context *ctx = exec->ctx;
+ struct vbo_context *vbo = vbo_context(ctx);
+ GLuint i;
+
+ for (i = VBO_ATTRIB_POS+1 ; i < VBO_ATTRIB_MAX ; i++) {
+ if (exec->vtx.attrsz[i]) {
+ /* Note: the exec->vtx.current[i] pointers point into the
+ * ctx->Current.Attrib and ctx->Light.Material.Attrib arrays.
+ */
+ GLfloat *current = (GLfloat *)vbo->currval[i].Ptr;
+ GLfloat tmp[4];
+
+ COPY_CLEAN_4V(tmp,
+ exec->vtx.attrsz[i],
+ exec->vtx.attrptr[i]);
+
+ if (memcmp(current, tmp, sizeof(tmp)) != 0) {
+ memcpy(current, tmp, sizeof(tmp));
+
+ /* Given that we explicitly state size here, there is no need
+ * for the COPY_CLEAN above, could just copy 16 bytes and be
+ * done. The only problem is when Mesa accesses ctx->Current
+ * directly.
+ */
+ vbo->currval[i].Size = exec->vtx.attrsz[i];
+
+ /* This triggers rather too much recalculation of Mesa state
+ * that doesn't get used (eg light positions).
+ */
+ if (i >= VBO_ATTRIB_MAT_FRONT_AMBIENT &&
+ i <= VBO_ATTRIB_MAT_BACK_INDEXES)
+ ctx->NewState |= _NEW_LIGHT;
+
+ ctx->NewState |= _NEW_CURRENT_ATTRIB;
+ }
+ }
+ }
+
+ /* Colormaterial -- this kindof sucks.
+ */
+ if (ctx->Light.ColorMaterialEnabled &&
+ exec->vtx.attrsz[VBO_ATTRIB_COLOR0]) {
+ _mesa_update_color_material(ctx,
+ ctx->Current.Attrib[VBO_ATTRIB_COLOR0]);
+ }
+}
+
+
+/**
+ * Copy current vertex attribute values into the current vertex.
+ */
+static void
+vbo_exec_copy_from_current(struct vbo_exec_context *exec)
+{
+ struct gl_context *ctx = exec->ctx;
+ struct vbo_context *vbo = vbo_context(ctx);
+ GLint i;
+
+ for (i = VBO_ATTRIB_POS + 1; i < VBO_ATTRIB_MAX; i++) {
+ const GLfloat *current = (GLfloat *) vbo->currval[i].Ptr;
+ switch (exec->vtx.attrsz[i]) {
+ case 4: exec->vtx.attrptr[i][3] = current[3];
+ case 3: exec->vtx.attrptr[i][2] = current[2];
+ case 2: exec->vtx.attrptr[i][1] = current[1];
+ case 1: exec->vtx.attrptr[i][0] = current[0];
+ break;
+ }
+ }
+}
+
+
+/**
+ * Flush existing data, set new attrib size, replay copied vertices.
+ * This is called when we transition from a small vertex attribute size
+ * to a larger one. Ex: glTexCoord2f -> glTexCoord4f.
+ * We need to go back over the previous 2-component texcoords and insert
+ * zero and one values.
+ */
+static void
+vbo_exec_wrap_upgrade_vertex(struct vbo_exec_context *exec,
+ GLuint attr, GLuint newSize )
+{
+ struct gl_context *ctx = exec->ctx;
+ struct vbo_context *vbo = vbo_context(ctx);
+ const GLint lastcount = exec->vtx.vert_count;
+ GLfloat *old_attrptr[VBO_ATTRIB_MAX];
+ const GLuint old_vtx_size = exec->vtx.vertex_size; /* floats per vertex */
+ const GLuint oldSize = exec->vtx.attrsz[attr];
+ GLuint i;
+
+ /* Run pipeline on current vertices, copy wrapped vertices
+ * to exec->vtx.copied.
+ */
+ vbo_exec_wrap_buffers( exec );
+
+ if (unlikely(exec->vtx.copied.nr)) {
+ /* We're in the middle of a primitive, keep the old vertex
+ * format around to be able to translate the copied vertices to
+ * the new format.
+ */
+ memcpy(old_attrptr, exec->vtx.attrptr, sizeof(old_attrptr));
+ }
+
+ if (unlikely(oldSize)) {
+ /* Do a COPY_TO_CURRENT to ensure back-copying works for the
+ * case when the attribute already exists in the vertex and is
+ * having its size increased.
+ */
+ vbo_exec_copy_to_current( exec );
+ }
+
+ /* Heuristic: Attempt to isolate attributes received outside
+ * begin/end so that they don't bloat the vertices.
+ */
+ if (ctx->Driver.CurrentExecPrimitive == PRIM_OUTSIDE_BEGIN_END &&
+ !oldSize && lastcount > 8 && exec->vtx.vertex_size) {
+ vbo_exec_copy_to_current( exec );
+ reset_attrfv( exec );
+ }
+
+ /* Fix up sizes:
+ */
+ exec->vtx.attrsz[attr] = newSize;
+ exec->vtx.vertex_size += newSize - oldSize;
+ exec->vtx.max_vert = ((VBO_VERT_BUFFER_SIZE - exec->vtx.buffer_used) /
+ (exec->vtx.vertex_size * sizeof(GLfloat)));
+ exec->vtx.vert_count = 0;
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+
+ if (unlikely(oldSize)) {
+ /* Size changed, recalculate all the attrptr[] values
+ */
+ GLfloat *tmp = exec->vtx.vertex;
+
+ for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
+ if (exec->vtx.attrsz[i]) {
+ exec->vtx.attrptr[i] = tmp;
+ tmp += exec->vtx.attrsz[i];
+ }
+ else
+ exec->vtx.attrptr[i] = NULL; /* will not be dereferenced */
+ }
+
+ /* Copy from current to repopulate the vertex with correct
+ * values.
+ */
+ vbo_exec_copy_from_current( exec );
+ }
+ else {
+ /* Just have to append the new attribute at the end */
+ exec->vtx.attrptr[attr] = exec->vtx.vertex +
+ exec->vtx.vertex_size - newSize;
+ }
+
+ /* Replay stored vertices to translate them
+ * to new format here.
+ *
+ * -- No need to replay - just copy piecewise
+ */
+ if (unlikely(exec->vtx.copied.nr)) {
+ GLfloat *data = exec->vtx.copied.buffer;
+ GLfloat *dest = exec->vtx.buffer_ptr;
+ GLuint j;
+
+ assert(exec->vtx.buffer_ptr == exec->vtx.buffer_map);
+
+ for (i = 0 ; i < exec->vtx.copied.nr ; i++) {
+ for (j = 0 ; j < VBO_ATTRIB_MAX ; j++) {
+ GLuint sz = exec->vtx.attrsz[j];
+
+ if (sz) {
+ GLint old_offset = old_attrptr[j] - exec->vtx.vertex;
+ GLint new_offset = exec->vtx.attrptr[j] - exec->vtx.vertex;
+
+ if (j == attr) {
+ if (oldSize) {
+ GLfloat tmp[4];
+ COPY_CLEAN_4V(tmp, oldSize, data + old_offset);
+ COPY_SZ_4V(dest + new_offset, newSize, tmp);
+ } else {
+ GLfloat *current = (GLfloat *)vbo->currval[j].Ptr;
+ COPY_SZ_4V(dest + new_offset, sz, current);
+ }
+ }
+ else {
+ COPY_SZ_4V(dest + new_offset, sz, data + old_offset);
+ }
+ }
+ }
+
+ data += old_vtx_size;
+ dest += exec->vtx.vertex_size;
+ }
+
+ exec->vtx.buffer_ptr = dest;
+ exec->vtx.vert_count += exec->vtx.copied.nr;
+ exec->vtx.copied.nr = 0;
+ }
+}
+
+
+/**
+ * This is when a vertex attribute transitions to a different size.
+ * For example, we saw a bunch of glTexCoord2f() calls and now we got a
+ * glTexCoord4f() call. We promote the array from size=2 to size=4.
+ */
+static void
+vbo_exec_fixup_vertex(struct gl_context *ctx, GLuint attr, GLuint newSize)
+{
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+
+ if (newSize > exec->vtx.attrsz[attr]) {
+ /* New size is larger. Need to flush existing vertices and get
+ * an enlarged vertex format.
+ */
+ vbo_exec_wrap_upgrade_vertex( exec, attr, newSize );
+ }
+ else if (newSize < exec->vtx.active_sz[attr]) {
+ static const GLfloat id[4] = { 0, 0, 0, 1 };
+ GLuint i;
+
+ /* New size is smaller - just need to fill in some
+ * zeros. Don't need to flush or wrap.
+ */
+ for (i = newSize; i <= exec->vtx.attrsz[attr]; i++)
+ exec->vtx.attrptr[attr][i-1] = id[i-1];
+ }
+
+ exec->vtx.active_sz[attr] = newSize;
+
+ /* Does setting NeedFlush belong here? Necessitates resetting
+ * vtxfmt on each flush (otherwise flags won't get reset
+ * afterwards).
+ */
+ if (attr == 0)
+ ctx->Driver.NeedFlush |= FLUSH_STORED_VERTICES;
+}
+
+
+/**
+ * This macro is used to implement all the glVertex, glColor, glTexCoord,
+ * glVertexAttrib, etc functions.
+ */
+#define ATTR( A, N, V0, V1, V2, V3 ) \
+do { \
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec; \
+ \
+ if (unlikely(!(ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT))) \
+ ctx->Driver.BeginVertices( ctx ); \
+ \
+ if (unlikely(exec->vtx.active_sz[A] != N)) \
+ vbo_exec_fixup_vertex(ctx, A, N); \
+ \
+ { \
+ GLfloat *dest = exec->vtx.attrptr[A]; \
+ if (N>0) dest[0] = V0; \
+ if (N>1) dest[1] = V1; \
+ if (N>2) dest[2] = V2; \
+ if (N>3) dest[3] = V3; \
+ } \
+ \
+ if ((A) == 0) { \
+ /* This is a glVertex call */ \
+ GLuint i; \
+ \
+ for (i = 0; i < exec->vtx.vertex_size; i++) \
+ exec->vtx.buffer_ptr[i] = exec->vtx.vertex[i]; \
+ \
+ exec->vtx.buffer_ptr += exec->vtx.vertex_size; \
+ \
+ /* Set FLUSH_STORED_VERTICES to indicate that there's now */ \
+ /* something to draw (not just updating a color or texcoord).*/ \
+ ctx->Driver.NeedFlush |= FLUSH_STORED_VERTICES; \
+ \
+ if (++exec->vtx.vert_count >= exec->vtx.max_vert) \
+ vbo_exec_vtx_wrap( exec ); \
+ } \
+} while (0)
+
+
+#define ERROR() _mesa_error( ctx, GL_INVALID_ENUM, __FUNCTION__ )
+#define TAG(x) vbo_##x
+
+#include "vbo_attrib_tmp.h"
+
+
+#if FEATURE_beginend
+
+
+#if FEATURE_evaluators
+
+static void GLAPIENTRY vbo_exec_EvalCoord1f( GLfloat u )
+{
+ GET_CURRENT_CONTEXT( ctx );
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+
+ {
+ GLint i;
+ if (exec->eval.recalculate_maps)
+ vbo_exec_eval_update( exec );
+
+ for (i = 0; i <= VBO_ATTRIB_TEX7; i++) {
+ if (exec->eval.map1[i].map)
+ if (exec->vtx.active_sz[i] != exec->eval.map1[i].sz)
+ vbo_exec_fixup_vertex( ctx, i, exec->eval.map1[i].sz );
+ }
+ }
+
+
+ memcpy( exec->vtx.copied.buffer, exec->vtx.vertex,
+ exec->vtx.vertex_size * sizeof(GLfloat));
+
+ vbo_exec_do_EvalCoord1f( exec, u );
+
+ memcpy( exec->vtx.vertex, exec->vtx.copied.buffer,
+ exec->vtx.vertex_size * sizeof(GLfloat));
+}
+
+static void GLAPIENTRY vbo_exec_EvalCoord2f( GLfloat u, GLfloat v )
+{
+ GET_CURRENT_CONTEXT( ctx );
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+
+ {
+ GLint i;
+ if (exec->eval.recalculate_maps)
+ vbo_exec_eval_update( exec );
+
+ for (i = 0; i <= VBO_ATTRIB_TEX7; i++) {
+ if (exec->eval.map2[i].map)
+ if (exec->vtx.active_sz[i] != exec->eval.map2[i].sz)
+ vbo_exec_fixup_vertex( ctx, i, exec->eval.map2[i].sz );
+ }
+
+ if (ctx->Eval.AutoNormal)
+ if (exec->vtx.active_sz[VBO_ATTRIB_NORMAL] != 3)
+ vbo_exec_fixup_vertex( ctx, VBO_ATTRIB_NORMAL, 3 );
+ }
+
+ memcpy( exec->vtx.copied.buffer, exec->vtx.vertex,
+ exec->vtx.vertex_size * sizeof(GLfloat));
+
+ vbo_exec_do_EvalCoord2f( exec, u, v );
+
+ memcpy( exec->vtx.vertex, exec->vtx.copied.buffer,
+ exec->vtx.vertex_size * sizeof(GLfloat));
+}
+
+static void GLAPIENTRY vbo_exec_EvalCoord1fv( const GLfloat *u )
+{
+ vbo_exec_EvalCoord1f( u[0] );
+}
+
+static void GLAPIENTRY vbo_exec_EvalCoord2fv( const GLfloat *u )
+{
+ vbo_exec_EvalCoord2f( u[0], u[1] );
+}
+
+static void GLAPIENTRY vbo_exec_EvalPoint1( GLint i )
+{
+ GET_CURRENT_CONTEXT( ctx );
+ GLfloat du = ((ctx->Eval.MapGrid1u2 - ctx->Eval.MapGrid1u1) /
+ (GLfloat) ctx->Eval.MapGrid1un);
+ GLfloat u = i * du + ctx->Eval.MapGrid1u1;
+
+ vbo_exec_EvalCoord1f( u );
+}
+
+
+static void GLAPIENTRY vbo_exec_EvalPoint2( GLint i, GLint j )
+{
+ GET_CURRENT_CONTEXT( ctx );
+ GLfloat du = ((ctx->Eval.MapGrid2u2 - ctx->Eval.MapGrid2u1) /
+ (GLfloat) ctx->Eval.MapGrid2un);
+ GLfloat dv = ((ctx->Eval.MapGrid2v2 - ctx->Eval.MapGrid2v1) /
+ (GLfloat) ctx->Eval.MapGrid2vn);
+ GLfloat u = i * du + ctx->Eval.MapGrid2u1;
+ GLfloat v = j * dv + ctx->Eval.MapGrid2v1;
+
+ vbo_exec_EvalCoord2f( u, v );
+}
+
+/* use noop eval mesh */
+#define vbo_exec_EvalMesh1 _mesa_noop_EvalMesh1
+#define vbo_exec_EvalMesh2 _mesa_noop_EvalMesh2
+
+#endif /* FEATURE_evaluators */
+
+
+/**
+ * Flush (draw) vertices.
+ * \param unmap - leave VBO unmapped after flushing?
+ */
+static void
+vbo_exec_FlushVertices_internal(struct vbo_exec_context *exec, GLboolean unmap)
+{
+ if (exec->vtx.vert_count || unmap) {
+ vbo_exec_vtx_flush( exec, unmap );
+ }
+
+ if (exec->vtx.vertex_size) {
+ vbo_exec_copy_to_current( exec );
+ reset_attrfv( exec );
+ }
+}
+
+
+/**
+ * Called via glBegin.
+ */
+static void GLAPIENTRY vbo_exec_Begin( GLenum mode )
+{
+ GET_CURRENT_CONTEXT( ctx );
+
+ if (ctx->Driver.CurrentExecPrimitive == PRIM_OUTSIDE_BEGIN_END) {
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+ int i;
+
+ if (ctx->NewState) {
+ _mesa_update_state( ctx );
+
+ CALL_Begin(ctx->Exec, (mode));
+ return;
+ }
+
+ if (!_mesa_valid_to_render(ctx, "glBegin")) {
+ return;
+ }
+
+ /* Heuristic: attempt to isolate attributes occuring outside
+ * begin/end pairs.
+ */
+ if (exec->vtx.vertex_size && !exec->vtx.attrsz[0])
+ vbo_exec_FlushVertices_internal(exec, GL_FALSE);
+
+ i = exec->vtx.prim_count++;
+ exec->vtx.prim[i].mode = mode;
+ exec->vtx.prim[i].begin = 1;
+ exec->vtx.prim[i].end = 0;
+ exec->vtx.prim[i].indexed = 0;
+ exec->vtx.prim[i].weak = 0;
+ exec->vtx.prim[i].pad = 0;
+ exec->vtx.prim[i].start = exec->vtx.vert_count;
+ exec->vtx.prim[i].count = 0;
+ exec->vtx.prim[i].num_instances = 1;
+
+ ctx->Driver.CurrentExecPrimitive = mode;
+ }
+ else
+ _mesa_error( ctx, GL_INVALID_OPERATION, "glBegin" );
+
+}
+
+
+/**
+ * Called via glEnd.
+ */
+static void GLAPIENTRY vbo_exec_End( void )
+{
+ GET_CURRENT_CONTEXT( ctx );
+
+ if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+ int idx = exec->vtx.vert_count;
+ int i = exec->vtx.prim_count - 1;
+
+ exec->vtx.prim[i].end = 1;
+ exec->vtx.prim[i].count = idx - exec->vtx.prim[i].start;
+
+ ctx->Driver.CurrentExecPrimitive = PRIM_OUTSIDE_BEGIN_END;
+
+ if (exec->vtx.prim_count == VBO_MAX_PRIM)
+ vbo_exec_vtx_flush( exec, GL_FALSE );
+ }
+ else
+ _mesa_error( ctx, GL_INVALID_OPERATION, "glEnd" );
+}
+
+
+/**
+ * Called via glPrimitiveRestartNV()
+ */
+static void GLAPIENTRY
+vbo_exec_PrimitiveRestartNV(void)
+{
+ GLenum curPrim;
+ GET_CURRENT_CONTEXT( ctx );
+
+ curPrim = ctx->Driver.CurrentExecPrimitive;
+
+ if (curPrim == PRIM_OUTSIDE_BEGIN_END) {
+ _mesa_error( ctx, GL_INVALID_OPERATION, "glPrimitiveRestartNV" );
+ }
+ else {
+ vbo_exec_End();
+ vbo_exec_Begin(curPrim);
+ }
+}
+
+
+
+static void vbo_exec_vtxfmt_init( struct vbo_exec_context *exec )
+{
+ GLvertexformat *vfmt = &exec->vtxfmt;
+
+ _MESA_INIT_ARRAYELT_VTXFMT(vfmt, _ae_);
+
+ vfmt->Begin = vbo_exec_Begin;
+ vfmt->End = vbo_exec_End;
+ vfmt->PrimitiveRestartNV = vbo_exec_PrimitiveRestartNV;
+
+ _MESA_INIT_DLIST_VTXFMT(vfmt, _mesa_);
+ _MESA_INIT_EVAL_VTXFMT(vfmt, vbo_exec_);
+
+ vfmt->Rectf = _mesa_noop_Rectf;
+
+ /* from attrib_tmp.h:
+ */
+ vfmt->Color3f = vbo_Color3f;
+ vfmt->Color3fv = vbo_Color3fv;
+ vfmt->Color4f = vbo_Color4f;
+ vfmt->Color4fv = vbo_Color4fv;
+ vfmt->FogCoordfEXT = vbo_FogCoordfEXT;
+ vfmt->FogCoordfvEXT = vbo_FogCoordfvEXT;
+ vfmt->MultiTexCoord1fARB = vbo_MultiTexCoord1f;
+ vfmt->MultiTexCoord1fvARB = vbo_MultiTexCoord1fv;
+ vfmt->MultiTexCoord2fARB = vbo_MultiTexCoord2f;
+ vfmt->MultiTexCoord2fvARB = vbo_MultiTexCoord2fv;
+ vfmt->MultiTexCoord3fARB = vbo_MultiTexCoord3f;
+ vfmt->MultiTexCoord3fvARB = vbo_MultiTexCoord3fv;
+ vfmt->MultiTexCoord4fARB = vbo_MultiTexCoord4f;
+ vfmt->MultiTexCoord4fvARB = vbo_MultiTexCoord4fv;
+ vfmt->Normal3f = vbo_Normal3f;
+ vfmt->Normal3fv = vbo_Normal3fv;
+ vfmt->SecondaryColor3fEXT = vbo_SecondaryColor3fEXT;
+ vfmt->SecondaryColor3fvEXT = vbo_SecondaryColor3fvEXT;
+ vfmt->TexCoord1f = vbo_TexCoord1f;
+ vfmt->TexCoord1fv = vbo_TexCoord1fv;
+ vfmt->TexCoord2f = vbo_TexCoord2f;
+ vfmt->TexCoord2fv = vbo_TexCoord2fv;
+ vfmt->TexCoord3f = vbo_TexCoord3f;
+ vfmt->TexCoord3fv = vbo_TexCoord3fv;
+ vfmt->TexCoord4f = vbo_TexCoord4f;
+ vfmt->TexCoord4fv = vbo_TexCoord4fv;
+ vfmt->Vertex2f = vbo_Vertex2f;
+ vfmt->Vertex2fv = vbo_Vertex2fv;
+ vfmt->Vertex3f = vbo_Vertex3f;
+ vfmt->Vertex3fv = vbo_Vertex3fv;
+ vfmt->Vertex4f = vbo_Vertex4f;
+ vfmt->Vertex4fv = vbo_Vertex4fv;
+
+ vfmt->VertexAttrib1fARB = vbo_VertexAttrib1fARB;
+ vfmt->VertexAttrib1fvARB = vbo_VertexAttrib1fvARB;
+ vfmt->VertexAttrib2fARB = vbo_VertexAttrib2fARB;
+ vfmt->VertexAttrib2fvARB = vbo_VertexAttrib2fvARB;
+ vfmt->VertexAttrib3fARB = vbo_VertexAttrib3fARB;
+ vfmt->VertexAttrib3fvARB = vbo_VertexAttrib3fvARB;
+ vfmt->VertexAttrib4fARB = vbo_VertexAttrib4fARB;
+ vfmt->VertexAttrib4fvARB = vbo_VertexAttrib4fvARB;
+
+ vfmt->VertexAttrib1fNV = vbo_VertexAttrib1fNV;
+ vfmt->VertexAttrib1fvNV = vbo_VertexAttrib1fvNV;
+ vfmt->VertexAttrib2fNV = vbo_VertexAttrib2fNV;
+ vfmt->VertexAttrib2fvNV = vbo_VertexAttrib2fvNV;
+ vfmt->VertexAttrib3fNV = vbo_VertexAttrib3fNV;
+ vfmt->VertexAttrib3fvNV = vbo_VertexAttrib3fvNV;
+ vfmt->VertexAttrib4fNV = vbo_VertexAttrib4fNV;
+ vfmt->VertexAttrib4fvNV = vbo_VertexAttrib4fvNV;
+
+ /* integer-valued */
+ vfmt->VertexAttribI1i = vbo_VertexAttribI1i;
+ vfmt->VertexAttribI2i = vbo_VertexAttribI2i;
+ vfmt->VertexAttribI3i = vbo_VertexAttribI3i;
+ vfmt->VertexAttribI4i = vbo_VertexAttribI4i;
+ vfmt->VertexAttribI2iv = vbo_VertexAttribI2iv;
+ vfmt->VertexAttribI3iv = vbo_VertexAttribI3iv;
+ vfmt->VertexAttribI4iv = vbo_VertexAttribI4iv;
+
+ /* unsigned integer-valued */
+ vfmt->VertexAttribI1ui = vbo_VertexAttribI1ui;
+ vfmt->VertexAttribI2ui = vbo_VertexAttribI2ui;
+ vfmt->VertexAttribI3ui = vbo_VertexAttribI3ui;
+ vfmt->VertexAttribI4ui = vbo_VertexAttribI4ui;
+ vfmt->VertexAttribI2uiv = vbo_VertexAttribI2uiv;
+ vfmt->VertexAttribI3uiv = vbo_VertexAttribI3uiv;
+ vfmt->VertexAttribI4uiv = vbo_VertexAttribI4uiv;
+
+ vfmt->Materialfv = vbo_Materialfv;
+
+ vfmt->EdgeFlag = vbo_EdgeFlag;
+ vfmt->Indexf = vbo_Indexf;
+ vfmt->Indexfv = vbo_Indexfv;
+
+}
+
+
+#else /* FEATURE_beginend */
+
+
+static void vbo_exec_vtxfmt_init( struct vbo_exec_context *exec )
+{
+ /* silence warnings */
+ (void) vbo_Color3f;
+ (void) vbo_Color3fv;
+ (void) vbo_Color4f;
+ (void) vbo_Color4fv;
+ (void) vbo_FogCoordfEXT;
+ (void) vbo_FogCoordfvEXT;
+ (void) vbo_MultiTexCoord1f;
+ (void) vbo_MultiTexCoord1fv;
+ (void) vbo_MultiTexCoord2f;
+ (void) vbo_MultiTexCoord2fv;
+ (void) vbo_MultiTexCoord3f;
+ (void) vbo_MultiTexCoord3fv;
+ (void) vbo_MultiTexCoord4f;
+ (void) vbo_MultiTexCoord4fv;
+ (void) vbo_Normal3f;
+ (void) vbo_Normal3fv;
+ (void) vbo_SecondaryColor3fEXT;
+ (void) vbo_SecondaryColor3fvEXT;
+ (void) vbo_TexCoord1f;
+ (void) vbo_TexCoord1fv;
+ (void) vbo_TexCoord2f;
+ (void) vbo_TexCoord2fv;
+ (void) vbo_TexCoord3f;
+ (void) vbo_TexCoord3fv;
+ (void) vbo_TexCoord4f;
+ (void) vbo_TexCoord4fv;
+ (void) vbo_Vertex2f;
+ (void) vbo_Vertex2fv;
+ (void) vbo_Vertex3f;
+ (void) vbo_Vertex3fv;
+ (void) vbo_Vertex4f;
+ (void) vbo_Vertex4fv;
+
+ (void) vbo_VertexAttrib1fARB;
+ (void) vbo_VertexAttrib1fvARB;
+ (void) vbo_VertexAttrib2fARB;
+ (void) vbo_VertexAttrib2fvARB;
+ (void) vbo_VertexAttrib3fARB;
+ (void) vbo_VertexAttrib3fvARB;
+ (void) vbo_VertexAttrib4fARB;
+ (void) vbo_VertexAttrib4fvARB;
+
+ (void) vbo_VertexAttrib1fNV;
+ (void) vbo_VertexAttrib1fvNV;
+ (void) vbo_VertexAttrib2fNV;
+ (void) vbo_VertexAttrib2fvNV;
+ (void) vbo_VertexAttrib3fNV;
+ (void) vbo_VertexAttrib3fvNV;
+ (void) vbo_VertexAttrib4fNV;
+ (void) vbo_VertexAttrib4fvNV;
+
+ (void) vbo_Materialfv;
+
+ (void) vbo_EdgeFlag;
+ (void) vbo_Indexf;
+ (void) vbo_Indexfv;
+}
+
+
+#endif /* FEATURE_beginend */
+
+
+/**
+ * Tell the VBO module to use a real OpenGL vertex buffer object to
+ * store accumulated immediate-mode vertex data.
+ * This replaces the malloced buffer which was created in
+ * vb_exec_vtx_init() below.
+ */
+void vbo_use_buffer_objects(struct gl_context *ctx)
+{
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+ /* Any buffer name but 0 can be used here since this bufferobj won't
+ * go into the bufferobj hashtable.
+ */
+ GLuint bufName = IMM_BUFFER_NAME;
+ GLenum target = GL_ARRAY_BUFFER_ARB;
+ GLenum usage = GL_STREAM_DRAW_ARB;
+ GLsizei size = VBO_VERT_BUFFER_SIZE;
+
+ /* Make sure this func is only used once */
+ assert(exec->vtx.bufferobj == ctx->Shared->NullBufferObj);
+ if (exec->vtx.buffer_map) {
+ _mesa_align_free(exec->vtx.buffer_map);
+ exec->vtx.buffer_map = NULL;
+ exec->vtx.buffer_ptr = NULL;
+ }
+
+ /* Allocate a real buffer object now */
+ _mesa_reference_buffer_object(ctx, &exec->vtx.bufferobj, NULL);
+ exec->vtx.bufferobj = ctx->Driver.NewBufferObject(ctx, bufName, target);
+ ctx->Driver.BufferData(ctx, target, size, NULL, usage, exec->vtx.bufferobj);
+}
+
+
+
+void vbo_exec_vtx_init( struct vbo_exec_context *exec )
+{
+ struct gl_context *ctx = exec->ctx;
+ struct vbo_context *vbo = vbo_context(ctx);
+ GLuint i;
+
+ /* Allocate a buffer object. Will just reuse this object
+ * continuously, unless vbo_use_buffer_objects() is called to enable
+ * use of real VBOs.
+ */
+ _mesa_reference_buffer_object(ctx,
+ &exec->vtx.bufferobj,
+ ctx->Shared->NullBufferObj);
+
+ ASSERT(!exec->vtx.buffer_map);
+ exec->vtx.buffer_map = (GLfloat *)_mesa_align_malloc(VBO_VERT_BUFFER_SIZE, 64);
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+
+ vbo_exec_vtxfmt_init( exec );
+
+ /* Hook our functions into the dispatch table.
+ */
+ _mesa_install_exec_vtxfmt( ctx, &exec->vtxfmt );
+
+ for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
+ ASSERT(i < Elements(exec->vtx.attrsz));
+ exec->vtx.attrsz[i] = 0;
+ ASSERT(i < Elements(exec->vtx.active_sz));
+ exec->vtx.active_sz[i] = 0;
+ }
+ for (i = 0 ; i < VERT_ATTRIB_MAX; i++) {
+ ASSERT(i < Elements(exec->vtx.inputs));
+ ASSERT(i < Elements(exec->vtx.arrays));
+ exec->vtx.inputs[i] = &exec->vtx.arrays[i];
+ }
+
+ {
+ struct gl_client_array *arrays = exec->vtx.arrays;
+ unsigned i;
+
+ memcpy(arrays, vbo->legacy_currval, 16 * sizeof(arrays[0]));
+ memcpy(arrays + 16, vbo->generic_currval, 16 * sizeof(arrays[0]));
+
+ for (i = 0; i < 16; ++i) {
+ arrays[i ].BufferObj = NULL;
+ arrays[i + 16].BufferObj = NULL;
+ _mesa_reference_buffer_object(ctx, &arrays[i ].BufferObj,
+ vbo->legacy_currval[i].BufferObj);
+ _mesa_reference_buffer_object(ctx, &arrays[i + 16].BufferObj,
+ vbo->generic_currval[i].BufferObj);
+ }
+ }
+
+ exec->vtx.vertex_size = 0;
+}
+
+
+void vbo_exec_vtx_destroy( struct vbo_exec_context *exec )
+{
+ /* using a real VBO for vertex data */
+ struct gl_context *ctx = exec->ctx;
+ unsigned i;
+
+ /* True VBOs should already be unmapped
+ */
+ if (exec->vtx.buffer_map) {
+ ASSERT(exec->vtx.bufferobj->Name == 0 ||
+ exec->vtx.bufferobj->Name == IMM_BUFFER_NAME);
+ if (exec->vtx.bufferobj->Name == 0) {
+ _mesa_align_free(exec->vtx.buffer_map);
+ exec->vtx.buffer_map = NULL;
+ exec->vtx.buffer_ptr = NULL;
+ }
+ }
+
+ /* Drop any outstanding reference to the vertex buffer
+ */
+ for (i = 0; i < Elements(exec->vtx.arrays); i++) {
+ _mesa_reference_buffer_object(ctx,
+ &exec->vtx.arrays[i].BufferObj,
+ NULL);
+ }
+
+ /* Free the vertex buffer. Unmap first if needed.
+ */
+ if (_mesa_bufferobj_mapped(exec->vtx.bufferobj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER, exec->vtx.bufferobj);
+ }
+ _mesa_reference_buffer_object(ctx, &exec->vtx.bufferobj, NULL);
+}
+
+
+/**
+ * Called upon first glVertex, glColor, glTexCoord, etc.
+ */
+void vbo_exec_BeginVertices( struct gl_context *ctx )
+{
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+
+ vbo_exec_vtx_map( exec );
+
+ assert((ctx->Driver.NeedFlush & FLUSH_UPDATE_CURRENT) == 0);
+ ctx->Driver.NeedFlush |= FLUSH_UPDATE_CURRENT;
+}
+
+
+/**
+ * Called via ctx->Driver.FlushVertices()
+ * \param flags bitmask of FLUSH_STORED_VERTICES, FLUSH_UPDATE_CURRENT
+ */
+void vbo_exec_FlushVertices( struct gl_context *ctx, GLuint flags )
+{
+ struct vbo_exec_context *exec = &vbo_context(ctx)->exec;
+
+#ifdef DEBUG
+ /* debug check: make sure we don't get called recursively */
+ exec->flush_call_depth++;
+ assert(exec->flush_call_depth == 1);
+#endif
+
+ if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END) {
+ /* We've had glBegin but not glEnd! */
+#ifdef DEBUG
+ exec->flush_call_depth--;
+ assert(exec->flush_call_depth == 0);
+#endif
+ return;
+ }
+
+ /* Flush (draw), and make sure VBO is left unmapped when done */
+ vbo_exec_FlushVertices_internal(exec, GL_TRUE);
+
+ /* Need to do this to ensure BeginVertices gets called again:
+ */
+ ctx->Driver.NeedFlush &= ~(FLUSH_UPDATE_CURRENT | flags);
+
+#ifdef DEBUG
+ exec->flush_call_depth--;
+ assert(exec->flush_call_depth == 0);
+#endif
+}
+
+
+static void reset_attrfv( struct vbo_exec_context *exec )
+{
+ GLuint i;
+
+ for (i = 0 ; i < VBO_ATTRIB_MAX ; i++) {
+ exec->vtx.attrsz[i] = 0;
+ exec->vtx.active_sz[i] = 0;
+ }
+
+ exec->vtx.vertex_size = 0;
+}
+
+
+void GLAPIENTRY
+_es_Color4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a)
+{
+ vbo_Color4f(r, g, b, a);
+}
+
+
+void GLAPIENTRY
+_es_Normal3f(GLfloat x, GLfloat y, GLfloat z)
+{
+ vbo_Normal3f(x, y, z);
+}
+
+
+void GLAPIENTRY
+_es_MultiTexCoord4f(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q)
+{
+ vbo_MultiTexCoord4f(target, s, t, r, q);
+}
+
+
+void GLAPIENTRY
+_es_Materialfv(GLenum face, GLenum pname, const GLfloat *params)
+{
+ vbo_Materialfv(face, pname, params);
+}
+
+
+void GLAPIENTRY
+_es_Materialf(GLenum face, GLenum pname, GLfloat param)
+{
+ GLfloat p[4];
+ p[0] = param;
+ p[1] = p[2] = p[3] = 0.0F;
+ vbo_Materialfv(face, pname, p);
+}
+
+
+/**
+ * A special version of glVertexAttrib4f that does not treat index 0 as
+ * VBO_ATTRIB_POS.
+ */
+static void
+VertexAttrib4f_nopos(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ if (index < MAX_VERTEX_GENERIC_ATTRIBS)
+ ATTR(VBO_ATTRIB_GENERIC0 + index, 4, x, y, z, w);
+ else
+ ERROR();
+}
+
+void GLAPIENTRY
+_es_VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w)
+{
+ VertexAttrib4f_nopos(index, x, y, z, w);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib1f(GLuint indx, GLfloat x)
+{
+ VertexAttrib4f_nopos(indx, x, 0.0f, 0.0f, 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib1fv(GLuint indx, const GLfloat* values)
+{
+ VertexAttrib4f_nopos(indx, values[0], 0.0f, 0.0f, 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib2f(GLuint indx, GLfloat x, GLfloat y)
+{
+ VertexAttrib4f_nopos(indx, x, y, 0.0f, 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib2fv(GLuint indx, const GLfloat* values)
+{
+ VertexAttrib4f_nopos(indx, values[0], values[1], 0.0f, 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib3f(GLuint indx, GLfloat x, GLfloat y, GLfloat z)
+{
+ VertexAttrib4f_nopos(indx, x, y, z, 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib3fv(GLuint indx, const GLfloat* values)
+{
+ VertexAttrib4f_nopos(indx, values[0], values[1], values[2], 1.0f);
+}
+
+
+void GLAPIENTRY
+_es_VertexAttrib4fv(GLuint indx, const GLfloat* values)
+{
+ VertexAttrib4f_nopos(indx, values[0], values[1], values[2], values[3]);
+}
diff --git a/mesalib/src/mesa/vbo/vbo_exec_array.c b/mesalib/src/mesa/vbo/vbo_exec_array.c
index 457343a1a..1d7fe4d3f 100644
--- a/mesalib/src/mesa/vbo/vbo_exec_array.c
+++ b/mesalib/src/mesa/vbo/vbo_exec_array.c
@@ -1,1324 +1,1324 @@
-/**************************************************************************
- *
- * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
- * Copyright 2009 VMware, Inc.
- * 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, sub license, 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 (including the
- * next paragraph) 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 NON-INFRINGEMENT.
- * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
- *
- **************************************************************************/
-
-#include "main/glheader.h"
-#include "main/context.h"
-#include "main/state.h"
-#include "main/api_validate.h"
-#include "main/varray.h"
-#include "main/bufferobj.h"
-#include "main/enums.h"
-#include "main/macros.h"
-
-#include "vbo_context.h"
-
-
-/**
- * All vertex buffers should be in an unmapped state when we're about
- * to draw. This debug function checks that.
- */
-static void
-check_buffers_are_unmapped(const struct gl_client_array **inputs)
-{
-#ifdef DEBUG
- GLuint i;
-
- for (i = 0; i < VERT_ATTRIB_MAX; i++) {
- if (inputs[i]) {
- struct gl_buffer_object *obj = inputs[i]->BufferObj;
- assert(!_mesa_bufferobj_mapped(obj));
- }
- }
-#endif
-}
-
-
-/**
- * A debug function that may be called from other parts of Mesa as
- * needed during debugging.
- */
-void
-vbo_check_buffers_are_unmapped(struct gl_context *ctx)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- /* check the current vertex arrays */
- check_buffers_are_unmapped(exec->array.inputs);
- /* check the current glBegin/glVertex/glEnd-style VBO */
- assert(!_mesa_bufferobj_mapped(exec->vtx.bufferobj));
-}
-
-
-
-/**
- * Compute min and max elements by scanning the index buffer for
- * glDraw[Range]Elements() calls.
- * If primitive restart is enabled, we need to ignore restart
- * indexes when computing min/max.
- */
-void
-vbo_get_minmax_index(struct gl_context *ctx,
- const struct _mesa_prim *prim,
- const struct _mesa_index_buffer *ib,
- GLuint *min_index, GLuint *max_index)
-{
- const GLboolean restart = ctx->Array.PrimitiveRestart;
- const GLuint restartIndex = ctx->Array.RestartIndex;
- const GLuint count = prim->count;
- const void *indices;
- GLuint i;
-
- if (_mesa_is_bufferobj(ib->obj)) {
- const GLvoid *map =
- ctx->Driver.MapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
- GL_READ_ONLY, ib->obj);
- indices = ADD_POINTERS(map, ib->ptr);
- } else {
- indices = ib->ptr;
- }
-
- switch (ib->type) {
- case GL_UNSIGNED_INT: {
- const GLuint *ui_indices = (const GLuint *)indices;
- GLuint max_ui = 0;
- GLuint min_ui = ~0U;
- if (restart) {
- for (i = 0; i < count; i++) {
- if (ui_indices[i] != restartIndex) {
- if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
- if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
- }
- }
- }
- else {
- for (i = 0; i < count; i++) {
- if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
- if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
- }
- }
- *min_index = min_ui;
- *max_index = max_ui;
- break;
- }
- case GL_UNSIGNED_SHORT: {
- const GLushort *us_indices = (const GLushort *)indices;
- GLuint max_us = 0;
- GLuint min_us = ~0U;
- if (restart) {
- for (i = 0; i < count; i++) {
- if (us_indices[i] != restartIndex) {
- if (us_indices[i] > max_us) max_us = us_indices[i];
- if (us_indices[i] < min_us) min_us = us_indices[i];
- }
- }
- }
- else {
- for (i = 0; i < count; i++) {
- if (us_indices[i] > max_us) max_us = us_indices[i];
- if (us_indices[i] < min_us) min_us = us_indices[i];
- }
- }
- *min_index = min_us;
- *max_index = max_us;
- break;
- }
- case GL_UNSIGNED_BYTE: {
- const GLubyte *ub_indices = (const GLubyte *)indices;
- GLuint max_ub = 0;
- GLuint min_ub = ~0U;
- if (restart) {
- for (i = 0; i < count; i++) {
- if (ub_indices[i] != restartIndex) {
- if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
- if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
- }
- }
- }
- else {
- for (i = 0; i < count; i++) {
- if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
- if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
- }
- }
- *min_index = min_ub;
- *max_index = max_ub;
- break;
- }
- default:
- assert(0);
- break;
- }
-
- if (_mesa_is_bufferobj(ib->obj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB, ib->obj);
- }
-}
-
-
-/**
- * Check that element 'j' of the array has reasonable data.
- * Map VBO if needed.
- * For debugging purposes; not normally used.
- */
-static void
-check_array_data(struct gl_context *ctx, struct gl_client_array *array,
- GLuint attrib, GLuint j)
-{
- if (array->Enabled) {
- const void *data = array->Ptr;
- if (_mesa_is_bufferobj(array->BufferObj)) {
- if (!array->BufferObj->Pointer) {
- /* need to map now */
- array->BufferObj->Pointer =
- ctx->Driver.MapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
- GL_READ_ONLY, array->BufferObj);
- }
- data = ADD_POINTERS(data, array->BufferObj->Pointer);
- }
- switch (array->Type) {
- case GL_FLOAT:
- {
- GLfloat *f = (GLfloat *) ((GLubyte *) data + array->StrideB * j);
- GLint k;
- for (k = 0; k < array->Size; k++) {
- if (IS_INF_OR_NAN(f[k]) ||
- f[k] >= 1.0e20 || f[k] <= -1.0e10) {
- printf("Bad array data:\n");
- printf(" Element[%u].%u = %f\n", j, k, f[k]);
- printf(" Array %u at %p\n", attrib, (void* ) array);
- printf(" Type 0x%x, Size %d, Stride %d\n",
- array->Type, array->Size, array->Stride);
- printf(" Address/offset %p in Buffer Object %u\n",
- array->Ptr, array->BufferObj->Name);
- f[k] = 1.0; /* XXX replace the bad value! */
- }
- /*assert(!IS_INF_OR_NAN(f[k]));*/
- }
- }
- break;
- default:
- ;
- }
- }
-}
-
-
-/**
- * Unmap the buffer object referenced by given array, if mapped.
- */
-static void
-unmap_array_buffer(struct gl_context *ctx, struct gl_client_array *array)
-{
- if (array->Enabled &&
- _mesa_is_bufferobj(array->BufferObj) &&
- _mesa_bufferobj_mapped(array->BufferObj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB, array->BufferObj);
- }
-}
-
-
-/**
- * Examine the array's data for NaNs, etc.
- * For debug purposes; not normally used.
- */
-static void
-check_draw_elements_data(struct gl_context *ctx, GLsizei count, GLenum elemType,
- const void *elements, GLint basevertex)
-{
- struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
- const void *elemMap;
- GLint i, k;
-
- if (_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj)) {
- elemMap = ctx->Driver.MapBuffer(ctx,
- GL_ELEMENT_ARRAY_BUFFER_ARB,
- GL_READ_ONLY,
- ctx->Array.ElementArrayBufferObj);
- elements = ADD_POINTERS(elements, elemMap);
- }
-
- for (i = 0; i < count; i++) {
- GLuint j;
-
- /* j = element[i] */
- switch (elemType) {
- case GL_UNSIGNED_BYTE:
- j = ((const GLubyte *) elements)[i];
- break;
- case GL_UNSIGNED_SHORT:
- j = ((const GLushort *) elements)[i];
- break;
- case GL_UNSIGNED_INT:
- j = ((const GLuint *) elements)[i];
- break;
- default:
- assert(0);
- }
-
- /* check element j of each enabled array */
- check_array_data(ctx, &arrayObj->Vertex, VERT_ATTRIB_POS, j);
- check_array_data(ctx, &arrayObj->Normal, VERT_ATTRIB_NORMAL, j);
- check_array_data(ctx, &arrayObj->Color, VERT_ATTRIB_COLOR0, j);
- check_array_data(ctx, &arrayObj->SecondaryColor, VERT_ATTRIB_COLOR1, j);
- for (k = 0; k < Elements(arrayObj->TexCoord); k++) {
- check_array_data(ctx, &arrayObj->TexCoord[k], VERT_ATTRIB_TEX0 + k, j);
- }
- for (k = 0; k < Elements(arrayObj->VertexAttrib); k++) {
- check_array_data(ctx, &arrayObj->VertexAttrib[k],
- VERT_ATTRIB_GENERIC0 + k, j);
- }
- }
-
- if (_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj)) {
- ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
- ctx->Array.ElementArrayBufferObj);
- }
-
- unmap_array_buffer(ctx, &arrayObj->Vertex);
- unmap_array_buffer(ctx, &arrayObj->Normal);
- unmap_array_buffer(ctx, &arrayObj->Color);
- for (k = 0; k < Elements(arrayObj->TexCoord); k++) {
- unmap_array_buffer(ctx, &arrayObj->TexCoord[k]);
- }
- for (k = 0; k < Elements(arrayObj->VertexAttrib); k++) {
- unmap_array_buffer(ctx, &arrayObj->VertexAttrib[k]);
- }
-}
-
-
-/**
- * Check array data, looking for NaNs, etc.
- */
-static void
-check_draw_arrays_data(struct gl_context *ctx, GLint start, GLsizei count)
-{
- /* TO DO */
-}
-
-
-/**
- * Print info/data for glDrawArrays(), for debugging.
- */
-static void
-print_draw_arrays(struct gl_context *ctx,
- GLenum mode, GLint start, GLsizei count)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- int i;
-
- printf("vbo_exec_DrawArrays(mode 0x%x, start %d, count %d):\n",
- mode, start, count);
-
- for (i = 0; i < 32; i++) {
- GLuint bufName = exec->array.inputs[i]->BufferObj->Name;
- GLint stride = exec->array.inputs[i]->Stride;
- printf("attr %2d: size %d stride %d enabled %d "
- "ptr %p Bufobj %u\n",
- i,
- exec->array.inputs[i]->Size,
- stride,
- /*exec->array.inputs[i]->Enabled,*/
- exec->array.legacy_array[i]->Enabled,
- exec->array.inputs[i]->Ptr,
- bufName);
-
- if (bufName) {
- struct gl_buffer_object *buf = _mesa_lookup_bufferobj(ctx, bufName);
- GLubyte *p = ctx->Driver.MapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
- GL_READ_ONLY_ARB, buf);
- int offset = (int) (GLintptr) exec->array.inputs[i]->Ptr;
- float *f = (float *) (p + offset);
- int *k = (int *) f;
- int i;
- int n = (count * stride) / 4;
- if (n > 32)
- n = 32;
- printf(" Data at offset %d:\n", offset);
- for (i = 0; i < n; i++) {
- printf(" float[%d] = 0x%08x %f\n", i, k[i], f[i]);
- }
- ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB, buf);
- }
- }
-}
-
-
-/**
- * Bind the VBO executor to the current vertex array object prior
- * to drawing.
- *
- * Just translate the arrayobj into a sane layout.
- */
-static void
-bind_array_obj(struct gl_context *ctx)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
- GLuint i;
-
- /* TODO: Fix the ArrayObj struct to keep legacy arrays in an array
- * rather than as individual named arrays. Then this function can
- * go away.
- */
- exec->array.legacy_array[VERT_ATTRIB_POS] = &arrayObj->Vertex;
- exec->array.legacy_array[VERT_ATTRIB_WEIGHT] = &arrayObj->Weight;
- exec->array.legacy_array[VERT_ATTRIB_NORMAL] = &arrayObj->Normal;
- exec->array.legacy_array[VERT_ATTRIB_COLOR0] = &arrayObj->Color;
- exec->array.legacy_array[VERT_ATTRIB_COLOR1] = &arrayObj->SecondaryColor;
- exec->array.legacy_array[VERT_ATTRIB_FOG] = &arrayObj->FogCoord;
- exec->array.legacy_array[VERT_ATTRIB_COLOR_INDEX] = &arrayObj->Index;
- if (arrayObj->PointSize.Enabled) {
- /* this aliases COLOR_INDEX */
- exec->array.legacy_array[VERT_ATTRIB_POINT_SIZE] = &arrayObj->PointSize;
- }
- exec->array.legacy_array[VERT_ATTRIB_EDGEFLAG] = &arrayObj->EdgeFlag;
-
- for (i = 0; i < Elements(arrayObj->TexCoord); i++)
- exec->array.legacy_array[VERT_ATTRIB_TEX0 + i] = &arrayObj->TexCoord[i];
-
- for (i = 0; i < Elements(arrayObj->VertexAttrib); i++) {
- assert(i < Elements(exec->array.generic_array));
- exec->array.generic_array[i] = &arrayObj->VertexAttrib[i];
- }
-
- exec->array.array_obj = arrayObj->Name;
-}
-
-
-/**
- * Set the vbo->exec->inputs[] pointers to point to the enabled
- * vertex arrays. This depends on the current vertex program/shader
- * being executed because of whether or not generic vertex arrays
- * alias the conventional vertex arrays.
- * For arrays that aren't enabled, we set the input[attrib] pointer
- * to point at a zero-stride current value "array".
- */
-static void
-recalculate_input_bindings(struct gl_context *ctx)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- const struct gl_client_array **inputs = &exec->array.inputs[0];
- GLbitfield const_inputs = 0x0;
- GLuint i;
-
- exec->array.program_mode = get_program_mode(ctx);
- exec->array.enabled_flags = ctx->Array.ArrayObj->_Enabled;
-
- switch (exec->array.program_mode) {
- case VP_NONE:
- /* When no vertex program is active (or the vertex program is generated
- * from fixed-function state). We put the material values into the
- * generic slots. This is the only situation where material values
- * are available as per-vertex attributes.
- */
- for (i = 0; i <= VERT_ATTRIB_TEX7; i++) {
- if (exec->array.legacy_array[i]->Enabled)
- inputs[i] = exec->array.legacy_array[i];
- else {
- inputs[i] = &vbo->legacy_currval[i];
- const_inputs |= 1 << i;
- }
- }
-
- for (i = 0; i < MAT_ATTRIB_MAX; i++) {
- inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->mat_currval[i];
- const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
- }
-
- /* Could use just about anything, just to fill in the empty
- * slots:
- */
- for (i = MAT_ATTRIB_MAX; i < VERT_ATTRIB_MAX - VERT_ATTRIB_GENERIC0; i++) {
- inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->generic_currval[i];
- const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
- }
- break;
-
- case VP_NV:
- /* NV_vertex_program - attribute arrays alias and override
- * conventional, legacy arrays. No materials, and the generic
- * slots are vacant.
- */
- for (i = 0; i <= VERT_ATTRIB_TEX7; i++) {
- if (exec->array.generic_array[i]->Enabled)
- inputs[i] = exec->array.generic_array[i];
- else if (exec->array.legacy_array[i]->Enabled)
- inputs[i] = exec->array.legacy_array[i];
- else {
- inputs[i] = &vbo->legacy_currval[i];
- const_inputs |= 1 << i;
- }
- }
-
- /* Could use just about anything, just to fill in the empty
- * slots:
- */
- for (i = VERT_ATTRIB_GENERIC0; i < VERT_ATTRIB_MAX; i++) {
- inputs[i] = &vbo->generic_currval[i - VERT_ATTRIB_GENERIC0];
- const_inputs |= 1 << i;
- }
- break;
-
- case VP_ARB:
- /* GL_ARB_vertex_program or GLSL vertex shader - Only the generic[0]
- * attribute array aliases and overrides the legacy position array.
- *
- * Otherwise, legacy attributes available in the legacy slots,
- * generic attributes in the generic slots and materials are not
- * available as per-vertex attributes.
- */
- if (exec->array.generic_array[0]->Enabled)
- inputs[0] = exec->array.generic_array[0];
- else if (exec->array.legacy_array[0]->Enabled)
- inputs[0] = exec->array.legacy_array[0];
- else {
- inputs[0] = &vbo->legacy_currval[0];
- const_inputs |= 1 << 0;
- }
-
- for (i = 1; i <= VERT_ATTRIB_TEX7; i++) {
- if (exec->array.legacy_array[i]->Enabled)
- inputs[i] = exec->array.legacy_array[i];
- else {
- inputs[i] = &vbo->legacy_currval[i];
- const_inputs |= 1 << i;
- }
- }
-
- for (i = 0; i < MAX_VERTEX_GENERIC_ATTRIBS; i++) {
- if (exec->array.generic_array[i]->Enabled)
- inputs[VERT_ATTRIB_GENERIC0 + i] = exec->array.generic_array[i];
- else {
- inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->generic_currval[i];
- const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
- }
-
- }
- break;
- }
-
- _mesa_set_varying_vp_inputs( ctx, ~const_inputs );
-}
-
-
-/**
- * Examine the enabled vertex arrays to set the exec->array.inputs[] values.
- * These will point to the arrays to actually use for drawing. Some will
- * be user-provided arrays, other will be zero-stride const-valued arrays.
- * Note that this might set the _NEW_ARRAY dirty flag so state validation
- * must be done after this call.
- */
-static void
-bind_arrays(struct gl_context *ctx)
-{
- if (!ctx->Array.RebindArrays) {
- return;
- }
-
- bind_array_obj(ctx);
- recalculate_input_bindings(ctx);
- ctx->Array.RebindArrays = GL_FALSE;
-}
-
-
-/**
- * Helper function called by the other DrawArrays() functions below.
- * This is where we handle primitive restart for drawing non-indexed
- * arrays. If primitive restart is enabled, it typically means
- * splitting one DrawArrays() into two.
- */
-static void
-vbo_draw_arrays(struct gl_context *ctx, GLenum mode, GLint start,
- GLsizei count, GLuint numInstances)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- struct _mesa_prim prim[2];
-
- bind_arrays(ctx);
-
- /* Again... because we may have changed the bitmask of per-vertex varying
- * attributes. If we regenerate the fixed-function vertex program now
- * we may be able to prune down the number of vertex attributes which we
- * need in the shader.
- */
- if (ctx->NewState)
- _mesa_update_state(ctx);
-
- prim[0].begin = 1;
- prim[0].end = 1;
- prim[0].weak = 0;
- prim[0].pad = 0;
- prim[0].mode = mode;
- prim[0].start = 0; /* filled in below */
- prim[0].count = 0; /* filled in below */
- prim[0].indexed = 0;
- prim[0].basevertex = 0;
- prim[0].num_instances = numInstances;
-
- /* Implement the primitive restart index */
- if (ctx->Array.PrimitiveRestart && ctx->Array.RestartIndex < count) {
- GLuint primCount = 0;
-
- if (ctx->Array.RestartIndex == start) {
- /* special case: RestartIndex at beginning */
- if (count > 1) {
- prim[0].start = start + 1;
- prim[0].count = count - 1;
- primCount = 1;
- }
- }
- else if (ctx->Array.RestartIndex == start + count - 1) {
- /* special case: RestartIndex at end */
- if (count > 1) {
- prim[0].start = start;
- prim[0].count = count - 1;
- primCount = 1;
- }
- }
- else {
- /* general case: RestartIndex in middle, split into two prims */
- prim[0].start = start;
- prim[0].count = ctx->Array.RestartIndex - start;
-
- prim[1] = prim[0];
- prim[1].start = ctx->Array.RestartIndex + 1;
- prim[1].count = count - prim[1].start;
-
- primCount = 2;
- }
-
- if (primCount > 0) {
- /* draw one or two prims */
- check_buffers_are_unmapped(exec->array.inputs);
- vbo->draw_prims(ctx, exec->array.inputs, prim, primCount, NULL,
- GL_TRUE, start, start + count - 1);
- }
- }
- else {
- /* no prim restart */
- prim[0].start = start;
- prim[0].count = count;
-
- check_buffers_are_unmapped(exec->array.inputs);
- vbo->draw_prims(ctx, exec->array.inputs, prim, 1, NULL,
- GL_TRUE, start, start + count - 1);
- }
-}
-
-
-
-/**
- * Called from glDrawArrays when in immediate mode (not display list mode).
- */
-static void GLAPIENTRY
-vbo_exec_DrawArrays(GLenum mode, GLint start, GLsizei count)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx, "glDrawArrays(%s, %d, %d)\n",
- _mesa_lookup_enum_by_nr(mode), start, count);
-
- if (!_mesa_validate_DrawArrays( ctx, mode, start, count ))
- return;
-
- FLUSH_CURRENT( ctx, 0 );
-
- if (!_mesa_valid_to_render(ctx, "glDrawArrays")) {
- return;
- }
-
- if (0)
- check_draw_arrays_data(ctx, start, count);
-
- vbo_draw_arrays(ctx, mode, start, count, 1);
-
- if (0)
- print_draw_arrays(ctx, mode, start, count);
-}
-
-
-/**
- * Called from glDrawArraysInstanced when in immediate mode (not
- * display list mode).
- */
-static void GLAPIENTRY
-vbo_exec_DrawArraysInstanced(GLenum mode, GLint start, GLsizei count,
- GLsizei numInstances)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx, "glDrawArraysInstanced(%s, %d, %d, %d)\n",
- _mesa_lookup_enum_by_nr(mode), start, count, numInstances);
-
- if (!_mesa_validate_DrawArraysInstanced(ctx, mode, start, count, numInstances))
- return;
-
- FLUSH_CURRENT( ctx, 0 );
-
- if (!_mesa_valid_to_render(ctx, "glDrawArraysInstanced")) {
- return;
- }
-
- if (0)
- check_draw_arrays_data(ctx, start, count);
-
- vbo_draw_arrays(ctx, mode, start, count, numInstances);
-
- if (0)
- print_draw_arrays(ctx, mode, start, count);
-}
-
-
-/**
- * Map GL_ELEMENT_ARRAY_BUFFER and print contents.
- * For debugging.
- */
-static void
-dump_element_buffer(struct gl_context *ctx, GLenum type)
-{
- const GLvoid *map = ctx->Driver.MapBuffer(ctx,
- GL_ELEMENT_ARRAY_BUFFER_ARB,
- GL_READ_ONLY,
- ctx->Array.ElementArrayBufferObj);
- switch (type) {
- case GL_UNSIGNED_BYTE:
- {
- const GLubyte *us = (const GLubyte *) map;
- GLint i;
- for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size; i++) {
- printf("%02x ", us[i]);
- if (i % 32 == 31)
- printf("\n");
- }
- printf("\n");
- }
- break;
- case GL_UNSIGNED_SHORT:
- {
- const GLushort *us = (const GLushort *) map;
- GLint i;
- for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size / 2; i++) {
- printf("%04x ", us[i]);
- if (i % 16 == 15)
- printf("\n");
- }
- printf("\n");
- }
- break;
- case GL_UNSIGNED_INT:
- {
- const GLuint *us = (const GLuint *) map;
- GLint i;
- for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size / 4; i++) {
- printf("%08x ", us[i]);
- if (i % 8 == 7)
- printf("\n");
- }
- printf("\n");
- }
- break;
- default:
- ;
- }
-
- ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
- ctx->Array.ElementArrayBufferObj);
-}
-
-
-/**
- * Inner support for both _mesa_DrawElements and _mesa_DrawRangeElements.
- * Do the rendering for a glDrawElements or glDrawRangeElements call after
- * we've validated buffer bounds, etc.
- */
-static void
-vbo_validated_drawrangeelements(struct gl_context *ctx, GLenum mode,
- GLboolean index_bounds_valid,
- GLuint start, GLuint end,
- GLsizei count, GLenum type,
- const GLvoid *indices,
- GLint basevertex, GLint numInstances)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- struct _mesa_index_buffer ib;
- struct _mesa_prim prim[1];
-
- FLUSH_CURRENT( ctx, 0 );
-
- if (!_mesa_valid_to_render(ctx, "glDraw[Range]Elements")) {
- return;
- }
-
- bind_arrays( ctx );
-
- /* check for dirty state again */
- if (ctx->NewState)
- _mesa_update_state( ctx );
-
- ib.count = count;
- ib.type = type;
- ib.obj = ctx->Array.ElementArrayBufferObj;
- ib.ptr = indices;
-
- prim[0].begin = 1;
- prim[0].end = 1;
- prim[0].weak = 0;
- prim[0].pad = 0;
- prim[0].mode = mode;
- prim[0].start = 0;
- prim[0].count = count;
- prim[0].indexed = 1;
- prim[0].basevertex = basevertex;
- prim[0].num_instances = numInstances;
-
- /* Need to give special consideration to rendering a range of
- * indices starting somewhere above zero. Typically the
- * application is issuing multiple DrawRangeElements() to draw
- * successive primitives layed out linearly in the vertex arrays.
- * Unless the vertex arrays are all in a VBO (or locked as with
- * CVA), the OpenGL semantics imply that we need to re-read or
- * re-upload the vertex data on each draw call.
- *
- * In the case of hardware tnl, we want to avoid starting the
- * upload at zero, as it will mean every draw call uploads an
- * increasing amount of not-used vertex data. Worse - in the
- * software tnl module, all those vertices might be transformed and
- * lit but never rendered.
- *
- * If we just upload or transform the vertices in start..end,
- * however, the indices will be incorrect.
- *
- * At this level, we don't know exactly what the requirements of
- * the backend are going to be, though it will likely boil down to
- * either:
- *
- * 1) Do nothing, everything is in a VBO and is processed once
- * only.
- *
- * 2) Adjust the indices and vertex arrays so that start becomes
- * zero.
- *
- * Rather than doing anything here, I'll provide a helper function
- * for the latter case elsewhere.
- */
-
- check_buffers_are_unmapped(exec->array.inputs);
- vbo->draw_prims( ctx, exec->array.inputs, prim, 1, &ib,
- index_bounds_valid, start, end );
-}
-
-
-/**
- * Called by glDrawRangeElementsBaseVertex() in immediate mode.
- */
-static void GLAPIENTRY
-vbo_exec_DrawRangeElementsBaseVertex(GLenum mode,
- GLuint start, GLuint end,
- GLsizei count, GLenum type,
- const GLvoid *indices,
- GLint basevertex)
-{
- static GLuint warnCount = 0;
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx,
- "glDrawRangeElementsBaseVertex(%s, %u, %u, %d, %s, %p, %d)\n",
- _mesa_lookup_enum_by_nr(mode), start, end, count,
- _mesa_lookup_enum_by_nr(type), indices, basevertex);
-
- if (!_mesa_validate_DrawRangeElements( ctx, mode, start, end, count,
- type, indices, basevertex ))
- return;
-
- /* NOTE: It's important that 'end' is a reasonable value.
- * in _tnl_draw_prims(), we use end to determine how many vertices
- * to transform. If it's too large, we can unnecessarily split prims
- * or we can read/write out of memory in several different places!
- */
-
- /* Catch/fix some potential user errors */
- if (type == GL_UNSIGNED_BYTE) {
- start = MIN2(start, 0xff);
- end = MIN2(end, 0xff);
- }
- else if (type == GL_UNSIGNED_SHORT) {
- start = MIN2(start, 0xffff);
- end = MIN2(end, 0xffff);
- }
-
- if (end >= ctx->Array.ArrayObj->_MaxElement) {
- /* the max element is out of bounds of one or more enabled arrays */
- warnCount++;
-
- if (warnCount < 10) {
- _mesa_warning(ctx, "glDraw[Range]Elements(start %u, end %u, count %d, "
- "type 0x%x, indices=%p)\n"
- "\tend is out of bounds (max=%u) "
- "Element Buffer %u (size %d)\n"
- "\tThis should probably be fixed in the application.",
- start, end, count, type, indices,
- ctx->Array.ArrayObj->_MaxElement - 1,
- ctx->Array.ElementArrayBufferObj->Name,
- (int) ctx->Array.ElementArrayBufferObj->Size);
- }
-
- if (0)
- dump_element_buffer(ctx, type);
-
- if (0)
- _mesa_print_arrays(ctx);
-
-#ifdef DEBUG
- /* 'end' was out of bounds, but now let's check the actual array
- * indexes to see if any of them are out of bounds.
- */
- {
- GLuint max = _mesa_max_buffer_index(ctx, count, type, indices,
- ctx->Array.ElementArrayBufferObj);
- if (max >= ctx->Array.ArrayObj->_MaxElement) {
- if (warnCount < 10) {
- _mesa_warning(ctx, "glDraw[Range]Elements(start %u, end %u, "
- "count %d, type 0x%x, indices=%p)\n"
- "\tindex=%u is out of bounds (max=%u) "
- "Element Buffer %u (size %d)\n"
- "\tSkipping the glDrawRangeElements() call",
- start, end, count, type, indices, max,
- ctx->Array.ArrayObj->_MaxElement - 1,
- ctx->Array.ElementArrayBufferObj->Name,
- (int) ctx->Array.ElementArrayBufferObj->Size);
- }
- }
- /* XXX we could also find the min index and compare to 'start'
- * to see if start is correct. But it's more likely to get the
- * upper bound wrong.
- */
- }
-#endif
-
- /* Set 'end' to the max possible legal value */
- assert(ctx->Array.ArrayObj->_MaxElement >= 1);
- end = ctx->Array.ArrayObj->_MaxElement - 1;
- }
- else if (0) {
- printf("glDraw[Range]Elements{,BaseVertex}"
- "(start %u, end %u, type 0x%x, count %d) ElemBuf %u, "
- "base %d\n",
- start, end, type, count,
- ctx->Array.ElementArrayBufferObj->Name,
- basevertex);
- }
-
-#if 0
- check_draw_elements_data(ctx, count, type, indices);
-#else
- (void) check_draw_elements_data;
-#endif
-
- vbo_validated_drawrangeelements(ctx, mode, GL_TRUE, start, end,
- count, type, indices, basevertex, 1);
-}
-
-
-/**
- * Called by glDrawRangeElements() in immediate mode.
- */
-static void GLAPIENTRY
-vbo_exec_DrawRangeElements(GLenum mode, GLuint start, GLuint end,
- GLsizei count, GLenum type, const GLvoid *indices)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx,
- "glDrawRangeElements(%s, %u, %u, %d, %s, %p)\n",
- _mesa_lookup_enum_by_nr(mode), start, end, count,
- _mesa_lookup_enum_by_nr(type), indices);
-
- vbo_exec_DrawRangeElementsBaseVertex(mode, start, end, count, type,
- indices, 0);
-}
-
-
-/**
- * Called by glDrawElements() in immediate mode.
- */
-static void GLAPIENTRY
-vbo_exec_DrawElements(GLenum mode, GLsizei count, GLenum type,
- const GLvoid *indices)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx, "glDrawElements(%s, %u, %s, %p)\n",
- _mesa_lookup_enum_by_nr(mode), count,
- _mesa_lookup_enum_by_nr(type), indices);
-
- if (!_mesa_validate_DrawElements( ctx, mode, count, type, indices, 0 ))
- return;
-
- vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
- count, type, indices, 0, 1);
-}
-
-
-/**
- * Called by glDrawElementsBaseVertex() in immediate mode.
- */
-static void GLAPIENTRY
-vbo_exec_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
- const GLvoid *indices, GLint basevertex)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx, "glDrawElementsBaseVertex(%s, %d, %s, %p, %d)\n",
- _mesa_lookup_enum_by_nr(mode), count,
- _mesa_lookup_enum_by_nr(type), indices, basevertex);
-
- if (!_mesa_validate_DrawElements( ctx, mode, count, type, indices,
- basevertex ))
- return;
-
- vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
- count, type, indices, basevertex, 1);
-}
-
-
-/**
- * Called by glDrawElementsInstanced() in immediate mode.
- */
-static void GLAPIENTRY
-vbo_exec_DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type,
- const GLvoid *indices, GLsizei numInstances)
-{
- GET_CURRENT_CONTEXT(ctx);
-
- if (MESA_VERBOSE & VERBOSE_DRAW)
- _mesa_debug(ctx, "glDrawElementsInstanced(%s, %d, %s, %p, %d)\n",
- _mesa_lookup_enum_by_nr(mode), count,
- _mesa_lookup_enum_by_nr(type), indices, numInstances);
-
- if (!_mesa_validate_DrawElementsInstanced(ctx, mode, count, type, indices,
- numInstances))
- return;
-
- vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
- count, type, indices, 0, numInstances);
-}
-
-
-/**
- * Inner support for both _mesa_MultiDrawElements() and
- * _mesa_MultiDrawRangeElements().
- * This does the actual rendering after we've checked array indexes, etc.
- */
-static void
-vbo_validated_multidrawelements(struct gl_context *ctx, GLenum mode,
- const GLsizei *count, GLenum type,
- const GLvoid **indices, GLsizei primcount,
- const GLint *basevertex)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- struct _mesa_index_buffer ib;
- struct _mesa_prim *prim;
- unsigned int index_type_size = 0;
- uintptr_t min_index_ptr, max_index_ptr;
- GLboolean fallback = GL_FALSE;
- int i;
-
- if (primcount == 0)
- return;
-
- FLUSH_CURRENT( ctx, 0 );
-
- if (!_mesa_valid_to_render(ctx, "glMultiDrawElements")) {
- return;
- }
-
- prim = calloc(1, primcount * sizeof(*prim));
- if (prim == NULL) {
- _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMultiDrawElements");
- return;
- }
-
- /* Decide if we can do this all as one set of primitives sharing the
- * same index buffer, or if we have to reset the index pointer per
- * primitive.
- */
- bind_arrays( ctx );
-
- /* check for dirty state again */
- if (ctx->NewState)
- _mesa_update_state( ctx );
-
- switch (type) {
- case GL_UNSIGNED_INT:
- index_type_size = 4;
- break;
- case GL_UNSIGNED_SHORT:
- index_type_size = 2;
- break;
- case GL_UNSIGNED_BYTE:
- index_type_size = 1;
- break;
- default:
- assert(0);
- }
-
- min_index_ptr = (uintptr_t)indices[0];
- max_index_ptr = 0;
- for (i = 0; i < primcount; i++) {
- min_index_ptr = MIN2(min_index_ptr, (uintptr_t)indices[i]);
- max_index_ptr = MAX2(max_index_ptr, (uintptr_t)indices[i] +
- index_type_size * count[i]);
- }
-
- /* Check if we can handle this thing as a bunch of index offsets from the
- * same index pointer. If we can't, then we have to fall back to doing
- * a draw_prims per primitive.
- * Check that the difference between each prim's indexes is a multiple of
- * the index/element size.
- */
- if (index_type_size != 1) {
- for (i = 0; i < primcount; i++) {
- if ((((uintptr_t)indices[i] - min_index_ptr) % index_type_size) != 0) {
- fallback = GL_TRUE;
- break;
- }
- }
- }
-
- /* If the index buffer isn't in a VBO, then treating the application's
- * subranges of the index buffer as one large index buffer may lead to
- * us reading unmapped memory.
- */
- if (!_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj))
- fallback = GL_TRUE;
-
- if (!fallback) {
- ib.count = (max_index_ptr - min_index_ptr) / index_type_size;
- ib.type = type;
- ib.obj = ctx->Array.ElementArrayBufferObj;
- ib.ptr = (void *)min_index_ptr;
-
- for (i = 0; i < primcount; i++) {
- prim[i].begin = (i == 0);
- prim[i].end = (i == primcount - 1);
- prim[i].weak = 0;
- prim[i].pad = 0;
- prim[i].mode = mode;
- prim[i].start = ((uintptr_t)indices[i] - min_index_ptr) / index_type_size;
- prim[i].count = count[i];
- prim[i].indexed = 1;
- prim[i].num_instances = 1;
- if (basevertex != NULL)
- prim[i].basevertex = basevertex[i];
- else
- prim[i].basevertex = 0;
- }
-
- check_buffers_are_unmapped(exec->array.inputs);
- vbo->draw_prims(ctx, exec->array.inputs, prim, primcount, &ib,
- GL_FALSE, ~0, ~0);
- } else {
- /* render one prim at a time */
- for (i = 0; i < primcount; i++) {
- ib.count = count[i];
- ib.type = type;
- ib.obj = ctx->Array.ElementArrayBufferObj;
- ib.ptr = indices[i];
-
- prim[0].begin = 1;
- prim[0].end = 1;
- prim[0].weak = 0;
- prim[0].pad = 0;
- prim[0].mode = mode;
- prim[0].start = 0;
- prim[0].count = count[i];
- prim[0].indexed = 1;
- prim[0].num_instances = 1;
- if (basevertex != NULL)
- prim[0].basevertex = basevertex[i];
- else
- prim[0].basevertex = 0;
-
- check_buffers_are_unmapped(exec->array.inputs);
- vbo->draw_prims(ctx, exec->array.inputs, prim, 1, &ib,
- GL_FALSE, ~0, ~0);
- }
- }
-
- free(prim);
-}
-
-
-static void GLAPIENTRY
-vbo_exec_MultiDrawElements(GLenum mode,
- const GLsizei *count, GLenum type,
- const GLvoid **indices,
- GLsizei primcount)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint i;
-
- ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
-
- for (i = 0; i < primcount; i++) {
- if (!_mesa_validate_DrawElements(ctx, mode, count[i], type, indices[i],
- 0))
- return;
- }
-
- vbo_validated_multidrawelements(ctx, mode, count, type, indices, primcount,
- NULL);
-}
-
-
-static void GLAPIENTRY
-vbo_exec_MultiDrawElementsBaseVertex(GLenum mode,
- const GLsizei *count, GLenum type,
- const GLvoid **indices,
- GLsizei primcount,
- const GLsizei *basevertex)
-{
- GET_CURRENT_CONTEXT(ctx);
- GLint i;
-
- ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
-
- for (i = 0; i < primcount; i++) {
- if (!_mesa_validate_DrawElements(ctx, mode, count[i], type, indices[i],
- basevertex[i]))
- return;
- }
-
- vbo_validated_multidrawelements(ctx, mode, count, type, indices, primcount,
- basevertex);
-}
-
-
-/**
- * Plug in the immediate-mode vertex array drawing commands into the
- * givven vbo_exec_context object.
- */
-void
-vbo_exec_array_init( struct vbo_exec_context *exec )
-{
- exec->vtxfmt.DrawArrays = vbo_exec_DrawArrays;
- exec->vtxfmt.DrawElements = vbo_exec_DrawElements;
- exec->vtxfmt.DrawRangeElements = vbo_exec_DrawRangeElements;
- exec->vtxfmt.MultiDrawElementsEXT = vbo_exec_MultiDrawElements;
- exec->vtxfmt.DrawElementsBaseVertex = vbo_exec_DrawElementsBaseVertex;
- exec->vtxfmt.DrawRangeElementsBaseVertex = vbo_exec_DrawRangeElementsBaseVertex;
- exec->vtxfmt.MultiDrawElementsBaseVertex = vbo_exec_MultiDrawElementsBaseVertex;
- exec->vtxfmt.DrawArraysInstanced = vbo_exec_DrawArraysInstanced;
- exec->vtxfmt.DrawElementsInstanced = vbo_exec_DrawElementsInstanced;
-}
-
-
-void
-vbo_exec_array_destroy( struct vbo_exec_context *exec )
-{
- /* nothing to do */
-}
-
-
-
-/**
- * The following functions are only used for OpenGL ES 1/2 support.
- * And some aren't even supported (yet) in ES 1/2.
- */
-
-
-void GLAPIENTRY
-_mesa_DrawArrays(GLenum mode, GLint first, GLsizei count)
-{
- vbo_exec_DrawArrays(mode, first, count);
-}
-
-
-void GLAPIENTRY
-_mesa_DrawElements(GLenum mode, GLsizei count, GLenum type,
- const GLvoid *indices)
-{
- vbo_exec_DrawElements(mode, count, type, indices);
-}
-
-
-void GLAPIENTRY
-_mesa_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
- const GLvoid *indices, GLint basevertex)
-{
- vbo_exec_DrawElementsBaseVertex(mode, count, type, indices, basevertex);
-}
-
-
-void GLAPIENTRY
-_mesa_DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count,
- GLenum type, const GLvoid *indices)
-{
- vbo_exec_DrawRangeElements(mode, start, end, count, type, indices);
-}
-
-
-void GLAPIENTRY
-_mesa_DrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end,
- GLsizei count, GLenum type,
- const GLvoid *indices, GLint basevertex)
-{
- vbo_exec_DrawRangeElementsBaseVertex(mode, start, end, count, type,
- indices, basevertex);
-}
-
-
-void GLAPIENTRY
-_mesa_MultiDrawElementsEXT(GLenum mode, const GLsizei *count, GLenum type,
- const GLvoid **indices, GLsizei primcount)
-{
- vbo_exec_MultiDrawElements(mode, count, type, indices, primcount);
-}
-
-
-void GLAPIENTRY
-_mesa_MultiDrawElementsBaseVertex(GLenum mode,
- const GLsizei *count, GLenum type,
- const GLvoid **indices, GLsizei primcount,
- const GLint *basevertex)
-{
- vbo_exec_MultiDrawElementsBaseVertex(mode, count, type, indices,
- primcount, basevertex);
-}
+/**************************************************************************
+ *
+ * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
+ * Copyright 2009 VMware, Inc.
+ * 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, sub license, 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 (including the
+ * next paragraph) 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 NON-INFRINGEMENT.
+ * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
+ *
+ **************************************************************************/
+
+#include "main/glheader.h"
+#include "main/context.h"
+#include "main/state.h"
+#include "main/api_validate.h"
+#include "main/varray.h"
+#include "main/bufferobj.h"
+#include "main/enums.h"
+#include "main/macros.h"
+
+#include "vbo_context.h"
+
+
+/**
+ * All vertex buffers should be in an unmapped state when we're about
+ * to draw. This debug function checks that.
+ */
+static void
+check_buffers_are_unmapped(const struct gl_client_array **inputs)
+{
+#ifdef DEBUG
+ GLuint i;
+
+ for (i = 0; i < VERT_ATTRIB_MAX; i++) {
+ if (inputs[i]) {
+ struct gl_buffer_object *obj = inputs[i]->BufferObj;
+ assert(!_mesa_bufferobj_mapped(obj));
+ }
+ }
+#endif
+}
+
+
+/**
+ * A debug function that may be called from other parts of Mesa as
+ * needed during debugging.
+ */
+void
+vbo_check_buffers_are_unmapped(struct gl_context *ctx)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ /* check the current vertex arrays */
+ check_buffers_are_unmapped(exec->array.inputs);
+ /* check the current glBegin/glVertex/glEnd-style VBO */
+ assert(!_mesa_bufferobj_mapped(exec->vtx.bufferobj));
+}
+
+
+
+/**
+ * Compute min and max elements by scanning the index buffer for
+ * glDraw[Range]Elements() calls.
+ * If primitive restart is enabled, we need to ignore restart
+ * indexes when computing min/max.
+ */
+void
+vbo_get_minmax_index(struct gl_context *ctx,
+ const struct _mesa_prim *prim,
+ const struct _mesa_index_buffer *ib,
+ GLuint *min_index, GLuint *max_index)
+{
+ const GLboolean restart = ctx->Array.PrimitiveRestart;
+ const GLuint restartIndex = ctx->Array.RestartIndex;
+ const GLuint count = prim->count;
+ const void *indices;
+ GLuint i;
+
+ if (_mesa_is_bufferobj(ib->obj)) {
+ const GLvoid *map =
+ ctx->Driver.MapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY, ib->obj);
+ indices = ADD_POINTERS(map, ib->ptr);
+ } else {
+ indices = ib->ptr;
+ }
+
+ switch (ib->type) {
+ case GL_UNSIGNED_INT: {
+ const GLuint *ui_indices = (const GLuint *)indices;
+ GLuint max_ui = 0;
+ GLuint min_ui = ~0U;
+ if (restart) {
+ for (i = 0; i < count; i++) {
+ if (ui_indices[i] != restartIndex) {
+ if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
+ if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
+ }
+ }
+ }
+ else {
+ for (i = 0; i < count; i++) {
+ if (ui_indices[i] > max_ui) max_ui = ui_indices[i];
+ if (ui_indices[i] < min_ui) min_ui = ui_indices[i];
+ }
+ }
+ *min_index = min_ui;
+ *max_index = max_ui;
+ break;
+ }
+ case GL_UNSIGNED_SHORT: {
+ const GLushort *us_indices = (const GLushort *)indices;
+ GLuint max_us = 0;
+ GLuint min_us = ~0U;
+ if (restart) {
+ for (i = 0; i < count; i++) {
+ if (us_indices[i] != restartIndex) {
+ if (us_indices[i] > max_us) max_us = us_indices[i];
+ if (us_indices[i] < min_us) min_us = us_indices[i];
+ }
+ }
+ }
+ else {
+ for (i = 0; i < count; i++) {
+ if (us_indices[i] > max_us) max_us = us_indices[i];
+ if (us_indices[i] < min_us) min_us = us_indices[i];
+ }
+ }
+ *min_index = min_us;
+ *max_index = max_us;
+ break;
+ }
+ case GL_UNSIGNED_BYTE: {
+ const GLubyte *ub_indices = (const GLubyte *)indices;
+ GLuint max_ub = 0;
+ GLuint min_ub = ~0U;
+ if (restart) {
+ for (i = 0; i < count; i++) {
+ if (ub_indices[i] != restartIndex) {
+ if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
+ if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
+ }
+ }
+ }
+ else {
+ for (i = 0; i < count; i++) {
+ if (ub_indices[i] > max_ub) max_ub = ub_indices[i];
+ if (ub_indices[i] < min_ub) min_ub = ub_indices[i];
+ }
+ }
+ *min_index = min_ub;
+ *max_index = max_ub;
+ break;
+ }
+ default:
+ assert(0);
+ break;
+ }
+
+ if (_mesa_is_bufferobj(ib->obj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB, ib->obj);
+ }
+}
+
+
+/**
+ * Check that element 'j' of the array has reasonable data.
+ * Map VBO if needed.
+ * For debugging purposes; not normally used.
+ */
+static void
+check_array_data(struct gl_context *ctx, struct gl_client_array *array,
+ GLuint attrib, GLuint j)
+{
+ if (array->Enabled) {
+ const void *data = array->Ptr;
+ if (_mesa_is_bufferobj(array->BufferObj)) {
+ if (!array->BufferObj->Pointer) {
+ /* need to map now */
+ array->BufferObj->Pointer =
+ ctx->Driver.MapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY, array->BufferObj);
+ }
+ data = ADD_POINTERS(data, array->BufferObj->Pointer);
+ }
+ switch (array->Type) {
+ case GL_FLOAT:
+ {
+ GLfloat *f = (GLfloat *) ((GLubyte *) data + array->StrideB * j);
+ GLint k;
+ for (k = 0; k < array->Size; k++) {
+ if (IS_INF_OR_NAN(f[k]) ||
+ f[k] >= 1.0e20 || f[k] <= -1.0e10) {
+ printf("Bad array data:\n");
+ printf(" Element[%u].%u = %f\n", j, k, f[k]);
+ printf(" Array %u at %p\n", attrib, (void* ) array);
+ printf(" Type 0x%x, Size %d, Stride %d\n",
+ array->Type, array->Size, array->Stride);
+ printf(" Address/offset %p in Buffer Object %u\n",
+ array->Ptr, array->BufferObj->Name);
+ f[k] = 1.0; /* XXX replace the bad value! */
+ }
+ /*assert(!IS_INF_OR_NAN(f[k]));*/
+ }
+ }
+ break;
+ default:
+ ;
+ }
+ }
+}
+
+
+/**
+ * Unmap the buffer object referenced by given array, if mapped.
+ */
+static void
+unmap_array_buffer(struct gl_context *ctx, struct gl_client_array *array)
+{
+ if (array->Enabled &&
+ _mesa_is_bufferobj(array->BufferObj) &&
+ _mesa_bufferobj_mapped(array->BufferObj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB, array->BufferObj);
+ }
+}
+
+
+/**
+ * Examine the array's data for NaNs, etc.
+ * For debug purposes; not normally used.
+ */
+static void
+check_draw_elements_data(struct gl_context *ctx, GLsizei count, GLenum elemType,
+ const void *elements, GLint basevertex)
+{
+ struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
+ const void *elemMap;
+ GLint i, k;
+
+ if (_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj)) {
+ elemMap = ctx->Driver.MapBuffer(ctx,
+ GL_ELEMENT_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY,
+ ctx->Array.ElementArrayBufferObj);
+ elements = ADD_POINTERS(elements, elemMap);
+ }
+
+ for (i = 0; i < count; i++) {
+ GLuint j;
+
+ /* j = element[i] */
+ switch (elemType) {
+ case GL_UNSIGNED_BYTE:
+ j = ((const GLubyte *) elements)[i];
+ break;
+ case GL_UNSIGNED_SHORT:
+ j = ((const GLushort *) elements)[i];
+ break;
+ case GL_UNSIGNED_INT:
+ j = ((const GLuint *) elements)[i];
+ break;
+ default:
+ assert(0);
+ }
+
+ /* check element j of each enabled array */
+ check_array_data(ctx, &arrayObj->Vertex, VERT_ATTRIB_POS, j);
+ check_array_data(ctx, &arrayObj->Normal, VERT_ATTRIB_NORMAL, j);
+ check_array_data(ctx, &arrayObj->Color, VERT_ATTRIB_COLOR0, j);
+ check_array_data(ctx, &arrayObj->SecondaryColor, VERT_ATTRIB_COLOR1, j);
+ for (k = 0; k < Elements(arrayObj->TexCoord); k++) {
+ check_array_data(ctx, &arrayObj->TexCoord[k], VERT_ATTRIB_TEX0 + k, j);
+ }
+ for (k = 0; k < Elements(arrayObj->VertexAttrib); k++) {
+ check_array_data(ctx, &arrayObj->VertexAttrib[k],
+ VERT_ATTRIB_GENERIC0 + k, j);
+ }
+ }
+
+ if (_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj)) {
+ ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
+ ctx->Array.ElementArrayBufferObj);
+ }
+
+ unmap_array_buffer(ctx, &arrayObj->Vertex);
+ unmap_array_buffer(ctx, &arrayObj->Normal);
+ unmap_array_buffer(ctx, &arrayObj->Color);
+ for (k = 0; k < Elements(arrayObj->TexCoord); k++) {
+ unmap_array_buffer(ctx, &arrayObj->TexCoord[k]);
+ }
+ for (k = 0; k < Elements(arrayObj->VertexAttrib); k++) {
+ unmap_array_buffer(ctx, &arrayObj->VertexAttrib[k]);
+ }
+}
+
+
+/**
+ * Check array data, looking for NaNs, etc.
+ */
+static void
+check_draw_arrays_data(struct gl_context *ctx, GLint start, GLsizei count)
+{
+ /* TO DO */
+}
+
+
+/**
+ * Print info/data for glDrawArrays(), for debugging.
+ */
+static void
+print_draw_arrays(struct gl_context *ctx,
+ GLenum mode, GLint start, GLsizei count)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ int i;
+
+ printf("vbo_exec_DrawArrays(mode 0x%x, start %d, count %d):\n",
+ mode, start, count);
+
+ for (i = 0; i < 32; i++) {
+ GLuint bufName = exec->array.inputs[i]->BufferObj->Name;
+ GLint stride = exec->array.inputs[i]->Stride;
+ printf("attr %2d: size %d stride %d enabled %d "
+ "ptr %p Bufobj %u\n",
+ i,
+ exec->array.inputs[i]->Size,
+ stride,
+ /*exec->array.inputs[i]->Enabled,*/
+ exec->array.legacy_array[i]->Enabled,
+ exec->array.inputs[i]->Ptr,
+ bufName);
+
+ if (bufName) {
+ struct gl_buffer_object *buf = _mesa_lookup_bufferobj(ctx, bufName);
+ GLubyte *p = ctx->Driver.MapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY_ARB, buf);
+ int offset = (int) (GLintptr) exec->array.inputs[i]->Ptr;
+ float *f = (float *) (p + offset);
+ int *k = (int *) f;
+ int i;
+ int n = (count * stride) / 4;
+ if (n > 32)
+ n = 32;
+ printf(" Data at offset %d:\n", offset);
+ for (i = 0; i < n; i++) {
+ printf(" float[%d] = 0x%08x %f\n", i, k[i], f[i]);
+ }
+ ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB, buf);
+ }
+ }
+}
+
+
+/**
+ * Bind the VBO executor to the current vertex array object prior
+ * to drawing.
+ *
+ * Just translate the arrayobj into a sane layout.
+ */
+static void
+bind_array_obj(struct gl_context *ctx)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ struct gl_array_object *arrayObj = ctx->Array.ArrayObj;
+ GLuint i;
+
+ /* TODO: Fix the ArrayObj struct to keep legacy arrays in an array
+ * rather than as individual named arrays. Then this function can
+ * go away.
+ */
+ exec->array.legacy_array[VERT_ATTRIB_POS] = &arrayObj->Vertex;
+ exec->array.legacy_array[VERT_ATTRIB_WEIGHT] = &arrayObj->Weight;
+ exec->array.legacy_array[VERT_ATTRIB_NORMAL] = &arrayObj->Normal;
+ exec->array.legacy_array[VERT_ATTRIB_COLOR0] = &arrayObj->Color;
+ exec->array.legacy_array[VERT_ATTRIB_COLOR1] = &arrayObj->SecondaryColor;
+ exec->array.legacy_array[VERT_ATTRIB_FOG] = &arrayObj->FogCoord;
+ exec->array.legacy_array[VERT_ATTRIB_COLOR_INDEX] = &arrayObj->Index;
+ if (arrayObj->PointSize.Enabled) {
+ /* this aliases COLOR_INDEX */
+ exec->array.legacy_array[VERT_ATTRIB_POINT_SIZE] = &arrayObj->PointSize;
+ }
+ exec->array.legacy_array[VERT_ATTRIB_EDGEFLAG] = &arrayObj->EdgeFlag;
+
+ for (i = 0; i < Elements(arrayObj->TexCoord); i++)
+ exec->array.legacy_array[VERT_ATTRIB_TEX0 + i] = &arrayObj->TexCoord[i];
+
+ for (i = 0; i < Elements(arrayObj->VertexAttrib); i++) {
+ assert(i < Elements(exec->array.generic_array));
+ exec->array.generic_array[i] = &arrayObj->VertexAttrib[i];
+ }
+
+ exec->array.array_obj = arrayObj->Name;
+}
+
+
+/**
+ * Set the vbo->exec->inputs[] pointers to point to the enabled
+ * vertex arrays. This depends on the current vertex program/shader
+ * being executed because of whether or not generic vertex arrays
+ * alias the conventional vertex arrays.
+ * For arrays that aren't enabled, we set the input[attrib] pointer
+ * to point at a zero-stride current value "array".
+ */
+static void
+recalculate_input_bindings(struct gl_context *ctx)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ const struct gl_client_array **inputs = &exec->array.inputs[0];
+ GLbitfield const_inputs = 0x0;
+ GLuint i;
+
+ exec->array.program_mode = get_program_mode(ctx);
+ exec->array.enabled_flags = ctx->Array.ArrayObj->_Enabled;
+
+ switch (exec->array.program_mode) {
+ case VP_NONE:
+ /* When no vertex program is active (or the vertex program is generated
+ * from fixed-function state). We put the material values into the
+ * generic slots. This is the only situation where material values
+ * are available as per-vertex attributes.
+ */
+ for (i = 0; i <= VERT_ATTRIB_TEX7; i++) {
+ if (exec->array.legacy_array[i]->Enabled)
+ inputs[i] = exec->array.legacy_array[i];
+ else {
+ inputs[i] = &vbo->legacy_currval[i];
+ const_inputs |= 1 << i;
+ }
+ }
+
+ for (i = 0; i < MAT_ATTRIB_MAX; i++) {
+ inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->mat_currval[i];
+ const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
+ }
+
+ /* Could use just about anything, just to fill in the empty
+ * slots:
+ */
+ for (i = MAT_ATTRIB_MAX; i < VERT_ATTRIB_MAX - VERT_ATTRIB_GENERIC0; i++) {
+ inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->generic_currval[i];
+ const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
+ }
+ break;
+
+ case VP_NV:
+ /* NV_vertex_program - attribute arrays alias and override
+ * conventional, legacy arrays. No materials, and the generic
+ * slots are vacant.
+ */
+ for (i = 0; i <= VERT_ATTRIB_TEX7; i++) {
+ if (exec->array.generic_array[i]->Enabled)
+ inputs[i] = exec->array.generic_array[i];
+ else if (exec->array.legacy_array[i]->Enabled)
+ inputs[i] = exec->array.legacy_array[i];
+ else {
+ inputs[i] = &vbo->legacy_currval[i];
+ const_inputs |= 1 << i;
+ }
+ }
+
+ /* Could use just about anything, just to fill in the empty
+ * slots:
+ */
+ for (i = VERT_ATTRIB_GENERIC0; i < VERT_ATTRIB_MAX; i++) {
+ inputs[i] = &vbo->generic_currval[i - VERT_ATTRIB_GENERIC0];
+ const_inputs |= 1 << i;
+ }
+ break;
+
+ case VP_ARB:
+ /* GL_ARB_vertex_program or GLSL vertex shader - Only the generic[0]
+ * attribute array aliases and overrides the legacy position array.
+ *
+ * Otherwise, legacy attributes available in the legacy slots,
+ * generic attributes in the generic slots and materials are not
+ * available as per-vertex attributes.
+ */
+ if (exec->array.generic_array[0]->Enabled)
+ inputs[0] = exec->array.generic_array[0];
+ else if (exec->array.legacy_array[0]->Enabled)
+ inputs[0] = exec->array.legacy_array[0];
+ else {
+ inputs[0] = &vbo->legacy_currval[0];
+ const_inputs |= 1 << 0;
+ }
+
+ for (i = 1; i <= VERT_ATTRIB_TEX7; i++) {
+ if (exec->array.legacy_array[i]->Enabled)
+ inputs[i] = exec->array.legacy_array[i];
+ else {
+ inputs[i] = &vbo->legacy_currval[i];
+ const_inputs |= 1 << i;
+ }
+ }
+
+ for (i = 0; i < MAX_VERTEX_GENERIC_ATTRIBS; i++) {
+ if (exec->array.generic_array[i]->Enabled)
+ inputs[VERT_ATTRIB_GENERIC0 + i] = exec->array.generic_array[i];
+ else {
+ inputs[VERT_ATTRIB_GENERIC0 + i] = &vbo->generic_currval[i];
+ const_inputs |= 1 << (VERT_ATTRIB_GENERIC0 + i);
+ }
+
+ }
+ break;
+ }
+
+ _mesa_set_varying_vp_inputs( ctx, ~const_inputs );
+}
+
+
+/**
+ * Examine the enabled vertex arrays to set the exec->array.inputs[] values.
+ * These will point to the arrays to actually use for drawing. Some will
+ * be user-provided arrays, other will be zero-stride const-valued arrays.
+ * Note that this might set the _NEW_ARRAY dirty flag so state validation
+ * must be done after this call.
+ */
+static void
+bind_arrays(struct gl_context *ctx)
+{
+ if (!ctx->Array.RebindArrays) {
+ return;
+ }
+
+ bind_array_obj(ctx);
+ recalculate_input_bindings(ctx);
+ ctx->Array.RebindArrays = GL_FALSE;
+}
+
+
+/**
+ * Helper function called by the other DrawArrays() functions below.
+ * This is where we handle primitive restart for drawing non-indexed
+ * arrays. If primitive restart is enabled, it typically means
+ * splitting one DrawArrays() into two.
+ */
+static void
+vbo_draw_arrays(struct gl_context *ctx, GLenum mode, GLint start,
+ GLsizei count, GLuint numInstances)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ struct _mesa_prim prim[2];
+
+ bind_arrays(ctx);
+
+ /* Again... because we may have changed the bitmask of per-vertex varying
+ * attributes. If we regenerate the fixed-function vertex program now
+ * we may be able to prune down the number of vertex attributes which we
+ * need in the shader.
+ */
+ if (ctx->NewState)
+ _mesa_update_state(ctx);
+
+ prim[0].begin = 1;
+ prim[0].end = 1;
+ prim[0].weak = 0;
+ prim[0].pad = 0;
+ prim[0].mode = mode;
+ prim[0].start = 0; /* filled in below */
+ prim[0].count = 0; /* filled in below */
+ prim[0].indexed = 0;
+ prim[0].basevertex = 0;
+ prim[0].num_instances = numInstances;
+
+ /* Implement the primitive restart index */
+ if (ctx->Array.PrimitiveRestart && ctx->Array.RestartIndex < count) {
+ GLuint primCount = 0;
+
+ if (ctx->Array.RestartIndex == start) {
+ /* special case: RestartIndex at beginning */
+ if (count > 1) {
+ prim[0].start = start + 1;
+ prim[0].count = count - 1;
+ primCount = 1;
+ }
+ }
+ else if (ctx->Array.RestartIndex == start + count - 1) {
+ /* special case: RestartIndex at end */
+ if (count > 1) {
+ prim[0].start = start;
+ prim[0].count = count - 1;
+ primCount = 1;
+ }
+ }
+ else {
+ /* general case: RestartIndex in middle, split into two prims */
+ prim[0].start = start;
+ prim[0].count = ctx->Array.RestartIndex - start;
+
+ prim[1] = prim[0];
+ prim[1].start = ctx->Array.RestartIndex + 1;
+ prim[1].count = count - prim[1].start;
+
+ primCount = 2;
+ }
+
+ if (primCount > 0) {
+ /* draw one or two prims */
+ check_buffers_are_unmapped(exec->array.inputs);
+ vbo->draw_prims(ctx, exec->array.inputs, prim, primCount, NULL,
+ GL_TRUE, start, start + count - 1);
+ }
+ }
+ else {
+ /* no prim restart */
+ prim[0].start = start;
+ prim[0].count = count;
+
+ check_buffers_are_unmapped(exec->array.inputs);
+ vbo->draw_prims(ctx, exec->array.inputs, prim, 1, NULL,
+ GL_TRUE, start, start + count - 1);
+ }
+}
+
+
+
+/**
+ * Called from glDrawArrays when in immediate mode (not display list mode).
+ */
+static void GLAPIENTRY
+vbo_exec_DrawArrays(GLenum mode, GLint start, GLsizei count)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx, "glDrawArrays(%s, %d, %d)\n",
+ _mesa_lookup_enum_by_nr(mode), start, count);
+
+ if (!_mesa_validate_DrawArrays( ctx, mode, start, count ))
+ return;
+
+ FLUSH_CURRENT( ctx, 0 );
+
+ if (!_mesa_valid_to_render(ctx, "glDrawArrays")) {
+ return;
+ }
+
+ if (0)
+ check_draw_arrays_data(ctx, start, count);
+
+ vbo_draw_arrays(ctx, mode, start, count, 1);
+
+ if (0)
+ print_draw_arrays(ctx, mode, start, count);
+}
+
+
+/**
+ * Called from glDrawArraysInstanced when in immediate mode (not
+ * display list mode).
+ */
+static void GLAPIENTRY
+vbo_exec_DrawArraysInstanced(GLenum mode, GLint start, GLsizei count,
+ GLsizei numInstances)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx, "glDrawArraysInstanced(%s, %d, %d, %d)\n",
+ _mesa_lookup_enum_by_nr(mode), start, count, numInstances);
+
+ if (!_mesa_validate_DrawArraysInstanced(ctx, mode, start, count, numInstances))
+ return;
+
+ FLUSH_CURRENT( ctx, 0 );
+
+ if (!_mesa_valid_to_render(ctx, "glDrawArraysInstanced")) {
+ return;
+ }
+
+ if (0)
+ check_draw_arrays_data(ctx, start, count);
+
+ vbo_draw_arrays(ctx, mode, start, count, numInstances);
+
+ if (0)
+ print_draw_arrays(ctx, mode, start, count);
+}
+
+
+/**
+ * Map GL_ELEMENT_ARRAY_BUFFER and print contents.
+ * For debugging.
+ */
+static void
+dump_element_buffer(struct gl_context *ctx, GLenum type)
+{
+ const GLvoid *map = ctx->Driver.MapBuffer(ctx,
+ GL_ELEMENT_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY,
+ ctx->Array.ElementArrayBufferObj);
+ switch (type) {
+ case GL_UNSIGNED_BYTE:
+ {
+ const GLubyte *us = (const GLubyte *) map;
+ GLint i;
+ for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size; i++) {
+ printf("%02x ", us[i]);
+ if (i % 32 == 31)
+ printf("\n");
+ }
+ printf("\n");
+ }
+ break;
+ case GL_UNSIGNED_SHORT:
+ {
+ const GLushort *us = (const GLushort *) map;
+ GLint i;
+ for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size / 2; i++) {
+ printf("%04x ", us[i]);
+ if (i % 16 == 15)
+ printf("\n");
+ }
+ printf("\n");
+ }
+ break;
+ case GL_UNSIGNED_INT:
+ {
+ const GLuint *us = (const GLuint *) map;
+ GLint i;
+ for (i = 0; i < ctx->Array.ElementArrayBufferObj->Size / 4; i++) {
+ printf("%08x ", us[i]);
+ if (i % 8 == 7)
+ printf("\n");
+ }
+ printf("\n");
+ }
+ break;
+ default:
+ ;
+ }
+
+ ctx->Driver.UnmapBuffer(ctx, GL_ELEMENT_ARRAY_BUFFER_ARB,
+ ctx->Array.ElementArrayBufferObj);
+}
+
+
+/**
+ * Inner support for both _mesa_DrawElements and _mesa_DrawRangeElements.
+ * Do the rendering for a glDrawElements or glDrawRangeElements call after
+ * we've validated buffer bounds, etc.
+ */
+static void
+vbo_validated_drawrangeelements(struct gl_context *ctx, GLenum mode,
+ GLboolean index_bounds_valid,
+ GLuint start, GLuint end,
+ GLsizei count, GLenum type,
+ const GLvoid *indices,
+ GLint basevertex, GLint numInstances)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ struct _mesa_index_buffer ib;
+ struct _mesa_prim prim[1];
+
+ FLUSH_CURRENT( ctx, 0 );
+
+ if (!_mesa_valid_to_render(ctx, "glDraw[Range]Elements")) {
+ return;
+ }
+
+ bind_arrays( ctx );
+
+ /* check for dirty state again */
+ if (ctx->NewState)
+ _mesa_update_state( ctx );
+
+ ib.count = count;
+ ib.type = type;
+ ib.obj = ctx->Array.ElementArrayBufferObj;
+ ib.ptr = indices;
+
+ prim[0].begin = 1;
+ prim[0].end = 1;
+ prim[0].weak = 0;
+ prim[0].pad = 0;
+ prim[0].mode = mode;
+ prim[0].start = 0;
+ prim[0].count = count;
+ prim[0].indexed = 1;
+ prim[0].basevertex = basevertex;
+ prim[0].num_instances = numInstances;
+
+ /* Need to give special consideration to rendering a range of
+ * indices starting somewhere above zero. Typically the
+ * application is issuing multiple DrawRangeElements() to draw
+ * successive primitives layed out linearly in the vertex arrays.
+ * Unless the vertex arrays are all in a VBO (or locked as with
+ * CVA), the OpenGL semantics imply that we need to re-read or
+ * re-upload the vertex data on each draw call.
+ *
+ * In the case of hardware tnl, we want to avoid starting the
+ * upload at zero, as it will mean every draw call uploads an
+ * increasing amount of not-used vertex data. Worse - in the
+ * software tnl module, all those vertices might be transformed and
+ * lit but never rendered.
+ *
+ * If we just upload or transform the vertices in start..end,
+ * however, the indices will be incorrect.
+ *
+ * At this level, we don't know exactly what the requirements of
+ * the backend are going to be, though it will likely boil down to
+ * either:
+ *
+ * 1) Do nothing, everything is in a VBO and is processed once
+ * only.
+ *
+ * 2) Adjust the indices and vertex arrays so that start becomes
+ * zero.
+ *
+ * Rather than doing anything here, I'll provide a helper function
+ * for the latter case elsewhere.
+ */
+
+ check_buffers_are_unmapped(exec->array.inputs);
+ vbo->draw_prims( ctx, exec->array.inputs, prim, 1, &ib,
+ index_bounds_valid, start, end );
+}
+
+
+/**
+ * Called by glDrawRangeElementsBaseVertex() in immediate mode.
+ */
+static void GLAPIENTRY
+vbo_exec_DrawRangeElementsBaseVertex(GLenum mode,
+ GLuint start, GLuint end,
+ GLsizei count, GLenum type,
+ const GLvoid *indices,
+ GLint basevertex)
+{
+ static GLuint warnCount = 0;
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx,
+ "glDrawRangeElementsBaseVertex(%s, %u, %u, %d, %s, %p, %d)\n",
+ _mesa_lookup_enum_by_nr(mode), start, end, count,
+ _mesa_lookup_enum_by_nr(type), indices, basevertex);
+
+ if (!_mesa_validate_DrawRangeElements( ctx, mode, start, end, count,
+ type, indices, basevertex ))
+ return;
+
+ /* NOTE: It's important that 'end' is a reasonable value.
+ * in _tnl_draw_prims(), we use end to determine how many vertices
+ * to transform. If it's too large, we can unnecessarily split prims
+ * or we can read/write out of memory in several different places!
+ */
+
+ /* Catch/fix some potential user errors */
+ if (type == GL_UNSIGNED_BYTE) {
+ start = MIN2(start, 0xff);
+ end = MIN2(end, 0xff);
+ }
+ else if (type == GL_UNSIGNED_SHORT) {
+ start = MIN2(start, 0xffff);
+ end = MIN2(end, 0xffff);
+ }
+
+ if (end >= ctx->Array.ArrayObj->_MaxElement) {
+ /* the max element is out of bounds of one or more enabled arrays */
+ warnCount++;
+
+ if (warnCount < 10) {
+ _mesa_warning(ctx, "glDraw[Range]Elements(start %u, end %u, count %d, "
+ "type 0x%x, indices=%p)\n"
+ "\tend is out of bounds (max=%u) "
+ "Element Buffer %u (size %d)\n"
+ "\tThis should probably be fixed in the application.",
+ start, end, count, type, indices,
+ ctx->Array.ArrayObj->_MaxElement - 1,
+ ctx->Array.ElementArrayBufferObj->Name,
+ (int) ctx->Array.ElementArrayBufferObj->Size);
+ }
+
+ if (0)
+ dump_element_buffer(ctx, type);
+
+ if (0)
+ _mesa_print_arrays(ctx);
+
+#ifdef DEBUG
+ /* 'end' was out of bounds, but now let's check the actual array
+ * indexes to see if any of them are out of bounds.
+ */
+ {
+ GLuint max = _mesa_max_buffer_index(ctx, count, type, indices,
+ ctx->Array.ElementArrayBufferObj);
+ if (max >= ctx->Array.ArrayObj->_MaxElement) {
+ if (warnCount < 10) {
+ _mesa_warning(ctx, "glDraw[Range]Elements(start %u, end %u, "
+ "count %d, type 0x%x, indices=%p)\n"
+ "\tindex=%u is out of bounds (max=%u) "
+ "Element Buffer %u (size %d)\n"
+ "\tSkipping the glDrawRangeElements() call",
+ start, end, count, type, indices, max,
+ ctx->Array.ArrayObj->_MaxElement - 1,
+ ctx->Array.ElementArrayBufferObj->Name,
+ (int) ctx->Array.ElementArrayBufferObj->Size);
+ }
+ }
+ /* XXX we could also find the min index and compare to 'start'
+ * to see if start is correct. But it's more likely to get the
+ * upper bound wrong.
+ */
+ }
+#endif
+
+ /* Set 'end' to the max possible legal value */
+ assert(ctx->Array.ArrayObj->_MaxElement >= 1);
+ end = ctx->Array.ArrayObj->_MaxElement - 1;
+ }
+ else if (0) {
+ printf("glDraw[Range]Elements{,BaseVertex}"
+ "(start %u, end %u, type 0x%x, count %d) ElemBuf %u, "
+ "base %d\n",
+ start, end, type, count,
+ ctx->Array.ElementArrayBufferObj->Name,
+ basevertex);
+ }
+
+#if 0
+ check_draw_elements_data(ctx, count, type, indices);
+#else
+ (void) check_draw_elements_data;
+#endif
+
+ vbo_validated_drawrangeelements(ctx, mode, GL_TRUE, start, end,
+ count, type, indices, basevertex, 1);
+}
+
+
+/**
+ * Called by glDrawRangeElements() in immediate mode.
+ */
+static void GLAPIENTRY
+vbo_exec_DrawRangeElements(GLenum mode, GLuint start, GLuint end,
+ GLsizei count, GLenum type, const GLvoid *indices)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx,
+ "glDrawRangeElements(%s, %u, %u, %d, %s, %p)\n",
+ _mesa_lookup_enum_by_nr(mode), start, end, count,
+ _mesa_lookup_enum_by_nr(type), indices);
+
+ vbo_exec_DrawRangeElementsBaseVertex(mode, start, end, count, type,
+ indices, 0);
+}
+
+
+/**
+ * Called by glDrawElements() in immediate mode.
+ */
+static void GLAPIENTRY
+vbo_exec_DrawElements(GLenum mode, GLsizei count, GLenum type,
+ const GLvoid *indices)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx, "glDrawElements(%s, %u, %s, %p)\n",
+ _mesa_lookup_enum_by_nr(mode), count,
+ _mesa_lookup_enum_by_nr(type), indices);
+
+ if (!_mesa_validate_DrawElements( ctx, mode, count, type, indices, 0 ))
+ return;
+
+ vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
+ count, type, indices, 0, 1);
+}
+
+
+/**
+ * Called by glDrawElementsBaseVertex() in immediate mode.
+ */
+static void GLAPIENTRY
+vbo_exec_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
+ const GLvoid *indices, GLint basevertex)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx, "glDrawElementsBaseVertex(%s, %d, %s, %p, %d)\n",
+ _mesa_lookup_enum_by_nr(mode), count,
+ _mesa_lookup_enum_by_nr(type), indices, basevertex);
+
+ if (!_mesa_validate_DrawElements( ctx, mode, count, type, indices,
+ basevertex ))
+ return;
+
+ vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
+ count, type, indices, basevertex, 1);
+}
+
+
+/**
+ * Called by glDrawElementsInstanced() in immediate mode.
+ */
+static void GLAPIENTRY
+vbo_exec_DrawElementsInstanced(GLenum mode, GLsizei count, GLenum type,
+ const GLvoid *indices, GLsizei numInstances)
+{
+ GET_CURRENT_CONTEXT(ctx);
+
+ if (MESA_VERBOSE & VERBOSE_DRAW)
+ _mesa_debug(ctx, "glDrawElementsInstanced(%s, %d, %s, %p, %d)\n",
+ _mesa_lookup_enum_by_nr(mode), count,
+ _mesa_lookup_enum_by_nr(type), indices, numInstances);
+
+ if (!_mesa_validate_DrawElementsInstanced(ctx, mode, count, type, indices,
+ numInstances))
+ return;
+
+ vbo_validated_drawrangeelements(ctx, mode, GL_FALSE, ~0, ~0,
+ count, type, indices, 0, numInstances);
+}
+
+
+/**
+ * Inner support for both _mesa_MultiDrawElements() and
+ * _mesa_MultiDrawRangeElements().
+ * This does the actual rendering after we've checked array indexes, etc.
+ */
+static void
+vbo_validated_multidrawelements(struct gl_context *ctx, GLenum mode,
+ const GLsizei *count, GLenum type,
+ const GLvoid **indices, GLsizei primcount,
+ const GLint *basevertex)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ struct _mesa_index_buffer ib;
+ struct _mesa_prim *prim;
+ unsigned int index_type_size = 0;
+ uintptr_t min_index_ptr, max_index_ptr;
+ GLboolean fallback = GL_FALSE;
+ int i;
+
+ if (primcount == 0)
+ return;
+
+ FLUSH_CURRENT( ctx, 0 );
+
+ if (!_mesa_valid_to_render(ctx, "glMultiDrawElements")) {
+ return;
+ }
+
+ prim = calloc(1, primcount * sizeof(*prim));
+ if (prim == NULL) {
+ _mesa_error(ctx, GL_OUT_OF_MEMORY, "glMultiDrawElements");
+ return;
+ }
+
+ /* Decide if we can do this all as one set of primitives sharing the
+ * same index buffer, or if we have to reset the index pointer per
+ * primitive.
+ */
+ bind_arrays( ctx );
+
+ /* check for dirty state again */
+ if (ctx->NewState)
+ _mesa_update_state( ctx );
+
+ switch (type) {
+ case GL_UNSIGNED_INT:
+ index_type_size = 4;
+ break;
+ case GL_UNSIGNED_SHORT:
+ index_type_size = 2;
+ break;
+ case GL_UNSIGNED_BYTE:
+ index_type_size = 1;
+ break;
+ default:
+ assert(0);
+ }
+
+ min_index_ptr = (uintptr_t)indices[0];
+ max_index_ptr = 0;
+ for (i = 0; i < primcount; i++) {
+ min_index_ptr = MIN2(min_index_ptr, (uintptr_t)indices[i]);
+ max_index_ptr = MAX2(max_index_ptr, (uintptr_t)indices[i] +
+ index_type_size * count[i]);
+ }
+
+ /* Check if we can handle this thing as a bunch of index offsets from the
+ * same index pointer. If we can't, then we have to fall back to doing
+ * a draw_prims per primitive.
+ * Check that the difference between each prim's indexes is a multiple of
+ * the index/element size.
+ */
+ if (index_type_size != 1) {
+ for (i = 0; i < primcount; i++) {
+ if ((((uintptr_t)indices[i] - min_index_ptr) % index_type_size) != 0) {
+ fallback = GL_TRUE;
+ break;
+ }
+ }
+ }
+
+ /* If the index buffer isn't in a VBO, then treating the application's
+ * subranges of the index buffer as one large index buffer may lead to
+ * us reading unmapped memory.
+ */
+ if (!_mesa_is_bufferobj(ctx->Array.ElementArrayBufferObj))
+ fallback = GL_TRUE;
+
+ if (!fallback) {
+ ib.count = (max_index_ptr - min_index_ptr) / index_type_size;
+ ib.type = type;
+ ib.obj = ctx->Array.ElementArrayBufferObj;
+ ib.ptr = (void *)min_index_ptr;
+
+ for (i = 0; i < primcount; i++) {
+ prim[i].begin = (i == 0);
+ prim[i].end = (i == primcount - 1);
+ prim[i].weak = 0;
+ prim[i].pad = 0;
+ prim[i].mode = mode;
+ prim[i].start = ((uintptr_t)indices[i] - min_index_ptr) / index_type_size;
+ prim[i].count = count[i];
+ prim[i].indexed = 1;
+ prim[i].num_instances = 1;
+ if (basevertex != NULL)
+ prim[i].basevertex = basevertex[i];
+ else
+ prim[i].basevertex = 0;
+ }
+
+ check_buffers_are_unmapped(exec->array.inputs);
+ vbo->draw_prims(ctx, exec->array.inputs, prim, primcount, &ib,
+ GL_FALSE, ~0, ~0);
+ } else {
+ /* render one prim at a time */
+ for (i = 0; i < primcount; i++) {
+ ib.count = count[i];
+ ib.type = type;
+ ib.obj = ctx->Array.ElementArrayBufferObj;
+ ib.ptr = indices[i];
+
+ prim[0].begin = 1;
+ prim[0].end = 1;
+ prim[0].weak = 0;
+ prim[0].pad = 0;
+ prim[0].mode = mode;
+ prim[0].start = 0;
+ prim[0].count = count[i];
+ prim[0].indexed = 1;
+ prim[0].num_instances = 1;
+ if (basevertex != NULL)
+ prim[0].basevertex = basevertex[i];
+ else
+ prim[0].basevertex = 0;
+
+ check_buffers_are_unmapped(exec->array.inputs);
+ vbo->draw_prims(ctx, exec->array.inputs, prim, 1, &ib,
+ GL_FALSE, ~0, ~0);
+ }
+ }
+
+ free(prim);
+}
+
+
+static void GLAPIENTRY
+vbo_exec_MultiDrawElements(GLenum mode,
+ const GLsizei *count, GLenum type,
+ const GLvoid **indices,
+ GLsizei primcount)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint i;
+
+ ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
+
+ for (i = 0; i < primcount; i++) {
+ if (!_mesa_validate_DrawElements(ctx, mode, count[i], type, indices[i],
+ 0))
+ return;
+ }
+
+ vbo_validated_multidrawelements(ctx, mode, count, type, indices, primcount,
+ NULL);
+}
+
+
+static void GLAPIENTRY
+vbo_exec_MultiDrawElementsBaseVertex(GLenum mode,
+ const GLsizei *count, GLenum type,
+ const GLvoid **indices,
+ GLsizei primcount,
+ const GLsizei *basevertex)
+{
+ GET_CURRENT_CONTEXT(ctx);
+ GLint i;
+
+ ASSERT_OUTSIDE_BEGIN_END_AND_FLUSH(ctx);
+
+ for (i = 0; i < primcount; i++) {
+ if (!_mesa_validate_DrawElements(ctx, mode, count[i], type, indices[i],
+ basevertex[i]))
+ return;
+ }
+
+ vbo_validated_multidrawelements(ctx, mode, count, type, indices, primcount,
+ basevertex);
+}
+
+
+/**
+ * Plug in the immediate-mode vertex array drawing commands into the
+ * givven vbo_exec_context object.
+ */
+void
+vbo_exec_array_init( struct vbo_exec_context *exec )
+{
+ exec->vtxfmt.DrawArrays = vbo_exec_DrawArrays;
+ exec->vtxfmt.DrawElements = vbo_exec_DrawElements;
+ exec->vtxfmt.DrawRangeElements = vbo_exec_DrawRangeElements;
+ exec->vtxfmt.MultiDrawElementsEXT = vbo_exec_MultiDrawElements;
+ exec->vtxfmt.DrawElementsBaseVertex = vbo_exec_DrawElementsBaseVertex;
+ exec->vtxfmt.DrawRangeElementsBaseVertex = vbo_exec_DrawRangeElementsBaseVertex;
+ exec->vtxfmt.MultiDrawElementsBaseVertex = vbo_exec_MultiDrawElementsBaseVertex;
+ exec->vtxfmt.DrawArraysInstanced = vbo_exec_DrawArraysInstanced;
+ exec->vtxfmt.DrawElementsInstanced = vbo_exec_DrawElementsInstanced;
+}
+
+
+void
+vbo_exec_array_destroy( struct vbo_exec_context *exec )
+{
+ /* nothing to do */
+}
+
+
+
+/**
+ * The following functions are only used for OpenGL ES 1/2 support.
+ * And some aren't even supported (yet) in ES 1/2.
+ */
+
+
+void GLAPIENTRY
+_mesa_DrawArrays(GLenum mode, GLint first, GLsizei count)
+{
+ vbo_exec_DrawArrays(mode, first, count);
+}
+
+
+void GLAPIENTRY
+_mesa_DrawElements(GLenum mode, GLsizei count, GLenum type,
+ const GLvoid *indices)
+{
+ vbo_exec_DrawElements(mode, count, type, indices);
+}
+
+
+void GLAPIENTRY
+_mesa_DrawElementsBaseVertex(GLenum mode, GLsizei count, GLenum type,
+ const GLvoid *indices, GLint basevertex)
+{
+ vbo_exec_DrawElementsBaseVertex(mode, count, type, indices, basevertex);
+}
+
+
+void GLAPIENTRY
+_mesa_DrawRangeElements(GLenum mode, GLuint start, GLuint end, GLsizei count,
+ GLenum type, const GLvoid *indices)
+{
+ vbo_exec_DrawRangeElements(mode, start, end, count, type, indices);
+}
+
+
+void GLAPIENTRY
+_mesa_DrawRangeElementsBaseVertex(GLenum mode, GLuint start, GLuint end,
+ GLsizei count, GLenum type,
+ const GLvoid *indices, GLint basevertex)
+{
+ vbo_exec_DrawRangeElementsBaseVertex(mode, start, end, count, type,
+ indices, basevertex);
+}
+
+
+void GLAPIENTRY
+_mesa_MultiDrawElementsEXT(GLenum mode, const GLsizei *count, GLenum type,
+ const GLvoid **indices, GLsizei primcount)
+{
+ vbo_exec_MultiDrawElements(mode, count, type, indices, primcount);
+}
+
+
+void GLAPIENTRY
+_mesa_MultiDrawElementsBaseVertex(GLenum mode,
+ const GLsizei *count, GLenum type,
+ const GLvoid **indices, GLsizei primcount,
+ const GLint *basevertex)
+{
+ vbo_exec_MultiDrawElementsBaseVertex(mode, count, type, indices,
+ primcount, basevertex);
+}
diff --git a/mesalib/src/mesa/vbo/vbo_exec_draw.c b/mesalib/src/mesa/vbo/vbo_exec_draw.c
index 539658021..7cc843779 100644
--- a/mesalib/src/mesa/vbo/vbo_exec_draw.c
+++ b/mesalib/src/mesa/vbo/vbo_exec_draw.c
@@ -1,426 +1,426 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.2
- *
- * Copyright (C) 1999-2008 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:
- * Keith Whitwell <keith@tungstengraphics.com>
- */
-
-#include "main/glheader.h"
-#include "main/bufferobj.h"
-#include "main/compiler.h"
-#include "main/enums.h"
-#include "main/mfeatures.h"
-#include "main/state.h"
-
-#include "vbo_context.h"
-
-
-#if FEATURE_beginend
-
-
-static void
-vbo_exec_debug_verts( struct vbo_exec_context *exec )
-{
- GLuint count = exec->vtx.vert_count;
- GLuint i;
-
- printf("%s: %u vertices %d primitives, %d vertsize\n",
- __FUNCTION__,
- count,
- exec->vtx.prim_count,
- exec->vtx.vertex_size);
-
- for (i = 0 ; i < exec->vtx.prim_count ; i++) {
- struct _mesa_prim *prim = &exec->vtx.prim[i];
- printf(" prim %d: %s%s %d..%d %s %s\n",
- i,
- _mesa_lookup_prim_by_nr(prim->mode),
- prim->weak ? " (weak)" : "",
- prim->start,
- prim->start + prim->count,
- prim->begin ? "BEGIN" : "(wrap)",
- prim->end ? "END" : "(wrap)");
- }
-}
-
-
-/*
- * NOTE: Need to have calculated primitives by this point -- do it on the fly.
- * NOTE: Old 'parity' issue is gone.
- */
-static GLuint
-vbo_copy_vertices( struct vbo_exec_context *exec )
-{
- GLuint nr = exec->vtx.prim[exec->vtx.prim_count-1].count;
- GLuint ovf, i;
- GLuint sz = exec->vtx.vertex_size;
- GLfloat *dst = exec->vtx.copied.buffer;
- const GLfloat *src = (exec->vtx.buffer_map +
- exec->vtx.prim[exec->vtx.prim_count-1].start *
- exec->vtx.vertex_size);
-
-
- switch (exec->ctx->Driver.CurrentExecPrimitive) {
- case GL_POINTS:
- return 0;
- case GL_LINES:
- ovf = nr&1;
- for (i = 0 ; i < ovf ; i++)
- memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
- return i;
- case GL_TRIANGLES:
- ovf = nr%3;
- for (i = 0 ; i < ovf ; i++)
- memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
- return i;
- case GL_QUADS:
- ovf = nr&3;
- for (i = 0 ; i < ovf ; i++)
- memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
- return i;
- case GL_LINE_STRIP:
- if (nr == 0) {
- return 0;
- }
- else {
- memcpy( dst, src+(nr-1)*sz, sz * sizeof(GLfloat) );
- return 1;
- }
- case GL_LINE_LOOP:
- case GL_TRIANGLE_FAN:
- case GL_POLYGON:
- if (nr == 0) {
- return 0;
- }
- else if (nr == 1) {
- memcpy( dst, src+0, sz * sizeof(GLfloat) );
- return 1;
- }
- else {
- memcpy( dst, src+0, sz * sizeof(GLfloat) );
- memcpy( dst+sz, src+(nr-1)*sz, sz * sizeof(GLfloat) );
- return 2;
- }
- case GL_TRIANGLE_STRIP:
- /* no parity issue, but need to make sure the tri is not drawn twice */
- if (nr & 1) {
- exec->vtx.prim[exec->vtx.prim_count-1].count--;
- }
- /* fallthrough */
- case GL_QUAD_STRIP:
- switch (nr) {
- case 0:
- ovf = 0;
- break;
- case 1:
- ovf = 1;
- break;
- default:
- ovf = 2 + (nr & 1);
- break;
- }
- for (i = 0 ; i < ovf ; i++)
- memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
- return i;
- case PRIM_OUTSIDE_BEGIN_END:
- return 0;
- default:
- assert(0);
- return 0;
- }
-}
-
-
-
-/* TODO: populate these as the vertex is defined:
- */
-static void
-vbo_exec_bind_arrays( struct gl_context *ctx )
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_exec_context *exec = &vbo->exec;
- struct gl_client_array *arrays = exec->vtx.arrays;
- const GLuint count = exec->vtx.vert_count;
- const GLuint *map;
- GLuint attr;
- GLbitfield varying_inputs = 0x0;
-
- /* Install the default (ie Current) attributes first, then overlay
- * all active ones.
- */
- switch (get_program_mode(exec->ctx)) {
- case VP_NONE:
- for (attr = 0; attr < 16; attr++) {
- exec->vtx.inputs[attr] = &vbo->legacy_currval[attr];
- }
- for (attr = 0; attr < MAT_ATTRIB_MAX; attr++) {
- ASSERT(attr + 16 < Elements(exec->vtx.inputs));
- exec->vtx.inputs[attr + 16] = &vbo->mat_currval[attr];
- }
- map = vbo->map_vp_none;
- break;
- case VP_NV:
- case VP_ARB:
- /* The aliasing of attributes for NV vertex programs has already
- * occurred. NV vertex programs cannot access material values,
- * nor attributes greater than VERT_ATTRIB_TEX7.
- */
- for (attr = 0; attr < 16; attr++) {
- exec->vtx.inputs[attr] = &vbo->legacy_currval[attr];
- ASSERT(attr + 16 < Elements(exec->vtx.inputs));
- exec->vtx.inputs[attr + 16] = &vbo->generic_currval[attr];
- }
- map = vbo->map_vp_arb;
-
- /* check if VERT_ATTRIB_POS is not read but VERT_BIT_GENERIC0 is read.
- * In that case we effectively need to route the data from
- * glVertexAttrib(0, val) calls to feed into the GENERIC0 input.
- */
- if ((ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_POS) == 0 &&
- (ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_GENERIC0)) {
- exec->vtx.inputs[16] = exec->vtx.inputs[0];
- exec->vtx.attrsz[16] = exec->vtx.attrsz[0];
- exec->vtx.attrptr[16] = exec->vtx.attrptr[0];
- exec->vtx.attrsz[0] = 0;
- }
- break;
- default:
- assert(0);
- }
-
- /* Make all active attributes (including edgeflag) available as
- * arrays of floats.
- */
- for (attr = 0; attr < VERT_ATTRIB_MAX ; attr++) {
- const GLuint src = map[attr];
-
- if (exec->vtx.attrsz[src]) {
- GLsizeiptr offset = (GLbyte *)exec->vtx.attrptr[src] -
- (GLbyte *)exec->vtx.vertex;
-
- /* override the default array set above */
- ASSERT(attr < Elements(exec->vtx.inputs));
- ASSERT(attr < Elements(exec->vtx.arrays)); /* arrays[] */
- exec->vtx.inputs[attr] = &arrays[attr];
-
- if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
- /* a real buffer obj: Ptr is an offset, not a pointer*/
- assert(exec->vtx.bufferobj->Pointer); /* buf should be mapped */
- assert(offset >= 0);
- arrays[attr].Ptr = (GLubyte *)exec->vtx.bufferobj->Offset + offset;
- }
- else {
- /* Ptr into ordinary app memory */
- arrays[attr].Ptr = (GLubyte *)exec->vtx.buffer_map + offset;
- }
- arrays[attr].Size = exec->vtx.attrsz[src];
- arrays[attr].StrideB = exec->vtx.vertex_size * sizeof(GLfloat);
- arrays[attr].Stride = exec->vtx.vertex_size * sizeof(GLfloat);
- arrays[attr].Type = GL_FLOAT;
- arrays[attr].Format = GL_RGBA;
- arrays[attr].Enabled = 1;
- _mesa_reference_buffer_object(ctx,
- &arrays[attr].BufferObj,
- exec->vtx.bufferobj);
- arrays[attr]._MaxElement = count; /* ??? */
-
- varying_inputs |= 1 << attr;
- ctx->NewState |= _NEW_ARRAY;
- }
- }
-
- _mesa_set_varying_vp_inputs( ctx, varying_inputs );
-}
-
-
-/**
- * Unmap the VBO. This is called before drawing.
- */
-static void
-vbo_exec_vtx_unmap( struct vbo_exec_context *exec )
-{
- GLenum target = GL_ARRAY_BUFFER_ARB;
-
- if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
- struct gl_context *ctx = exec->ctx;
-
- if (ctx->Driver.FlushMappedBufferRange) {
- GLintptr offset = exec->vtx.buffer_used - exec->vtx.bufferobj->Offset;
- GLsizeiptr length = (exec->vtx.buffer_ptr - exec->vtx.buffer_map) * sizeof(float);
-
- if (length)
- ctx->Driver.FlushMappedBufferRange(ctx, target,
- offset, length,
- exec->vtx.bufferobj);
- }
-
- exec->vtx.buffer_used += (exec->vtx.buffer_ptr -
- exec->vtx.buffer_map) * sizeof(float);
-
- assert(exec->vtx.buffer_used <= VBO_VERT_BUFFER_SIZE);
- assert(exec->vtx.buffer_ptr != NULL);
-
- ctx->Driver.UnmapBuffer(ctx, target, exec->vtx.bufferobj);
- exec->vtx.buffer_map = NULL;
- exec->vtx.buffer_ptr = NULL;
- exec->vtx.max_vert = 0;
- }
-}
-
-
-/**
- * Map the vertex buffer to begin storing glVertex, glColor, etc data.
- */
-void
-vbo_exec_vtx_map( struct vbo_exec_context *exec )
-{
- struct gl_context *ctx = exec->ctx;
- const GLenum target = GL_ARRAY_BUFFER_ARB;
- const GLenum access = GL_READ_WRITE_ARB; /* for MapBuffer */
- const GLenum accessRange = GL_MAP_WRITE_BIT | /* for MapBufferRange */
- GL_MAP_INVALIDATE_RANGE_BIT |
- GL_MAP_UNSYNCHRONIZED_BIT |
- GL_MAP_FLUSH_EXPLICIT_BIT |
- MESA_MAP_NOWAIT_BIT;
- const GLenum usage = GL_STREAM_DRAW_ARB;
-
- if (!_mesa_is_bufferobj(exec->vtx.bufferobj))
- return;
-
- assert(!exec->vtx.buffer_map);
- assert(!exec->vtx.buffer_ptr);
-
- if (VBO_VERT_BUFFER_SIZE > exec->vtx.buffer_used + 1024 &&
- ctx->Driver.MapBufferRange) {
- /* The VBO exists and there's room for more */
- exec->vtx.buffer_map =
- (GLfloat *)ctx->Driver.MapBufferRange(ctx,
- target,
- exec->vtx.buffer_used,
- (VBO_VERT_BUFFER_SIZE -
- exec->vtx.buffer_used),
- accessRange,
- exec->vtx.bufferobj);
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
- }
-
- if (!exec->vtx.buffer_map) {
- /* Need to allocate a new VBO */
- exec->vtx.buffer_used = 0;
-
- ctx->Driver.BufferData(ctx, target,
- VBO_VERT_BUFFER_SIZE,
- NULL, usage, exec->vtx.bufferobj);
-
-
- if (ctx->Driver.MapBufferRange)
- exec->vtx.buffer_map =
- (GLfloat *)ctx->Driver.MapBufferRange(ctx, target,
- 0, VBO_VERT_BUFFER_SIZE,
- accessRange,
- exec->vtx.bufferobj);
- if (!exec->vtx.buffer_map)
- exec->vtx.buffer_map =
- (GLfloat *)ctx->Driver.MapBuffer(ctx, target, access, exec->vtx.bufferobj);
- assert(exec->vtx.buffer_map);
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
- }
-
- if (0)
- printf("map %d..\n", exec->vtx.buffer_used);
-}
-
-
-
-/**
- * Execute the buffer and save copied verts.
- * \param keep_unmapped if true, leave the VBO unmapped when we're done.
- */
-void
-vbo_exec_vtx_flush(struct vbo_exec_context *exec, GLboolean keepUnmapped)
-{
- if (0)
- vbo_exec_debug_verts( exec );
-
- if (exec->vtx.prim_count &&
- exec->vtx.vert_count) {
-
- exec->vtx.copied.nr = vbo_copy_vertices( exec );
-
- if (exec->vtx.copied.nr != exec->vtx.vert_count) {
- struct gl_context *ctx = exec->ctx;
-
- /* Before the update_state() as this may raise _NEW_ARRAY
- * from _mesa_set_varying_vp_inputs().
- */
- vbo_exec_bind_arrays( ctx );
-
- if (ctx->NewState)
- _mesa_update_state( ctx );
-
- if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
- vbo_exec_vtx_unmap( exec );
- }
-
- if (0)
- printf("%s %d %d\n", __FUNCTION__, exec->vtx.prim_count,
- exec->vtx.vert_count);
-
- vbo_context(ctx)->draw_prims( ctx,
- exec->vtx.inputs,
- exec->vtx.prim,
- exec->vtx.prim_count,
- NULL,
- GL_TRUE,
- 0,
- exec->vtx.vert_count - 1);
-
- /* If using a real VBO, get new storage -- unless asked not to.
- */
- if (_mesa_is_bufferobj(exec->vtx.bufferobj) && !keepUnmapped) {
- vbo_exec_vtx_map( exec );
- }
- }
- }
-
- /* May have to unmap explicitly if we didn't draw:
- */
- if (keepUnmapped &&
- _mesa_is_bufferobj(exec->vtx.bufferobj) &&
- exec->vtx.buffer_map) {
- vbo_exec_vtx_unmap( exec );
- }
-
- if (keepUnmapped || exec->vtx.vertex_size == 0)
- exec->vtx.max_vert = 0;
- else
- exec->vtx.max_vert = ((VBO_VERT_BUFFER_SIZE - exec->vtx.buffer_used) /
- (exec->vtx.vertex_size * sizeof(GLfloat)));
-
- exec->vtx.buffer_ptr = exec->vtx.buffer_map;
- exec->vtx.prim_count = 0;
- exec->vtx.vert_count = 0;
-}
-
-
-#endif /* FEATURE_beginend */
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.2
+ *
+ * Copyright (C) 1999-2008 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:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ */
+
+#include "main/glheader.h"
+#include "main/bufferobj.h"
+#include "main/compiler.h"
+#include "main/enums.h"
+#include "main/mfeatures.h"
+#include "main/state.h"
+
+#include "vbo_context.h"
+
+
+#if FEATURE_beginend
+
+
+static void
+vbo_exec_debug_verts( struct vbo_exec_context *exec )
+{
+ GLuint count = exec->vtx.vert_count;
+ GLuint i;
+
+ printf("%s: %u vertices %d primitives, %d vertsize\n",
+ __FUNCTION__,
+ count,
+ exec->vtx.prim_count,
+ exec->vtx.vertex_size);
+
+ for (i = 0 ; i < exec->vtx.prim_count ; i++) {
+ struct _mesa_prim *prim = &exec->vtx.prim[i];
+ printf(" prim %d: %s%s %d..%d %s %s\n",
+ i,
+ _mesa_lookup_prim_by_nr(prim->mode),
+ prim->weak ? " (weak)" : "",
+ prim->start,
+ prim->start + prim->count,
+ prim->begin ? "BEGIN" : "(wrap)",
+ prim->end ? "END" : "(wrap)");
+ }
+}
+
+
+/*
+ * NOTE: Need to have calculated primitives by this point -- do it on the fly.
+ * NOTE: Old 'parity' issue is gone.
+ */
+static GLuint
+vbo_copy_vertices( struct vbo_exec_context *exec )
+{
+ GLuint nr = exec->vtx.prim[exec->vtx.prim_count-1].count;
+ GLuint ovf, i;
+ GLuint sz = exec->vtx.vertex_size;
+ GLfloat *dst = exec->vtx.copied.buffer;
+ const GLfloat *src = (exec->vtx.buffer_map +
+ exec->vtx.prim[exec->vtx.prim_count-1].start *
+ exec->vtx.vertex_size);
+
+
+ switch (exec->ctx->Driver.CurrentExecPrimitive) {
+ case GL_POINTS:
+ return 0;
+ case GL_LINES:
+ ovf = nr&1;
+ for (i = 0 ; i < ovf ; i++)
+ memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
+ return i;
+ case GL_TRIANGLES:
+ ovf = nr%3;
+ for (i = 0 ; i < ovf ; i++)
+ memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
+ return i;
+ case GL_QUADS:
+ ovf = nr&3;
+ for (i = 0 ; i < ovf ; i++)
+ memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
+ return i;
+ case GL_LINE_STRIP:
+ if (nr == 0) {
+ return 0;
+ }
+ else {
+ memcpy( dst, src+(nr-1)*sz, sz * sizeof(GLfloat) );
+ return 1;
+ }
+ case GL_LINE_LOOP:
+ case GL_TRIANGLE_FAN:
+ case GL_POLYGON:
+ if (nr == 0) {
+ return 0;
+ }
+ else if (nr == 1) {
+ memcpy( dst, src+0, sz * sizeof(GLfloat) );
+ return 1;
+ }
+ else {
+ memcpy( dst, src+0, sz * sizeof(GLfloat) );
+ memcpy( dst+sz, src+(nr-1)*sz, sz * sizeof(GLfloat) );
+ return 2;
+ }
+ case GL_TRIANGLE_STRIP:
+ /* no parity issue, but need to make sure the tri is not drawn twice */
+ if (nr & 1) {
+ exec->vtx.prim[exec->vtx.prim_count-1].count--;
+ }
+ /* fallthrough */
+ case GL_QUAD_STRIP:
+ switch (nr) {
+ case 0:
+ ovf = 0;
+ break;
+ case 1:
+ ovf = 1;
+ break;
+ default:
+ ovf = 2 + (nr & 1);
+ break;
+ }
+ for (i = 0 ; i < ovf ; i++)
+ memcpy( dst+i*sz, src+(nr-ovf+i)*sz, sz * sizeof(GLfloat) );
+ return i;
+ case PRIM_OUTSIDE_BEGIN_END:
+ return 0;
+ default:
+ assert(0);
+ return 0;
+ }
+}
+
+
+
+/* TODO: populate these as the vertex is defined:
+ */
+static void
+vbo_exec_bind_arrays( struct gl_context *ctx )
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_exec_context *exec = &vbo->exec;
+ struct gl_client_array *arrays = exec->vtx.arrays;
+ const GLuint count = exec->vtx.vert_count;
+ const GLuint *map;
+ GLuint attr;
+ GLbitfield varying_inputs = 0x0;
+
+ /* Install the default (ie Current) attributes first, then overlay
+ * all active ones.
+ */
+ switch (get_program_mode(exec->ctx)) {
+ case VP_NONE:
+ for (attr = 0; attr < 16; attr++) {
+ exec->vtx.inputs[attr] = &vbo->legacy_currval[attr];
+ }
+ for (attr = 0; attr < MAT_ATTRIB_MAX; attr++) {
+ ASSERT(attr + 16 < Elements(exec->vtx.inputs));
+ exec->vtx.inputs[attr + 16] = &vbo->mat_currval[attr];
+ }
+ map = vbo->map_vp_none;
+ break;
+ case VP_NV:
+ case VP_ARB:
+ /* The aliasing of attributes for NV vertex programs has already
+ * occurred. NV vertex programs cannot access material values,
+ * nor attributes greater than VERT_ATTRIB_TEX7.
+ */
+ for (attr = 0; attr < 16; attr++) {
+ exec->vtx.inputs[attr] = &vbo->legacy_currval[attr];
+ ASSERT(attr + 16 < Elements(exec->vtx.inputs));
+ exec->vtx.inputs[attr + 16] = &vbo->generic_currval[attr];
+ }
+ map = vbo->map_vp_arb;
+
+ /* check if VERT_ATTRIB_POS is not read but VERT_BIT_GENERIC0 is read.
+ * In that case we effectively need to route the data from
+ * glVertexAttrib(0, val) calls to feed into the GENERIC0 input.
+ */
+ if ((ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_POS) == 0 &&
+ (ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_GENERIC0)) {
+ exec->vtx.inputs[16] = exec->vtx.inputs[0];
+ exec->vtx.attrsz[16] = exec->vtx.attrsz[0];
+ exec->vtx.attrptr[16] = exec->vtx.attrptr[0];
+ exec->vtx.attrsz[0] = 0;
+ }
+ break;
+ default:
+ assert(0);
+ }
+
+ /* Make all active attributes (including edgeflag) available as
+ * arrays of floats.
+ */
+ for (attr = 0; attr < VERT_ATTRIB_MAX ; attr++) {
+ const GLuint src = map[attr];
+
+ if (exec->vtx.attrsz[src]) {
+ GLsizeiptr offset = (GLbyte *)exec->vtx.attrptr[src] -
+ (GLbyte *)exec->vtx.vertex;
+
+ /* override the default array set above */
+ ASSERT(attr < Elements(exec->vtx.inputs));
+ ASSERT(attr < Elements(exec->vtx.arrays)); /* arrays[] */
+ exec->vtx.inputs[attr] = &arrays[attr];
+
+ if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
+ /* a real buffer obj: Ptr is an offset, not a pointer*/
+ assert(exec->vtx.bufferobj->Pointer); /* buf should be mapped */
+ assert(offset >= 0);
+ arrays[attr].Ptr = (GLubyte *)exec->vtx.bufferobj->Offset + offset;
+ }
+ else {
+ /* Ptr into ordinary app memory */
+ arrays[attr].Ptr = (GLubyte *)exec->vtx.buffer_map + offset;
+ }
+ arrays[attr].Size = exec->vtx.attrsz[src];
+ arrays[attr].StrideB = exec->vtx.vertex_size * sizeof(GLfloat);
+ arrays[attr].Stride = exec->vtx.vertex_size * sizeof(GLfloat);
+ arrays[attr].Type = GL_FLOAT;
+ arrays[attr].Format = GL_RGBA;
+ arrays[attr].Enabled = 1;
+ _mesa_reference_buffer_object(ctx,
+ &arrays[attr].BufferObj,
+ exec->vtx.bufferobj);
+ arrays[attr]._MaxElement = count; /* ??? */
+
+ varying_inputs |= 1 << attr;
+ ctx->NewState |= _NEW_ARRAY;
+ }
+ }
+
+ _mesa_set_varying_vp_inputs( ctx, varying_inputs );
+}
+
+
+/**
+ * Unmap the VBO. This is called before drawing.
+ */
+static void
+vbo_exec_vtx_unmap( struct vbo_exec_context *exec )
+{
+ GLenum target = GL_ARRAY_BUFFER_ARB;
+
+ if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
+ struct gl_context *ctx = exec->ctx;
+
+ if (ctx->Driver.FlushMappedBufferRange) {
+ GLintptr offset = exec->vtx.buffer_used - exec->vtx.bufferobj->Offset;
+ GLsizeiptr length = (exec->vtx.buffer_ptr - exec->vtx.buffer_map) * sizeof(float);
+
+ if (length)
+ ctx->Driver.FlushMappedBufferRange(ctx, target,
+ offset, length,
+ exec->vtx.bufferobj);
+ }
+
+ exec->vtx.buffer_used += (exec->vtx.buffer_ptr -
+ exec->vtx.buffer_map) * sizeof(float);
+
+ assert(exec->vtx.buffer_used <= VBO_VERT_BUFFER_SIZE);
+ assert(exec->vtx.buffer_ptr != NULL);
+
+ ctx->Driver.UnmapBuffer(ctx, target, exec->vtx.bufferobj);
+ exec->vtx.buffer_map = NULL;
+ exec->vtx.buffer_ptr = NULL;
+ exec->vtx.max_vert = 0;
+ }
+}
+
+
+/**
+ * Map the vertex buffer to begin storing glVertex, glColor, etc data.
+ */
+void
+vbo_exec_vtx_map( struct vbo_exec_context *exec )
+{
+ struct gl_context *ctx = exec->ctx;
+ const GLenum target = GL_ARRAY_BUFFER_ARB;
+ const GLenum access = GL_READ_WRITE_ARB; /* for MapBuffer */
+ const GLenum accessRange = GL_MAP_WRITE_BIT | /* for MapBufferRange */
+ GL_MAP_INVALIDATE_RANGE_BIT |
+ GL_MAP_UNSYNCHRONIZED_BIT |
+ GL_MAP_FLUSH_EXPLICIT_BIT |
+ MESA_MAP_NOWAIT_BIT;
+ const GLenum usage = GL_STREAM_DRAW_ARB;
+
+ if (!_mesa_is_bufferobj(exec->vtx.bufferobj))
+ return;
+
+ assert(!exec->vtx.buffer_map);
+ assert(!exec->vtx.buffer_ptr);
+
+ if (VBO_VERT_BUFFER_SIZE > exec->vtx.buffer_used + 1024 &&
+ ctx->Driver.MapBufferRange) {
+ /* The VBO exists and there's room for more */
+ exec->vtx.buffer_map =
+ (GLfloat *)ctx->Driver.MapBufferRange(ctx,
+ target,
+ exec->vtx.buffer_used,
+ (VBO_VERT_BUFFER_SIZE -
+ exec->vtx.buffer_used),
+ accessRange,
+ exec->vtx.bufferobj);
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+ }
+
+ if (!exec->vtx.buffer_map) {
+ /* Need to allocate a new VBO */
+ exec->vtx.buffer_used = 0;
+
+ ctx->Driver.BufferData(ctx, target,
+ VBO_VERT_BUFFER_SIZE,
+ NULL, usage, exec->vtx.bufferobj);
+
+
+ if (ctx->Driver.MapBufferRange)
+ exec->vtx.buffer_map =
+ (GLfloat *)ctx->Driver.MapBufferRange(ctx, target,
+ 0, VBO_VERT_BUFFER_SIZE,
+ accessRange,
+ exec->vtx.bufferobj);
+ if (!exec->vtx.buffer_map)
+ exec->vtx.buffer_map =
+ (GLfloat *)ctx->Driver.MapBuffer(ctx, target, access, exec->vtx.bufferobj);
+ assert(exec->vtx.buffer_map);
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+ }
+
+ if (0)
+ printf("map %d..\n", exec->vtx.buffer_used);
+}
+
+
+
+/**
+ * Execute the buffer and save copied verts.
+ * \param keep_unmapped if true, leave the VBO unmapped when we're done.
+ */
+void
+vbo_exec_vtx_flush(struct vbo_exec_context *exec, GLboolean keepUnmapped)
+{
+ if (0)
+ vbo_exec_debug_verts( exec );
+
+ if (exec->vtx.prim_count &&
+ exec->vtx.vert_count) {
+
+ exec->vtx.copied.nr = vbo_copy_vertices( exec );
+
+ if (exec->vtx.copied.nr != exec->vtx.vert_count) {
+ struct gl_context *ctx = exec->ctx;
+
+ /* Before the update_state() as this may raise _NEW_ARRAY
+ * from _mesa_set_varying_vp_inputs().
+ */
+ vbo_exec_bind_arrays( ctx );
+
+ if (ctx->NewState)
+ _mesa_update_state( ctx );
+
+ if (_mesa_is_bufferobj(exec->vtx.bufferobj)) {
+ vbo_exec_vtx_unmap( exec );
+ }
+
+ if (0)
+ printf("%s %d %d\n", __FUNCTION__, exec->vtx.prim_count,
+ exec->vtx.vert_count);
+
+ vbo_context(ctx)->draw_prims( ctx,
+ exec->vtx.inputs,
+ exec->vtx.prim,
+ exec->vtx.prim_count,
+ NULL,
+ GL_TRUE,
+ 0,
+ exec->vtx.vert_count - 1);
+
+ /* If using a real VBO, get new storage -- unless asked not to.
+ */
+ if (_mesa_is_bufferobj(exec->vtx.bufferobj) && !keepUnmapped) {
+ vbo_exec_vtx_map( exec );
+ }
+ }
+ }
+
+ /* May have to unmap explicitly if we didn't draw:
+ */
+ if (keepUnmapped &&
+ _mesa_is_bufferobj(exec->vtx.bufferobj) &&
+ exec->vtx.buffer_map) {
+ vbo_exec_vtx_unmap( exec );
+ }
+
+ if (keepUnmapped || exec->vtx.vertex_size == 0)
+ exec->vtx.max_vert = 0;
+ else
+ exec->vtx.max_vert = ((VBO_VERT_BUFFER_SIZE - exec->vtx.buffer_used) /
+ (exec->vtx.vertex_size * sizeof(GLfloat)));
+
+ exec->vtx.buffer_ptr = exec->vtx.buffer_map;
+ exec->vtx.prim_count = 0;
+ exec->vtx.vert_count = 0;
+}
+
+
+#endif /* FEATURE_beginend */
diff --git a/mesalib/src/mesa/vbo/vbo_save_draw.c b/mesalib/src/mesa/vbo/vbo_save_draw.c
index 634a6d3f8..5a19b0d62 100644
--- a/mesalib/src/mesa/vbo/vbo_save_draw.c
+++ b/mesalib/src/mesa/vbo/vbo_save_draw.c
@@ -1,305 +1,305 @@
-/*
- * Mesa 3-D graphics library
- * Version: 7.2
- *
- * Copyright (C) 1999-2008 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.
- */
-
-/* Author:
- * Keith Whitwell <keith@tungstengraphics.com>
- */
-
-#include "main/glheader.h"
-#include "main/bufferobj.h"
-#include "main/context.h"
-#include "main/imports.h"
-#include "main/mfeatures.h"
-#include "main/mtypes.h"
-#include "main/macros.h"
-#include "main/light.h"
-#include "main/state.h"
-
-#include "vbo_context.h"
-
-
-#if FEATURE_dlist
-
-
-/**
- * After playback, copy everything but the position from the
- * last vertex to the saved state
- */
-static void
-_playback_copy_to_current(struct gl_context *ctx,
- const struct vbo_save_vertex_list *node)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- GLfloat vertex[VBO_ATTRIB_MAX * 4];
- GLfloat *data;
- GLuint i, offset;
-
- if (node->current_size == 0)
- return;
-
- if (node->current_data) {
- data = node->current_data;
- }
- else {
- data = vertex;
-
- if (node->count)
- offset = (node->buffer_offset +
- (node->count-1) * node->vertex_size * sizeof(GLfloat));
- else
- offset = node->buffer_offset;
-
- ctx->Driver.GetBufferSubData( ctx, 0, offset,
- node->vertex_size * sizeof(GLfloat),
- data, node->vertex_store->bufferobj );
-
- data += node->attrsz[0]; /* skip vertex position */
- }
-
- for (i = VBO_ATTRIB_POS+1 ; i < VBO_ATTRIB_MAX ; i++) {
- if (node->attrsz[i]) {
- GLfloat *current = (GLfloat *)vbo->currval[i].Ptr;
- GLfloat tmp[4];
-
- COPY_CLEAN_4V(tmp,
- node->attrsz[i],
- data);
-
- if (memcmp(current, tmp, 4 * sizeof(GLfloat)) != 0) {
- memcpy(current, tmp, 4 * sizeof(GLfloat));
-
- vbo->currval[i].Size = node->attrsz[i];
-
- if (i >= VBO_ATTRIB_FIRST_MATERIAL &&
- i <= VBO_ATTRIB_LAST_MATERIAL)
- ctx->NewState |= _NEW_LIGHT;
-
- ctx->NewState |= _NEW_CURRENT_ATTRIB;
- }
-
- data += node->attrsz[i];
- }
- }
-
- /* Colormaterial -- this kindof sucks.
- */
- if (ctx->Light.ColorMaterialEnabled) {
- _mesa_update_color_material(ctx, ctx->Current.Attrib[VBO_ATTRIB_COLOR0]);
- }
-
- /* CurrentExecPrimitive
- */
- if (node->prim_count) {
- const struct _mesa_prim *prim = &node->prim[node->prim_count - 1];
- if (prim->end)
- ctx->Driver.CurrentExecPrimitive = PRIM_OUTSIDE_BEGIN_END;
- else
- ctx->Driver.CurrentExecPrimitive = prim->mode;
- }
-}
-
-
-
-/**
- * Treat the vertex storage as a VBO, define vertex arrays pointing
- * into it:
- */
-static void vbo_bind_vertex_list(struct gl_context *ctx,
- const struct vbo_save_vertex_list *node)
-{
- struct vbo_context *vbo = vbo_context(ctx);
- struct vbo_save_context *save = &vbo->save;
- struct gl_client_array *arrays = save->arrays;
- GLuint buffer_offset = node->buffer_offset;
- const GLuint *map;
- GLuint attr;
- GLubyte node_attrsz[VBO_ATTRIB_MAX]; /* copy of node->attrsz[] */
- GLbitfield varying_inputs = 0x0;
-
- memcpy(node_attrsz, node->attrsz, sizeof(node->attrsz));
-
- /* Install the default (ie Current) attributes first, then overlay
- * all active ones.
- */
- switch (get_program_mode(ctx)) {
- case VP_NONE:
- for (attr = 0; attr < 16; attr++) {
- save->inputs[attr] = &vbo->legacy_currval[attr];
- }
- for (attr = 0; attr < MAT_ATTRIB_MAX; attr++) {
- save->inputs[attr + 16] = &vbo->mat_currval[attr];
- }
- map = vbo->map_vp_none;
- break;
- case VP_NV:
- case VP_ARB:
- /* The aliasing of attributes for NV vertex programs has already
- * occurred. NV vertex programs cannot access material values,
- * nor attributes greater than VERT_ATTRIB_TEX7.
- */
- for (attr = 0; attr < 16; attr++) {
- save->inputs[attr] = &vbo->legacy_currval[attr];
- save->inputs[attr + 16] = &vbo->generic_currval[attr];
- }
- map = vbo->map_vp_arb;
-
- /* check if VERT_ATTRIB_POS is not read but VERT_BIT_GENERIC0 is read.
- * In that case we effectively need to route the data from
- * glVertexAttrib(0, val) calls to feed into the GENERIC0 input.
- */
- if ((ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_POS) == 0 &&
- (ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_GENERIC0)) {
- save->inputs[16] = save->inputs[0];
- node_attrsz[16] = node_attrsz[0];
- node_attrsz[0] = 0;
- }
- break;
- default:
- assert(0);
- }
-
- for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
- const GLuint src = map[attr];
-
- if (node_attrsz[src]) {
- /* override the default array set above */
- save->inputs[attr] = &arrays[attr];
-
- arrays[attr].Ptr = (const GLubyte *) NULL + buffer_offset;
- arrays[attr].Size = node->attrsz[src];
- arrays[attr].StrideB = node->vertex_size * sizeof(GLfloat);
- arrays[attr].Stride = node->vertex_size * sizeof(GLfloat);
- arrays[attr].Type = GL_FLOAT;
- arrays[attr].Format = GL_RGBA;
- arrays[attr].Enabled = 1;
- _mesa_reference_buffer_object(ctx,
- &arrays[attr].BufferObj,
- node->vertex_store->bufferobj);
- arrays[attr]._MaxElement = node->count; /* ??? */
-
- assert(arrays[attr].BufferObj->Name);
-
- buffer_offset += node->attrsz[src] * sizeof(GLfloat);
- varying_inputs |= 1<<attr;
- ctx->NewState |= _NEW_ARRAY;
- }
- }
-
- _mesa_set_varying_vp_inputs( ctx, varying_inputs );
-}
-
-
-static void
-vbo_save_loopback_vertex_list(struct gl_context *ctx,
- const struct vbo_save_vertex_list *list)
-{
- const char *buffer = ctx->Driver.MapBuffer(ctx,
- GL_ARRAY_BUFFER_ARB,
- GL_READ_ONLY, /* ? */
- list->vertex_store->bufferobj);
-
- vbo_loopback_vertex_list(ctx,
- (const GLfloat *)(buffer + list->buffer_offset),
- list->attrsz,
- list->prim,
- list->prim_count,
- list->wrap_count,
- list->vertex_size);
-
- ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
- list->vertex_store->bufferobj);
-}
-
-
-/**
- * Execute the buffer and save copied verts.
- * This is called from the display list code when executing
- * a drawing command.
- */
-void
-vbo_save_playback_vertex_list(struct gl_context *ctx, void *data)
-{
- const struct vbo_save_vertex_list *node =
- (const struct vbo_save_vertex_list *) data;
- struct vbo_save_context *save = &vbo_context(ctx)->save;
-
- FLUSH_CURRENT(ctx, 0);
-
- if (node->prim_count > 0 && node->count > 0) {
-
- if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END &&
- node->prim[0].begin) {
-
- /* Degenerate case: list is called inside begin/end pair and
- * includes operations such as glBegin or glDrawArrays.
- */
- if (0)
- printf("displaylist recursive begin");
-
- vbo_save_loopback_vertex_list( ctx, node );
- return;
- }
- else if (save->replay_flags) {
- /* Various degnerate cases: translate into immediate mode
- * calls rather than trying to execute in place.
- */
- vbo_save_loopback_vertex_list( ctx, node );
- return;
- }
-
- if (ctx->NewState)
- _mesa_update_state( ctx );
-
- /* XXX also need to check if shader enabled, but invalid */
- if ((ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) ||
- (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled)) {
- _mesa_error(ctx, GL_INVALID_OPERATION,
- "glBegin (invalid vertex/fragment program)");
- return;
- }
-
- vbo_bind_vertex_list( ctx, node );
-
- /* Again...
- */
- if (ctx->NewState)
- _mesa_update_state( ctx );
-
- vbo_context(ctx)->draw_prims(ctx,
- save->inputs,
- node->prim,
- node->prim_count,
- NULL,
- GL_TRUE,
- 0, /* Node is a VBO, so this is ok */
- node->count - 1);
- }
-
- /* Copy to current?
- */
- _playback_copy_to_current( ctx, node );
-}
-
-
-#endif /* FEATURE_dlist */
+/*
+ * Mesa 3-D graphics library
+ * Version: 7.2
+ *
+ * Copyright (C) 1999-2008 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.
+ */
+
+/* Author:
+ * Keith Whitwell <keith@tungstengraphics.com>
+ */
+
+#include "main/glheader.h"
+#include "main/bufferobj.h"
+#include "main/context.h"
+#include "main/imports.h"
+#include "main/mfeatures.h"
+#include "main/mtypes.h"
+#include "main/macros.h"
+#include "main/light.h"
+#include "main/state.h"
+
+#include "vbo_context.h"
+
+
+#if FEATURE_dlist
+
+
+/**
+ * After playback, copy everything but the position from the
+ * last vertex to the saved state
+ */
+static void
+_playback_copy_to_current(struct gl_context *ctx,
+ const struct vbo_save_vertex_list *node)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ GLfloat vertex[VBO_ATTRIB_MAX * 4];
+ GLfloat *data;
+ GLuint i, offset;
+
+ if (node->current_size == 0)
+ return;
+
+ if (node->current_data) {
+ data = node->current_data;
+ }
+ else {
+ data = vertex;
+
+ if (node->count)
+ offset = (node->buffer_offset +
+ (node->count-1) * node->vertex_size * sizeof(GLfloat));
+ else
+ offset = node->buffer_offset;
+
+ ctx->Driver.GetBufferSubData( ctx, 0, offset,
+ node->vertex_size * sizeof(GLfloat),
+ data, node->vertex_store->bufferobj );
+
+ data += node->attrsz[0]; /* skip vertex position */
+ }
+
+ for (i = VBO_ATTRIB_POS+1 ; i < VBO_ATTRIB_MAX ; i++) {
+ if (node->attrsz[i]) {
+ GLfloat *current = (GLfloat *)vbo->currval[i].Ptr;
+ GLfloat tmp[4];
+
+ COPY_CLEAN_4V(tmp,
+ node->attrsz[i],
+ data);
+
+ if (memcmp(current, tmp, 4 * sizeof(GLfloat)) != 0) {
+ memcpy(current, tmp, 4 * sizeof(GLfloat));
+
+ vbo->currval[i].Size = node->attrsz[i];
+
+ if (i >= VBO_ATTRIB_FIRST_MATERIAL &&
+ i <= VBO_ATTRIB_LAST_MATERIAL)
+ ctx->NewState |= _NEW_LIGHT;
+
+ ctx->NewState |= _NEW_CURRENT_ATTRIB;
+ }
+
+ data += node->attrsz[i];
+ }
+ }
+
+ /* Colormaterial -- this kindof sucks.
+ */
+ if (ctx->Light.ColorMaterialEnabled) {
+ _mesa_update_color_material(ctx, ctx->Current.Attrib[VBO_ATTRIB_COLOR0]);
+ }
+
+ /* CurrentExecPrimitive
+ */
+ if (node->prim_count) {
+ const struct _mesa_prim *prim = &node->prim[node->prim_count - 1];
+ if (prim->end)
+ ctx->Driver.CurrentExecPrimitive = PRIM_OUTSIDE_BEGIN_END;
+ else
+ ctx->Driver.CurrentExecPrimitive = prim->mode;
+ }
+}
+
+
+
+/**
+ * Treat the vertex storage as a VBO, define vertex arrays pointing
+ * into it:
+ */
+static void vbo_bind_vertex_list(struct gl_context *ctx,
+ const struct vbo_save_vertex_list *node)
+{
+ struct vbo_context *vbo = vbo_context(ctx);
+ struct vbo_save_context *save = &vbo->save;
+ struct gl_client_array *arrays = save->arrays;
+ GLuint buffer_offset = node->buffer_offset;
+ const GLuint *map;
+ GLuint attr;
+ GLubyte node_attrsz[VBO_ATTRIB_MAX]; /* copy of node->attrsz[] */
+ GLbitfield varying_inputs = 0x0;
+
+ memcpy(node_attrsz, node->attrsz, sizeof(node->attrsz));
+
+ /* Install the default (ie Current) attributes first, then overlay
+ * all active ones.
+ */
+ switch (get_program_mode(ctx)) {
+ case VP_NONE:
+ for (attr = 0; attr < 16; attr++) {
+ save->inputs[attr] = &vbo->legacy_currval[attr];
+ }
+ for (attr = 0; attr < MAT_ATTRIB_MAX; attr++) {
+ save->inputs[attr + 16] = &vbo->mat_currval[attr];
+ }
+ map = vbo->map_vp_none;
+ break;
+ case VP_NV:
+ case VP_ARB:
+ /* The aliasing of attributes for NV vertex programs has already
+ * occurred. NV vertex programs cannot access material values,
+ * nor attributes greater than VERT_ATTRIB_TEX7.
+ */
+ for (attr = 0; attr < 16; attr++) {
+ save->inputs[attr] = &vbo->legacy_currval[attr];
+ save->inputs[attr + 16] = &vbo->generic_currval[attr];
+ }
+ map = vbo->map_vp_arb;
+
+ /* check if VERT_ATTRIB_POS is not read but VERT_BIT_GENERIC0 is read.
+ * In that case we effectively need to route the data from
+ * glVertexAttrib(0, val) calls to feed into the GENERIC0 input.
+ */
+ if ((ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_POS) == 0 &&
+ (ctx->VertexProgram._Current->Base.InputsRead & VERT_BIT_GENERIC0)) {
+ save->inputs[16] = save->inputs[0];
+ node_attrsz[16] = node_attrsz[0];
+ node_attrsz[0] = 0;
+ }
+ break;
+ default:
+ assert(0);
+ }
+
+ for (attr = 0; attr < VERT_ATTRIB_MAX; attr++) {
+ const GLuint src = map[attr];
+
+ if (node_attrsz[src]) {
+ /* override the default array set above */
+ save->inputs[attr] = &arrays[attr];
+
+ arrays[attr].Ptr = (const GLubyte *) NULL + buffer_offset;
+ arrays[attr].Size = node->attrsz[src];
+ arrays[attr].StrideB = node->vertex_size * sizeof(GLfloat);
+ arrays[attr].Stride = node->vertex_size * sizeof(GLfloat);
+ arrays[attr].Type = GL_FLOAT;
+ arrays[attr].Format = GL_RGBA;
+ arrays[attr].Enabled = 1;
+ _mesa_reference_buffer_object(ctx,
+ &arrays[attr].BufferObj,
+ node->vertex_store->bufferobj);
+ arrays[attr]._MaxElement = node->count; /* ??? */
+
+ assert(arrays[attr].BufferObj->Name);
+
+ buffer_offset += node->attrsz[src] * sizeof(GLfloat);
+ varying_inputs |= 1<<attr;
+ ctx->NewState |= _NEW_ARRAY;
+ }
+ }
+
+ _mesa_set_varying_vp_inputs( ctx, varying_inputs );
+}
+
+
+static void
+vbo_save_loopback_vertex_list(struct gl_context *ctx,
+ const struct vbo_save_vertex_list *list)
+{
+ const char *buffer = ctx->Driver.MapBuffer(ctx,
+ GL_ARRAY_BUFFER_ARB,
+ GL_READ_ONLY, /* ? */
+ list->vertex_store->bufferobj);
+
+ vbo_loopback_vertex_list(ctx,
+ (const GLfloat *)(buffer + list->buffer_offset),
+ list->attrsz,
+ list->prim,
+ list->prim_count,
+ list->wrap_count,
+ list->vertex_size);
+
+ ctx->Driver.UnmapBuffer(ctx, GL_ARRAY_BUFFER_ARB,
+ list->vertex_store->bufferobj);
+}
+
+
+/**
+ * Execute the buffer and save copied verts.
+ * This is called from the display list code when executing
+ * a drawing command.
+ */
+void
+vbo_save_playback_vertex_list(struct gl_context *ctx, void *data)
+{
+ const struct vbo_save_vertex_list *node =
+ (const struct vbo_save_vertex_list *) data;
+ struct vbo_save_context *save = &vbo_context(ctx)->save;
+
+ FLUSH_CURRENT(ctx, 0);
+
+ if (node->prim_count > 0 && node->count > 0) {
+
+ if (ctx->Driver.CurrentExecPrimitive != PRIM_OUTSIDE_BEGIN_END &&
+ node->prim[0].begin) {
+
+ /* Degenerate case: list is called inside begin/end pair and
+ * includes operations such as glBegin or glDrawArrays.
+ */
+ if (0)
+ printf("displaylist recursive begin");
+
+ vbo_save_loopback_vertex_list( ctx, node );
+ return;
+ }
+ else if (save->replay_flags) {
+ /* Various degnerate cases: translate into immediate mode
+ * calls rather than trying to execute in place.
+ */
+ vbo_save_loopback_vertex_list( ctx, node );
+ return;
+ }
+
+ if (ctx->NewState)
+ _mesa_update_state( ctx );
+
+ /* XXX also need to check if shader enabled, but invalid */
+ if ((ctx->VertexProgram.Enabled && !ctx->VertexProgram._Enabled) ||
+ (ctx->FragmentProgram.Enabled && !ctx->FragmentProgram._Enabled)) {
+ _mesa_error(ctx, GL_INVALID_OPERATION,
+ "glBegin (invalid vertex/fragment program)");
+ return;
+ }
+
+ vbo_bind_vertex_list( ctx, node );
+
+ /* Again...
+ */
+ if (ctx->NewState)
+ _mesa_update_state( ctx );
+
+ vbo_context(ctx)->draw_prims(ctx,
+ save->inputs,
+ node->prim,
+ node->prim_count,
+ NULL,
+ GL_TRUE,
+ 0, /* Node is a VBO, so this is ok */
+ node->count - 1);
+ }
+
+ /* Copy to current?
+ */
+ _playback_copy_to_current( ctx, node );
+}
+
+
+#endif /* FEATURE_dlist */