• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python3
2# Copyright 2016 The ANGLE Project Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5#
6# angle_format.py:
7#  Utils for ANGLE formats.
8
9import json
10import os
11import re
12
13kChannels = "ABDEGLRSX"
14
15
16def get_angle_format_map_abs_path():
17    return os.path.join(os.path.dirname(os.path.realpath(__file__)), 'angle_format_map.json')
18
19
20def reject_duplicate_keys(pairs):
21    found_keys = {}
22    for key, value in pairs:
23        if key in found_keys:
24            raise ValueError("duplicate key: %r" % (key,))
25        else:
26            found_keys[key] = value
27    return found_keys
28
29
30def load_json(path):
31    with open(path) as map_file:
32        return json.loads(map_file.read(), object_pairs_hook=reject_duplicate_keys)
33
34
35def load_forward_table(path):
36    pairs = load_json(path)
37    reject_duplicate_keys(pairs)
38    return {gl: angle for gl, angle in pairs}
39
40
41def load_inverse_table(path):
42    pairs = load_json(path)
43    reject_duplicate_keys(pairs)
44    for x in range(0, 8):
45        pairs.append(("GL_NONE", "EXTERNAL" + str(x)))
46    return {angle: gl for gl, angle in pairs}
47
48
49def load_without_override():
50    map_path = get_angle_format_map_abs_path()
51    return load_forward_table(map_path)
52
53
54def load_with_override(override_path):
55    results = load_without_override()
56    overrides = load_json(override_path)
57
58    for k, v in sorted(overrides.items()):
59        results[k] = v
60
61    return results
62
63
64def get_all_angle_formats():
65    map_path = get_angle_format_map_abs_path()
66    return load_inverse_table(map_path).keys()
67
68
69def get_component_type(format_id):
70    if "SNORM" in format_id:
71        return "snorm"
72    elif "UNORM" in format_id:
73        return "unorm"
74    elif "FLOAT" in format_id:
75        return "float"
76    elif "FIXED" in format_id:
77        return "float"
78    elif "UINT" in format_id:
79        return "uint"
80    elif "SINT" in format_id:
81        return "int"
82    elif "USCALED" in format_id:
83        return "uint"
84    elif "SSCALED" in format_id:
85        return "int"
86    elif format_id == "NONE":
87        return "none"
88    elif "SRGB" in format_id:
89        return "unorm"
90    elif "TYPELESS" in format_id:
91        return "unorm"
92    elif "EXTERNAL" in format_id:
93        return "unorm"
94    elif format_id == "R9G9B9E5_SHAREDEXP":
95        return "float"
96    else:
97        raise ValueError("Unknown component type for " + format_id)
98
99
100def get_channel_tokens(format_id):
101    if 'EXTERNAL' in format_id:
102        return ['R8', 'G8', 'B8', 'A8']
103    r = re.compile(r'([' + kChannels + '][\d]+)')
104    return list(filter(r.match, r.split(format_id)))
105
106
107def get_channels(format_id):
108    channels = ''
109    tokens = get_channel_tokens(format_id)
110    if len(tokens) == 0:
111        return None
112    for token in tokens:
113        channels += token[0].lower()
114
115    return channels
116
117
118def get_bits(format_id):
119    bits = {}
120    if "_RED_" in format_id:
121        # BC4
122        bits["R"] = 16
123    elif "_RG_" in format_id:
124        # BC5
125        bits["R"] = bits["G"] = 16
126    elif "_RGB_" in format_id:
127        # BC1-3, BC6H, PVRTC
128        bits["R"] = bits["G"] = bits["B"] = 16 if "BC6H" in format_id else 8
129    elif "_RGBA_" in format_id or "ASTC_" in format_id:
130        # ASTC, BC7, PVRTC
131        bits["R"] = bits["G"] = bits["B"] = bits["A"] = 8
132    else:
133        tokens = get_channel_tokens(format_id)
134        for token in tokens:
135            bits[token[0]] = int(token[1:])
136    return bits
137
138
139def get_format_info(format_id):
140    return get_component_type(format_id), get_bits(format_id), get_channels(format_id)
141
142
143# TODO(oetuaho): Expand this code so that it could generate the gl format info tables as well.
144def gl_format_channels(internal_format):
145    if internal_format == 'GL_BGR5_A1_ANGLEX':
146        return 'bgra'
147    if internal_format == 'GL_R11F_G11F_B10F':
148        return 'rgb'
149    if internal_format == 'GL_RGB5_A1':
150        return 'rgba'
151    if internal_format.find('GL_RGB10_A2') == 0:
152        return 'rgba'
153    if internal_format == 'GL_RGB10_UNORM_ANGLEX':
154        return 'rgb'
155    # signed/unsigned int_10_10_10_2 for vertex format
156    if internal_format.find('INT_10_10_10_2_OES') == 0:
157        return 'rgba'
158
159    channels_pattern = re.compile('GL_(COMPRESSED_)?(SIGNED_)?(ETC\d_)?([A-Z]+)')
160    match = re.search(channels_pattern, internal_format)
161    channels_string = match.group(4)
162
163    if channels_string == 'ALPHA':
164        return 'a'
165    if channels_string == 'LUMINANCE':
166        if (internal_format.find('ALPHA') >= 0):
167            return 'la'
168        return 'l'
169    if channels_string == 'SRGB' or channels_string == 'RGB':
170        if (internal_format.find('ALPHA') >= 0):
171            return 'rgba'
172        return 'rgb'
173    if channels_string == 'DEPTH':
174        if (internal_format.find('STENCIL') >= 0):
175            return 'ds'
176        return 'd'
177    if channels_string == 'STENCIL':
178        return 's'
179    return channels_string.lower()
180
181
182def get_internal_format_initializer(internal_format, format_id):
183    gl_channels = gl_format_channels(internal_format)
184    gl_format_no_alpha = gl_channels == 'rgb' or gl_channels == 'l'
185    component_type, bits, channels = get_format_info(format_id)
186
187    # ETC2 punchthrough formats have per-pixel alpha values but a zero-filled block is parsed as opaque black.
188    # Ensure correct initialization when the formats are emulated.
189    if 'PUNCHTHROUGH_ALPHA1_ETC2' in internal_format and 'ETC2' not in format_id:
190        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0xFF>'
191
192    if not gl_format_no_alpha or channels != 'rgba':
193        return 'nullptr'
194
195    elif internal_format == 'GL_RGB10_UNORM_ANGLEX':
196        return 'nullptr'
197
198    elif 'BC1_' in format_id:
199        # BC1 is a special case since the texture data determines whether each block has an alpha channel or not.
200        # This if statement is hit by COMPRESSED_RGB_S3TC_DXT1, which is a bit of a mess.
201        # TODO(oetuaho): Look into whether COMPRESSED_RGB_S3TC_DXT1 works right in general.
202        # Reference: https://www.opengl.org/registry/specs/EXT/texture_compression_s3tc.txt
203        return 'nullptr'
204
205    elif component_type == 'uint' and bits['R'] == 8:
206        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0x01>'
207    elif component_type == 'unorm' and bits['R'] == 8:
208        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0xFF>'
209    elif component_type == 'unorm' and bits['R'] == 16:
210        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0xFFFF>'
211    elif component_type == 'int' and bits['R'] == 8:
212        return 'Initialize4ComponentData<GLbyte, 0x00, 0x00, 0x00, 0x01>'
213    elif component_type == 'snorm' and bits['R'] == 8:
214        return 'Initialize4ComponentData<GLbyte, 0x00, 0x00, 0x00, 0x7F>'
215    elif component_type == 'snorm' and bits['R'] == 16:
216        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0x7FFF>'
217    elif component_type == 'float' and bits['R'] == 16:
218        return 'Initialize4ComponentData<GLhalf, 0x0000, 0x0000, 0x0000, gl::Float16One>'
219    elif component_type == 'uint' and bits['R'] == 16:
220        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0x0001>'
221    elif component_type == 'int' and bits['R'] == 16:
222        return 'Initialize4ComponentData<GLshort, 0x0000, 0x0000, 0x0000, 0x0001>'
223    elif component_type == 'float' and bits['R'] == 32:
224        return 'Initialize4ComponentData<GLfloat, 0x00000000, 0x00000000, 0x00000000, gl::Float32One>'
225    elif component_type == 'int' and bits['R'] == 32:
226        return 'Initialize4ComponentData<GLint, 0x00000000, 0x00000000, 0x00000000, 0x00000001>'
227    elif component_type == 'uint' and bits['R'] == 32:
228        return 'Initialize4ComponentData<GLuint, 0x00000000, 0x00000000, 0x00000000, 0x00000001>'
229    else:
230        raise ValueError(
231            'warning: internal format initializer could not be generated and may be needed for ' +
232            internal_format)
233
234
235def get_format_gl_type(format):
236    sign = ''
237    base_type = None
238    if 'FLOAT' in format:
239        bits = get_bits(format)
240        redbits = bits and bits.get('R')
241        base_type = 'float'
242        if redbits == 16:
243            base_type = 'half'
244    else:
245        bits = get_bits(format)
246        redbits = bits and bits.get('R')
247        if redbits == 8:
248            base_type = 'byte'
249        elif redbits == 16:
250            base_type = 'short'
251        elif redbits == 32:
252            base_type = 'int'
253
254        if 'UINT' in format or 'UNORM' in format or 'USCALED' in format:
255            sign = 'u'
256
257    if base_type is None:
258        return None
259
260    return 'GL' + sign + base_type
261
262
263def get_vertex_copy_function(src_format, dst_format):
264    if dst_format == "NONE":
265        return "nullptr"
266
267    src_num_channel = len(get_channel_tokens(src_format))
268    dst_num_channel = len(get_channel_tokens(dst_format))
269    if src_num_channel < 1 or src_num_channel > 4:
270        return "nullptr"
271
272    if src_format.endswith('_VERTEX'):
273        assert 'FLOAT' in dst_format, (
274            'get_vertex_copy_function: can only convert to float,' + ' not to ' + dst_format)
275        is_signed = 'true' if 'SINT' in src_format or 'SNORM' in src_format or 'SSCALED' in src_format else 'false'
276        is_normal = 'true' if 'NORM' in src_format else 'false'
277        if 'A2' in src_format:
278            return 'CopyW2XYZ10ToXYZWFloatVertexData<%s, %s, true>' % (is_signed, is_normal)
279        else:
280            return 'CopyXYZ10ToXYZWFloatVertexData<%s, %s, true>' % (is_signed, is_normal)
281
282    if 'FIXED' in src_format:
283        assert 'FLOAT' in dst_format, (
284            'get_vertex_copy_function: can only convert fixed to float,' + ' not to ' + dst_format)
285        return 'Copy32FixedTo32FVertexData<%d, %d>' % (src_num_channel, dst_num_channel)
286
287    src_gl_type = get_format_gl_type(src_format)
288    dst_gl_type = get_format_gl_type(dst_format)
289
290    if src_gl_type == None:
291        return "nullptr"
292
293    if src_gl_type == dst_gl_type:
294        default_alpha = '1'
295
296        if src_num_channel == dst_num_channel or dst_num_channel < 4:
297            default_alpha = '0'
298        elif 'A16_FLOAT' in dst_format:
299            default_alpha = 'gl::Float16One'
300        elif 'A32_FLOAT' in dst_format:
301            default_alpha = 'gl::Float32One'
302        elif 'NORM' in dst_format:
303            default_alpha = 'std::numeric_limits<%s>::max()' % (src_gl_type)
304
305        return 'CopyNativeVertexData<%s, %d, %d, %s>' % (src_gl_type, src_num_channel,
306                                                         dst_num_channel, default_alpha)
307
308    assert 'FLOAT' in dst_format, (
309        'get_vertex_copy_function: can only convert to float,' + ' not to ' + dst_format)
310    normalized = 'true' if 'NORM' in src_format else 'false'
311
312    dst_is_half = 'true' if dst_gl_type == 'GLhalf' else 'false'
313    return "CopyToFloatVertexData<%s, %d, %d, %s, %s>" % (src_gl_type, src_num_channel,
314                                                          dst_num_channel, normalized, dst_is_half)
315