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