yum-slop/TaSTT

Free self-hosted STT for VRChat.

git clone https://git.yummers.dev/yum-slop/TaSTT

yumFix user-reported bug in generate_shader.py5f33e4e

v0.20.0
7.0 KiB161 linesraw
1#!/usr/bin/env python3
2
3import argparse
4import generate_utils
5import os
6import sys
7
8# A single parameter looks like this:
9#   _Letter_Row00_Col00_Byte0("_Letter_Row00_Col00_Byte0", float) = 0
10def generateUnityParams(nbytes: int, nrows: int, ncols: int, prefix: str = "") -> str:
11    lines = []
12    lines.append(prefix + "// BEGIN GENERATED CODE BLOCK")
13    for byte in range(0, nbytes):
14        for row in range(0, nrows):
15            for col in range(0, ncols):
16                param_name = generate_utils.getShaderParamByRowColByte(row, col, byte)
17                line = prefix + """{}("{}", float) = 0""".format(param_name, param_name)
18                lines.append(line)
19    lines.append(prefix + "// END GENERATED CODE BLOCK")
20    return '\n'.join(lines)
21
22# A single parameter looks like this:
23#   float _Letter_Row00_Col00_Byte0;
24def generateCgParams(nbytes: int, nrows: int, ncols: int, prefix: str = "") -> str:
25    lines = []
26    lines.append(prefix + "// BEGIN GENERATED CODE BLOCK")
27    for byte in range(0, nbytes):
28        for row in range(0, nrows):
29            for col in range(0, ncols):
30                param_name = generate_utils.getShaderParamByRowColByte(row, col, byte)
31                line = prefix + """float {};""".format(param_name)
32                lines.append(line)
33    lines.append(prefix + "// END GENERATED CODE BLOCK")
34    return '\n'.join(lines)
35
36# Define 3 constants:
37#   uniform int BYTES_PER_CHAR = $nbytes;
38#   uniform int NROWS = $nrows;
39#   uniform int NCOLS = $ncols;
40def generateCgConstants(nbytes: int, board_nrows: int, board_ncols: int,
41        texture_nrows: int, texture_ncols: int, prefix: str = "") -> str:
42    lines = []
43    lines.append(prefix + "// BEGIN GENERATED CODE BLOCK")
44    lines.append(prefix + "#define BYTES_PER_CHAR {}".format(nbytes))
45    lines.append(prefix + "#define BOARD_NROWS {}".format(board_nrows))
46    lines.append(prefix + "#define BOARD_NCOLS {}".format(board_ncols))
47    lines.append(prefix + "#define TEXTURE_NROWS {}".format(texture_nrows))
48    lines.append(prefix + "#define TEXTURE_NCOLS {}".format(texture_ncols))
49    lines.append(prefix + "// END GENERATED CODE BLOCK")
50    return '\n'.join(lines)
51
52# This is the basic idea of what we're generating:
53#      // Get the value of the parameter for the cell we're in.
54#      uint GetLetterParameter(float2 uv)
55#      {
56#        float CHAR_COL = floor(uv.x * Cols);
57#        float CHAR_ROW = floor(uv.y * Rows);
58#        uint res = 0;
59#
60#          [forcecase] switch(CHAR_ROW) {
61#            case n:
62#            case n-1:
63#            ...
64#
65#              [forcecase] switch (CHAR_COL) {
66#              case 0:
67#              case 1:
68#              ...
69#
70#                res |= ((uint) _Letter_Row00_Col00_Byte0) << (0 * 8);
71#                res |= ((uint) _Letter_Row00_Col00_Byte1) << (1 * 8);
72#                continue;
73#              }
74#        }
75#        return res;
76#      }
77# In English, this provides an accessor to the many (possibly thousands)
78# float parameters which hold the text on the board.
79def generateLetterAccessor(nbytes: int, nrows: int, ncols: int, prefix: str = "") -> str:
80    lines = []
81    lines.append(prefix + "// BEGIN GENERATED CODE BLOCK")
82    lines.append(prefix + "[forcecase] switch (CHAR_ROW) {")
83    for row in range(0, nrows):
84        lines.append(prefix + "  case {}:".format(nrows - (row + 1)))
85        lines.append(prefix + "    [forcecase] switch (CHAR_COL) {")
86        for col in range(0, ncols):
87            lines.append(prefix + "      case {}:".format(col))
88            for byte in range(0, nbytes):
89                param_name = generate_utils.getShaderParamByRowColByte(row, col, byte)
90                lines.append(prefix + "        res |= ((uint) {}) << ({} * 8);".format(param_name, byte))
91            lines.append(prefix + "        return res;")
92        lines.append(prefix + "      default:")
93        lines.append(prefix + "        return 0;")
94        lines.append(prefix + "    }")
95    lines.append(prefix + "}")
96    lines.append(prefix + "// END GENERATED CODE BLOCK")
97    return '\n'.join(lines)
98
99# Replace any line containing `macro` with `replacement`.
100def applyLineMacro(old_path: str, new_path: str, macro: str, replacement: str) -> bool:
101    new_lines = []
102    times_applied = 0
103    with open(old_path, 'r', encoding="utf-8") as f:
104        for line in f:
105            if line[-1] == '\n':
106                line = line[0:len(line)-1]
107            if macro in line:
108                new_lines.append(replacement)
109                times_applied += 1
110            else:
111                new_lines.append(line)
112    with open(new_path, 'w', encoding="utf-8") as f:
113        f.write('\n'.join(new_lines))
114    return times_applied
115
116if __name__ == "__main__":
117    print("args: {}".format(" ".join(sys.argv)))
118
119    parser = argparse.ArgumentParser()
120    parser.add_argument("--bytes_per_char", type=str, help="The number of bytes to use to represent each character")
121    parser.add_argument("--board_rows", type=str, help="The number of rows on the board")
122    parser.add_argument("--board_cols", type=str, help="The number of columns on the board")
123    parser.add_argument("--texture_rows", type=str, help="The number of rows on the font textures")
124    parser.add_argument("--texture_cols", type=str, help="The number of columns on the font textures")
125    parser.add_argument("--shader_template", type=str, help="The path to the shader template")
126    parser.add_argument("--shader_path", type=str, help="The path where the generated shader will be written")
127    args = parser.parse_args()
128
129    if not args.bytes_per_char or not args.board_rows or not args.board_cols \
130            or not args.texture_rows or not args.texture_cols \
131            or not args.shader_template or not args.shader_path:
132        print(("--bytes_per_char, --board_rows, --board_cols, --texture_rows, "
133                "--texture_cols, --shader_template, --shader_path required"), file=sys.stderr)
134        sys.exit(1)
135
136    nbytes = int(args.bytes_per_char)
137    board_nrows = int(args.board_rows)
138    board_ncols = int(args.board_cols)
139    texture_nrows = int(args.texture_rows)
140    texture_ncols = int(args.texture_cols)
141
142    replacement = generateUnityParams(nbytes, board_nrows, board_ncols, prefix = "")
143    #print(replacement)
144    macro = "// %TEMPLATE__UNITY_ROW_COL_PARAMS%"
145    applyLineMacro(args.shader_template, args.shader_path, macro, replacement)
146
147    replacement = generateCgParams(nbytes, board_nrows, board_ncols, prefix = "  ")
148    #print(replacement)
149    macro = "// %TEMPLATE__CG_ROW_COL_PARAMS%"
150    applyLineMacro(args.shader_path, args.shader_path, macro, replacement)
151
152    replacement = generateCgConstants(nbytes, board_nrows, board_ncols,
153            texture_nrows, texture_ncols, prefix = "  ")
154    #print(replacement)
155    macro = "// %TEMPLATE__CG_ROW_COL_CONSTANTS%"
156    applyLineMacro(args.shader_path, args.shader_path, macro, replacement)
157
158    replacement = generateLetterAccessor(nbytes, board_nrows, board_ncols, prefix = "      ")
159    #print(replacement)
160    macro = "// %TEMPLATE__CG_LETTER_ACCESSOR%"
161    applyLineMacro(args.shader_path, args.shader_path, macro, replacement)