gl_enums.py revision 848b8605
1#!/usr/bin/python2
2# -*- Mode: Python; py-indent-offset: 8 -*-
3
4# (C) Copyright Zack Rusin 2005
5# All Rights Reserved.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a
8# copy of this software and associated documentation files (the "Software"),
9# to deal in the Software without restriction, including without limitation
10# on the rights to use, copy, modify, merge, publish, distribute, sub
11# license, and/or sell copies of the Software, and to permit persons to whom
12# the Software is furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice (including the next
15# paragraph) shall be included in all copies or substantial portions of the
16# Software.
17#
18# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
21# IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24# IN THE SOFTWARE.
25#
26# Authors:
27#    Zack Rusin <zack@kde.org>
28
29import license
30import gl_XML
31import sys, getopt
32
33class PrintGlEnums(gl_XML.gl_print_base):
34
35    def __init__(self):
36        gl_XML.gl_print_base.__init__(self)
37
38        self.name = "gl_enums.py (from Mesa)"
39        self.license = license.bsd_license_template % ( \
40"""Copyright (C) 1999-2005 Brian Paul All Rights Reserved.""", "BRIAN PAUL")
41        self.enum_table = {}
42
43
44    def printRealHeader(self):
45        print '#include "main/glheader.h"'
46        print '#include "main/enums.h"'
47        print '#include "main/imports.h"'
48        print '#include "main/mtypes.h"'
49        print ''
50        print 'typedef struct PACKED {'
51        print '   uint16_t offset;'
52        print '   int n;'
53        print '} enum_elt;'
54        print ''
55        return
56
57    def print_code(self):
58        print """
59typedef int (*cfunc)(const void *, const void *);
60
61/**
62 * Compare a key enum value to an element in the \c enum_string_table_offsets array.
63 *
64 * \c bsearch always passes the key as the first parameter and the pointer
65 * to the array element as the second parameter.  We can elimiate some
66 * extra work by taking advantage of that fact.
67 *
68 * \param a  Pointer to the desired enum name.
69 * \param b  Pointer into the \c enum_string_table_offsets array.
70 */
71static int compar_nr( const int *a, enum_elt *b )
72{
73   return a[0] - b->n;
74}
75
76
77static char token_tmp[20];
78
79const char *_mesa_lookup_enum_by_nr( int nr )
80{
81   enum_elt *elt;
82
83   STATIC_ASSERT(sizeof(enum_string_table) < (1 << 16));
84
85   elt = _mesa_bsearch(& nr, enum_string_table_offsets,
86                       Elements(enum_string_table_offsets),
87                       sizeof(enum_string_table_offsets[0]),
88                       (cfunc) compar_nr);
89
90   if (elt != NULL) {
91      return &enum_string_table[elt->offset];
92   }
93   else {
94      /* this is not re-entrant safe, no big deal here */
95      _mesa_snprintf(token_tmp, sizeof(token_tmp) - 1, "0x%x", nr);
96      token_tmp[sizeof(token_tmp) - 1] = '\\0';
97      return token_tmp;
98   }
99}
100
101/**
102 * Primitive names
103 */
104static const char *prim_names[PRIM_MAX+3] = {
105   "GL_POINTS",
106   "GL_LINES",
107   "GL_LINE_LOOP",
108   "GL_LINE_STRIP",
109   "GL_TRIANGLES",
110   "GL_TRIANGLE_STRIP",
111   "GL_TRIANGLE_FAN",
112   "GL_QUADS",
113   "GL_QUAD_STRIP",
114   "GL_POLYGON",
115   "GL_LINES_ADJACENCY",
116   "GL_LINE_STRIP_ADJACENCY",
117   "GL_TRIANGLES_ADJACENCY",
118   "GL_TRIANGLE_STRIP_ADJACENCY",
119   "outside begin/end",
120   "unknown state"
121};
122
123
124/* Get the name of an enum given that it is a primitive type.  Avoids
125 * GL_FALSE/GL_POINTS ambiguity and others.
126 */
127const char *
128_mesa_lookup_prim_by_nr(GLuint nr)
129{
130   if (nr < Elements(prim_names))
131      return prim_names[nr];
132   else
133      return "invalid mode";
134}
135
136
137"""
138        return
139
140
141    def printBody(self, api_list):
142        self.enum_table = {}
143        for api in api_list:
144            self.process_enums( api )
145
146        enum_table = []
147
148        for enum in sorted(self.enum_table.keys()):
149            low_pri = 9
150            best_name = ''
151            for [name, pri] in self.enum_table[ enum ]:
152                if pri < low_pri:
153                    low_pri = pri
154                    best_name = name
155
156            enum_table.append((enum, best_name))
157
158        string_offsets = {}
159        i = 0;
160        print 'LONGSTRING static const char enum_string_table[] = '
161        for enum, name in enum_table:
162            print '   "%s\\0"' % (name)
163            string_offsets[ enum ] = i
164            i += len(name) + 1
165
166        print '   ;'
167        print ''
168
169
170        print 'static const enum_elt enum_string_table_offsets[%u] =' % (len(enum_table))
171        print '{'
172        for enum, name in enum_table:
173            print '   { %5u, 0x%08X }, /* %s */' % (string_offsets[enum], enum, name)
174        print '};'
175        print ''
176
177        self.print_code()
178        return
179
180
181    def process_enums(self, api):
182        for obj in api.enumIterateByName():
183            if obj.value not in self.enum_table:
184                self.enum_table[ obj.value ] = []
185
186
187            enum = self.enum_table[ obj.value ]
188            name = "GL_" + obj.name
189            priority = obj.priority()
190            already_in = False;
191            for n, p in enum:
192                if n == name:
193                    already_in = True
194            if not already_in:
195                enum.append( [name, priority] )
196
197
198def show_usage():
199    print "Usage: %s [-f input_file_name]" % sys.argv[0]
200    sys.exit(1)
201
202if __name__ == '__main__':
203    try:
204        (args, trail) = getopt.getopt(sys.argv[1:], "f:")
205    except Exception,e:
206        show_usage()
207
208    api_list = []
209    for (arg,val) in args:
210        if arg == "-f":
211            api = gl_XML.parse_GL_API( val )
212            api_list.append(api);
213
214    printer = PrintGlEnums()
215    printer.Print( api_list )
216