gen_interpolation_tests.py 16.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# coding=utf-8
#
# Copyright © 2011 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.

# Correct interpolation of vertex shader outputs depends on (a)
# whether an interpolation qualifier is present in the shader source,
# and if so which qualifier is used, (b) if no interpolation qualifier
# is present, whether the output is a user-defined variable or a
# built-in color, and (c) if the output is a built-in color, the
# setting of the ShadeModel() setting.  In addition, we would like to
# test correct interpolation under various clipping scenarios.
#
# To verify that all the combinations of these possibilities work
# correctly, this script generates a shader_runner test to check
# proper interpolation for every combination of the following
# variables:
#
# - which interpolation qualifier is used ("flat", "noperspective",
#   "smooth", or no qualifier)
#
# - which variable is used (gl_FrontColor, gl_BackColor,
#   gl_FrontSecondaryColor, gl_BackSecondaryColor, or a non-built-in
#   variable)
#
# - the setting of ShadeModel() (either GL_SMOOTH or GL_FLAT)
#
# - whether the triangle in question is clipped using gl_ClipVertex,
#   clipped using gl_ClipDistance, clipped against the fixed viewing
#   volume, or unclipped.
#
# The tests operate by drawing a triangle with a different value of
# the variable at each vertex, and then probing within the interior of
# the triangle to verify that interpolation was performed correctly.
# The triangle is drawn in a frustum projection, with a different z
# value for each vertex, so that there will be a detectable difference
# in behavior between noperspective and smooth interpolation.
#
# When testing clipping, we clip off the frontmost corner of the
# triangle; this ensures that the proportion of the triangle's screen
# real estate that is clipped is significantly larger than the
# proportion of the triangle's 3D coordinate space that is clipped.
# So if the GL implementation doesn't perform perspective-correct
# interpolation generating clipped vertices, we will notice.
#
# This program outputs, to stdout, the name of each file it generates.

import os


class Test(object):
    def __init__(self, interpolation_qualifier, variable, shade_model,
71
72
                 clipping):
        """Get ready to generate a test using the given settings.
73

74
75
76
77
        interpolation_qualifier is a string representing the desired
        interpolation qualifier that should appear in GLSL code
        ('flat', 'noperspective', or 'smooth'), or None if no
        qualifier should appear.
78

79
80
81
82
83
84
85
        variable is the name of the variable on which to test
        interpolation.  If the name begins with 'gl_', it should be
        one of the four vertex shader variables that are allowed to be
        redeclared with an interpolation qualifier (see GLSL 1.30
        section 4.3.7 "Interpolation").  Namely: gl_FrontColor,
        gl_BackColor, gl_FrontSecondaryColor, or
        gl_BackSecondaryColor.
86

87
88
        shade_model is which shade model the GL state should be put in
        using the glShadeModel() command--either 'smooth' or 'flat'.
89

90
91
92
93
94
95
96
97
98
99
100
        clipping is the variety of clipping which should be tested:
        either 'fixed' to test a triangle that extends beyond the
        fixed view volume (we test clipping against the "near" plane),
        'vertex' to test a triangle which has one corner clipped using
        gl_ClipVertex, or 'distance' to test a triangle which has one
        corner clipped using gl_ClipDistance.
        """
        self.interpolation_qualifier = interpolation_qualifier
        self.vs_variable = variable
        self.shade_model = shade_model
        self.clipping = clipping
101

102
103
104
105
106
        # When colors are mapped into the fragment shader, the string
        # 'Front' or 'Back' is dropped from the variable name, since
        # e.g. gl_Color is mapped to gl_FrontColor for front-facing
        # triangles, and gl_BackColor for back-facing triangles.
        self.fs_variable = variable.replace('Front', '').replace('Back', '')
107

108
109
110
        # True if we are testing a BackColor, so we'll need to draw a
        # back-facing triangle.
        self.backfacing = variable.find('Back') != -1
111

112
113
114
        # True if we are testing a built-in color variable, False if
        # we are testing a generic vertex shader output.
        self.builtin_variable = variable[:3] == 'gl_'
115

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        # Determine whether the test requires GLSL 1.30.  If it does,
        # use "in" and "out" to qualify shader inputs and outputs.
        # Otherwise use the old keywords "attribute" and "varying".
        # shader_runner will insert a #version directive based on
        # glsl_version.
        if self.interpolation_qualifier or self.clipping == 'distance':
            self.glsl_version = '1.30'
            self.vs_input = 'in'
            self.vs_output = 'out'
            self.fs_input = 'in'
        else:
            self.glsl_version = '1.10'
            self.vs_input = 'attribute'
            self.vs_output = 'varying'
            self.fs_input = 'varying'
131

132
133
134
135
136
137
138
139
140
        # Determine the location of the near and far planes for the
        # frustum projection.  The triangle fits between z coordinates
        # -1 and -3; we use 1.75 as the near plane when we want to
        # force clipping.
        if self.clipping == 'fixed':
            self.frustum_near = 1.75
        else:
            self.frustum_near = 1.0
        self.frustum_far = 3.0
