OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/python | |
2 # Copyright 2016 The Chromium 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 """Helper script to inline files as const char[] into a C header file. | |
7 | |
8 Example: | |
9 | |
10 Input file in_a.vert: | |
11 1" | |
12 2 | |
13 3\ | |
14 | |
15 Input file in_b.frag: | |
16 4 | |
17 5 | |
18 6 | |
19 | |
20 shader_to_header.py "output.h" "in_a.vert" "in_b.frag" will generate this: | |
21 | |
22 #ifndef OUTPUT_H_BSGN3bbEMBDD0ucC | |
23 #define OUTPUT_H_BSGN3bbEMBDD0ucC | |
24 | |
25 const char kInAVert[] = "1\"\n2\n3\\\n"; | |
26 | |
27 const char kInBFrag[] = "4\n5\n6\n"; | |
28 | |
29 #endif // OUTPUT_H_BSGN3bbEMBDD0ucC | |
30 | |
31 | |
32 """ | |
33 | |
34 import os.path | |
35 import random | |
36 import string | |
37 import sys | |
38 | |
39 RANDOM_STRING_LENGTH = 16 | |
40 STRING_CHARACTERS = (string.ascii_uppercase + | |
41 string.ascii_lowercase + | |
42 string.digits) | |
43 | |
44 def random_str(): | |
45 return ''.join(random.choice(STRING_CHARACTERS) | |
Lambros
2016/06/06 21:17:46
drive-by:
How much do we trust Python's 'random'
| |
46 for _ in range(RANDOM_STRING_LENGTH)) | |
47 | |
48 | |
49 def escape_text(line): | |
50 # encode('string-escape') doesn't escape double quote so you need to manually | |
51 # escape it. | |
52 return line.encode('string-escape').replace('"', '\\"') | |
53 | |
54 | |
55 def main(): | |
56 if len(sys.argv) < 3: | |
57 print 'Usage: shader_to_header.py <output-file> <input-files...>' | |
58 return 1 | |
59 | |
60 output_path = sys.argv[1] | |
61 include_guard = (os.path.basename(output_path).upper().replace('.', '_') + | |
62 '_' + random_str()) | |
63 | |
64 with open(output_path, 'w') as output_file: | |
65 output_file.write('#ifndef ' + include_guard + '\n' + | |
66 '#define ' + include_guard + '\n\n') | |
67 | |
68 existing_names = set() | |
69 argc = len(sys.argv) | |
70 for i in xrange(2, argc): | |
71 input_path = sys.argv[i] | |
72 | |
73 with open(input_path, 'r') as input_file: | |
74 # hello_world.vert -> kHelloWorldVert | |
75 const_name = ('k' + os.path.basename(input_path).title() | |
76 .replace('_', '').replace('.', '')) | |
77 if const_name in existing_names: | |
78 print >> sys.stderr, ('Error: Constant name ' + const_name + | |
79 ' is already used by a previous file. Files with the same' + | |
80 ' name can\'t be inlined into the same header.') | |
81 return 1 | |
82 | |
83 existing_names.add(const_name) | |
84 text = input_file.read() | |
85 | |
86 inlined = ('const char ' + const_name + '[] = "' + escape_text(text) + | |
87 '";\n\n'); | |
88 output_file.write(inlined) | |
89 | |
90 output_file.write('#endif // ' + include_guard + '\n') | |
91 | |
92 return 0 | |
93 | |
94 | |
95 if __name__ == '__main__': | |
96 sys.exit(main()) | |
OLD | NEW |