• 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    if "_RED_" in format_id:
115        # BC4
116        bits["R"] = 16
117    elif "_RG_" in format_id:
118        # BC5
119        bits["R"] = bits["G"] = 16
120    elif "_RGB_" in format_id:
121        # BC1-3, BC6H, PVRTC
122        bits["R"] = bits["G"] = bits["B"] = 16 if "BC6H" in format_id else 8
123    elif "_RGBA_" in format_id or "ASTC_" in format_id:
124        # ASTC, BC7, PVRTC
125        bits["R"] = bits["G"] = bits["B"] = bits["A"] = 8
126    else:
127        tokens = get_channel_tokens(format_id)
128        for token in tokens:
129            bits[token[0]] = int(token[1:])
130    return bits
131
132
133def get_format_info(format_id):
134    return get_component_type(format_id), get_bits(format_id), get_channels(format_id)
135
136
137# TODO(oetuaho): Expand this code so that it could generate the gl format info tables as well.
138def gl_format_channels(internal_format):
139    if internal_format == 'GL_BGR5_A1_ANGLEX':
140        return 'bgra'
141    if internal_format == 'GL_R11F_G11F_B10F':
142        return 'rgb'
143    if internal_format == 'GL_RGB5_A1':
144        return 'rgba'
145    if internal_format.find('GL_RGB10_A2') == 0:
146        return 'rgba'
147    if internal_format == 'GL_RGB10_UNORM_ANGLEX':
148        return 'rgb'
149    # signed/unsigned int_10_10_10_2 for vertex format
150    if internal_format.find('INT_10_10_10_2_OES') == 0:
151        return 'rgba'
152
153    channels_pattern = re.compile('GL_(COMPRESSED_)?(SIGNED_)?(ETC\d_)?([A-Z]+)')
154    match = re.search(channels_pattern, internal_format)
155    channels_string = match.group(4)
156
157    if channels_string == 'ALPHA':
158        return 'a'
159    if channels_string == 'LUMINANCE':
160        if (internal_format.find('ALPHA') >= 0):
161            return 'la'
162        return 'l'
163    if channels_string == 'SRGB' or channels_string == 'RGB':
164        if (internal_format.find('ALPHA') >= 0):
165            return 'rgba'
166        return 'rgb'
167    if channels_string == 'DEPTH':
168        if (internal_format.find('STENCIL') >= 0):
169            return 'ds'
170        return 'd'
171    if channels_string == 'STENCIL':
172        return 's'
173    return channels_string.lower()
174
175
176def get_internal_format_initializer(internal_format, format_id):
177    gl_channels = gl_format_channels(internal_format)
178    gl_format_no_alpha = gl_channels == 'rgb' or gl_channels == 'l'
179    component_type, bits, channels = get_format_info(format_id)
180
181    # ETC2 punchthrough formats have per-pixel alpha values but a zero-filled block is parsed as opaque black.
182    # Ensure correct initialization when the formats are emulated.
183    if 'PUNCHTHROUGH_ALPHA1_ETC2' in internal_format and 'ETC2' not in format_id:
184        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0xFF>'
185
186    if not gl_format_no_alpha or channels != 'rgba':
187        return 'nullptr'
188
189    elif internal_format == 'GL_RGB10_UNORM_ANGLEX':
190        return 'nullptr'
191
192    elif 'BC1_' in format_id:
193        # BC1 is a special case since the texture data determines whether each block has an alpha channel or not.
194        # This if statement is hit by COMPRESSED_RGB_S3TC_DXT1, which is a bit of a mess.
195        # TODO(oetuaho): Look into whether COMPRESSED_RGB_S3TC_DXT1 works right in general.
196        # Reference: https://www.opengl.org/registry/specs/EXT/texture_compression_s3tc.txt
197        return 'nullptr'
198
199    elif component_type == 'uint' and bits['R'] == 8:
200        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0x01>'
201    elif component_type == 'unorm' and bits['R'] == 8:
202        return 'Initialize4ComponentData<GLubyte, 0x00, 0x00, 0x00, 0xFF>'
203    elif component_type == 'unorm' and bits['R'] == 16:
204        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0xFFFF>'
205    elif component_type == 'int' and bits['R'] == 8:
206        return 'Initialize4ComponentData<GLbyte, 0x00, 0x00, 0x00, 0x01>'
207    elif component_type == 'snorm' and bits['R'] == 8:
208        return 'Initialize4ComponentData<GLbyte, 0x00, 0x00, 0x00, 0x7F>'
209    elif component_type == 'snorm' and bits['R'] == 16:
210        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0x7FFF>'
211    elif component_type == 'float' and bits['R'] == 16:
212        return 'Initialize4ComponentData<GLhalf, 0x0000, 0x0000, 0x0000, gl::Float16One>'
213    elif component_type == 'uint' and bits['R'] == 16:
214        return 'Initialize4ComponentData<GLushort, 0x0000, 0x0000, 0x0000, 0x0001>'
215    elif component_type == 'int' and bits['R'] == 16:
216        return 'Initialize4ComponentData<GLshort, 0x0000, 0x0000, 0x0000, 0x0001>'
217    elif component_type == 'float' and bits['R'] == 32:
218        return 'Initialize4ComponentData<GLfloat, 0x00000000, 0x00000000, 0x00000000, gl::Float32One>'
219    elif component_type == 'int' and bits['R'] == 32:
220        return 'Initialize4ComponentData<GLint, 0x00000000, 0x00000000, 0x00000000, 0x00000001>'
221    elif component_type == 'uint' and bits['R'] == 32:
222        return 'Initialize4ComponentData<GLuint, 0x00000000, 0x00000000, 0x00000000, 0x00000001>'
223    else:
224        raise ValueError(
225            'warning: internal format initializer could not be generated and may be needed for ' +
226            internal_format)
227
228
229def get_format_gl_type(format):
230    sign = ''
231    base_type = None
232    if 'FLOAT' in format:
233        bits = get_bits(format)
234        redbits = bits and bits.get('R')
235        base_type = 'float'
236        if redbits == 16:
237            base_type = 'half'
238    else:
239        bits = get_bits(format)
240        redbits = bits and bits.get('R')
241        if redbits == 8:
242            base_type = 'byte'
243        elif redbits == 16:
244            base_type = 'short'
245        elif redbits == 32:
246            base_type = 'int'
247
248        if 'UINT' in format or 'UNORM' in format or 'USCALED' in format:
249            sign = 'u'
250
251    if base_type is None:
252        return None
253
254    return 'GL' + sign + base_type
255
256
257def get_vertex_copy_function(src_format, dst_format):
258    if dst_format == "NONE":
259        return "nullptr"
260
261    src_num_channel = len(get_channel_tokens(src_format))
262    dst_num_channel = len(get_channel_tokens(dst_format))
263    if src_num_channel < 1 or src_num_channel > 4:
264        return "nullptr"
265
266    if src_format.endswith('_VERTEX'):
267        assert 'FLOAT' in dst_format, (
268            'get_vertex_copy_function: can only convert to float,' + ' not to ' + dst_format)
269        is_signed = 'true' if 'SINT' in src_format or 'SNORM' in src_format or 'SSCALED' in src_format else 'false'
270        is_normal = 'true' if 'NORM' in src_format else 'false'
271        if 'A2' in src_format:
272            return 'CopyW2XYZ10ToXYZWFloatVertexData<%s, %s, true>' % (is_signed, is_normal)
273        else:
274            return 'CopyXYZ10ToXYZWFloatVertexData<%s, %s, true>' % (is_signed, is_normal)
275
276    if 'FIXED' in src_format:
277        assert 'FLOAT' in dst_format, (
278            'get_vertex_copy_function: can only convert fixed to float,' + ' not to ' + dst_format)
279        return 'Copy32FixedTo32FVertexData<%d, %d>' % (src_num_channel, dst_num_channel)
280
281    src_gl_type = get_format_gl_type(src_format)
282    dst_gl_type = get_format_gl_type(dst_format)
283
284    if src_gl_type == None:
285        return "nullptr"
286
287    if src_gl_type == dst_gl_type:
288        default_alpha = '1'
289
290        if src_num_channel == dst_num_channel or dst_num_channel < 4:
291            default_alpha = '0'
292        elif 'A16_FLOAT' in dst_format:
293            default_alpha = 'gl::Float16One'
294        elif 'A32_FLOAT' in dst_format:
295            default_alpha = 'gl::Float32One'
296        elif 'NORM' in dst_format:
297            default_alpha = 'std::numeric_limits<%s>::max()' % (src_gl_type)
298
299        return 'CopyNativeVertexData<%s, %d, %d, %s>' % (src_gl_type, src_num_channel,
300                                                         dst_num_channel, default_alpha)
301
302    assert 'FLOAT' in dst_format, (
303        'get_vertex_copy_function: can only convert to float,' + ' not to ' + dst_format)
304    normalized = 'true' if 'NORM' in src_format else 'false'
305
306    dst_is_half = 'true' if dst_gl_type == 'GLhalf' else 'false'
307    return "CopyToFloatVertexData<%s, %d, %d, %s, %s>" % (src_gl_type, src_num_channel,
308                                                          dst_num_channel, normalized, dst_is_half)
309