141

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        # Determine whether we expect the GL implementation to use
        # flatshading, non-perspective interpolation, or perspective
        # interpolation.
        if self.interpolation_qualifier:
            # According to GLSL 1.30 section 4.3.7 ("Interpolation"),
            # "When an interpolation qualifier is used, it overrides
            # settings established through the OpenGL API."
            self.expected_behavior = self.interpolation_qualifier
        elif self.builtin_variable:
            # According to GL 3.0 section 2.19.7 ("Flatshading"), "If
            # a vertex shader is active, the flat shading control
            # applies to the built-in varying variables gl FrontColor,
            # gl BackColor, gl FrontSecondaryColor and gl
            # BackSecondaryColor.  Non-color varying variables can be
            # specified as being flat-shaded via the flat qualifier,
            # as described in section 4.3.6 of the OpenGL Shading
            # Language Specification."
            self.expected_behavior = self.shade_model
        else:
            # The specs do not explicitly state how non-built-in
            # variables are to be interpolated in the case where no
            # interpolation qualifier is used.  However, it seems to
            # be heavily implied by the text of GL 3.0 section 2.19.6
            # ("Flatshading"--see above) that smooth
            # (perspective-correct) interpolation is intended,
            # regardless of the setting of glShadeModel().
            self.expected_behavior = 'smooth'
169
170

    def filename(self):
171
172
173
174
175
176
        return os.path.join(
            'spec', 'glsl-{0}'.format(self.glsl_version),
            'execution', 'interpolation',
            'interpolation-{0}-{1}-{2}-{3}.shader_test'.format(
                self.interpolation_qualifier or 'none', self.vs_variable,
                self.shade_model, self.clipping or 'none'))
177
178

    def vertex_data(self):
179
180
181
182
183
184
185
186
187
188
189
190
191
        table = ['vertex/float/3  input_data/float/4',
                 '-1.0 -1.0 -1.0  1.0 0.0 0.0 1.0',
                 ' 0.0  2.0 -2.0  0.0 1.0 0.0 1.0',
                 ' 3.0 -3.0 -3.0  0.0 0.0 1.0 1.0']
        if not self.backfacing:
            # The vertices above are ordered such that the front of
            # the triangle faces away from the viewer.  If we are
            # trying to render the front face, then swap the first two
            # vertices.  This shows us the front face of the triangle
            # without changing the provoking vertex (which is the
            # third vertex).
            table = [table[0], table[2], table[1], table[3]]
        return table
192
193

    def probe_data(self):
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        # Loop over possible barycentric coordinates with a spacing of
        # 1/num_subdivisions.  Skip points on the triangle edges and
        # corners so that rounding does not cause us to accidentally
        # probe a pixel that's outside the triangle.
        num_subdivisions = 6
        for i in xrange(1, num_subdivisions - 1):
            for j in xrange(1, num_subdivisions - i):
                # Compute 3D barycentric coordinates--these will be
                # used to compute the expected interpolated values
                # when using smooth (perspective-correct)
                # interpolation.  The vertex associated with b3d_0=1.0
                # is colored red, the vertex associated with b3d_1=1.0
                # is colored green, and the vertex associated with
                # b3d_2=1.0 is colored blue.
                b3d_0 = float(num_subdivisions - i - j)/num_subdivisions
                b3d_1 = float(i)/num_subdivisions
                b3d_2 = float(j)/num_subdivisions
                # Compute 3D coordinates based on those barycentric
                # coordinates.  These will be used, among other
                # things, to determine whether this part of the
                # triangle is clipped.
                x3d = -b3d_0 + 3.0*b3d_2
                y3d = -b3d_0 + 2.0*b3d_1 - 3.0*b3d_2
                z3d = -b3d_0 - 2.0*b3d_1 - 3.0*b3d_2
                # Use perspective division to compute 2D screen
                # coordinates.  These will be used with "relative
                # probe rgba", which treats the lower left corner of
                # the screen as (0, 0) and the upper right is (1, 1).
                x2d = (-x3d/z3d + 1.0) / 2.0
                y2d = (-y3d/z3d + 1.0) / 2.0
                # Finally, compute a second set of barycentric
                # coordinates based on the 2D screen
                # coordinates--these will be used to compute the
                # expected interpolated values when using
                # noperspective (screen-coordinate) interpolation.
                b2d_0 = 1.0 - x2d - 0.5*y2d
                b2d_1 = y2d
                b2d_2 = x2d - 0.5*y2d
232

233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
                if self.clipping and -z3d < 1.75:
                    # Points whose -z coordinate is less than 1.75
                    # should be clipped.
                    yield x2d, y2d, 0.0, 0.0, 0.0, 0.0
                elif self.expected_behavior == 'flat':
                    # When flatshading, all points on the triangle
                    # should inherit the color of the third vertex,
                    # which is blue.
                    yield x2d, y2d, 0.0, 0.0, 1.0, 1.0
                elif self.expected_behavior == 'noperspective':
                    # Since the 3 triangle vertices are red, green,
                    # and blue, the interpolated color channels should
                    # be exactly equal to the barycentric coordinates.
                    # For "noperspective" shading, we use the
                    # barycentric coordinates that we computed based
                    # on 2D screen position.
                    yield x2d, y2d, b2d_0, b2d_1, b2d_2, 1.0
                else:
                    # For "smooth" (perspective correct) shading, we
                    # use the barycentric coordinates that we used to
                    # compute the 3D position.
                    assert self.expected_behavior == 'smooth'
                    yield x2d, y2d, b3d_0, b3d_1, b3d_2, 1.0
256
257

    def generate(self):
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
        if self.builtin_variable:
            test = '# Test proper interpolation of {0}\n'.format(
                self.vs_variable)
        else:
            test = '# Test proper interpolation of a non-built-in variable\n'
        if self.interpolation_qualifier:
            test += '# When qualified with {0!r}\n'.format(
                self.interpolation_qualifier)
        else:
            test += '# When no interpolation qualifier present\n'
        test += '# And ShadeModel is {0!r}\n'.format(self.shade_model)
        if self.clipping == 'fixed':
            test += '# And clipping via fixed planes\n'
        elif self.clipping == 'vertex':
            test += '# And clipping via gl_ClipVertex\n'
        elif self.clipping == 'distance':
            test += '# And clipping via gl_ClipDistance\n'
        else:
            assert self.clipping is None
        test += '[require]\n'
        test += 'GLSL >= {0}\n'.format(self.glsl_version)
        test += '\n'
        test += '[vertex shader]\n'
        test += '{0} vec4 vertex;\n'.format(self.vs_input)
        test += '{0} vec4 input_data;\n'.format(self.vs_input)
        if self.interpolation_qualifier or not self.builtin_variable:
            test += '{0} {1} vec4 {2};'.format(
                self.interpolation_qualifier or '',
                self.vs_output, self.vs_variable).strip() + '\n'
        test += 'void main()\n'
        test += '{\n'
        test += '  gl_Position = gl_ModelViewProjectionMatrix * vertex;\n'
        test += '  {0} = input_data;\n'.format(self.vs_variable)
        if self.clipping == 'distance':
            test += '  gl_ClipDistance[0] = -1.75 - vertex.z;\n'
        elif self.clipping == 'vertex':
            test += '  gl_ClipVertex = vertex;\n'
        test += '}\n'
        test += '\n'
        test += '[fragment shader]\n'
        if self.interpolation_qualifier or not self.builtin_variable:
            test += '{0} {1} vec4 {2};'.format(
                self.interpolation_qualifier or '',
                self.fs_input, self.fs_variable).strip() + '\n'
        test += 'void main()\n'
        test += '{\n'
        test += '  gl_FragColor = {0};\n'.format(self.fs_variable)
        test += '}\n'
        test += '\n'
        test += '[vertex data]\n'
        test += ''.join(s + '\n' for s in self.vertex_data())
        test += '\n'
        test += '[test]\n'
        test += 'frustum -{0} {0} -{0} {0} {0} {1}\n'.format(
            self.frustum_near, self.frustum_far)
        test += 'clear color 0.0 0.0 0.0 0.0\n'
        test += 'clear\n'
        test += 'enable GL_VERTEX_PROGRAM_TWO_SIDE\n'
        test += 'shade model {0}\n'.format(self.shade_model)
        if self.clipping == 'distance' or self.clipping == 'vertex':
            test += 'enable GL_CLIP_PLANE0\n'
        if self.clipping == 'vertex':
            test += 'clip plane 0 0.0 0.0 -1.0 -1.75\n'
        test += 'draw arrays GL_TRIANGLES 0 3\n'
        for x, y, r, g, b, a in self.probe_data():
            test += ('relative probe rgba ({0}, {1}) ({2}, {3}, {4}, {5})\n'
                     .format(x, y, r, g, b, a))
        filename = self.filename()
        dirname = os.path.dirname(filename)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        with open(filename, 'w') as f:
            f.write(test)
331
332
333
334


def all_tests():
    for interpolation_qualifier in ['flat', 'smooth', 'noperspective', None]:
335
336
337
338
339
340
341
        for variable in ['gl_FrontColor', 'gl_BackColor',
                         'gl_FrontSecondaryColor', 'gl_BackSecondaryColor',
                         'other']:
            for shade_model in ['smooth', 'flat']:
                for clipping in ['vertex', 'distance', 'fixed', None]:
                    yield Test(interpolation_qualifier, variable, shade_model,
                               clipping)
342
343
344
345


def main():
    for test in all_tests():
346
347
        test.generate()
        print test.filename()
348
349
350
351


if __name__ == '__main__':
    main()