v
Зеркало из https://github.com/vlang/v
1// Copyright (c) 2024 Lars Pontoppidan. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4//
5// vshader aids in generating special shader code C headers via sokol-shdc's 'annotated GLSL' format to any
6// supported target formats that sokol_gfx supports internally.
7//
8// vshader bootstraps itself by downloading it's own dependencies to a system cache directory on first run.
9//
10// Please see https://github.com/floooh/sokol-tools/blob/master/docs/sokol-shdc.md#feature-overview
11// for a more in-depth overview of the specific tool in use.
12//
13// The shader language used is, as described on the overview page linked above, an 'annotated GLSL'
14// and 'modern GLSL' (v450) shader language format.
15import os
16import time
17import io.util
18import flag
19import net.http
20
21const shdc_full_hash = '0d91b038780614a867f2c8eecd7d935d76bcaae3'
22const tool_version = '0.0.4'
23const tool_description = "Compile shaders in sokol's annotated GLSL format to C headers for use with sokol based apps"
24const tool_name = os.file_name(os.executable())
25const cache_dir = os.join_path(os.cache_dir(), 'v', tool_name)
26const runtime_os = os.user_os()
27const supported_hosts = ['linux', 'macos', 'windows']
28const supported_slangs = [
29'glsl430', // default desktop OpenGL backend (SOKOL_GLCORE)
30'glsl410', // default macOS desktop OpenGL
31'glsl300es', // OpenGLES3 and WebGL2 (SOKOL_GLES3)
32'hlsl4', // Direct3D11 with HLSL4 (SOKOL_D3D11)
33'hlsl5', // Direct3D11 with HLSL5 (SOKOL_D3D11)
34'metal_macos', // Metal on macOS (SOKOL_METAL)
35'metal_ios', // Metal on iOS devices (SOKOL_METAL)
36'metal_sim', // Metal on iOS simulator (SOKOL_METAL)
37'wgsl', // WebGPU (SOKOL_WGPU)
38'reflection',
39]
40const default_slangs = [
41'glsl410',
42'glsl300es',
43// 'hlsl4', and hlsl5 can't be used at the same time
44'hlsl5',
45'metal_macos',
46'metal_ios',
47'metal_sim',
48'wgsl',
49]
50
51const shdc_version = shdc_full_hash[0..8]
52const shdc_urls = {
53'windows': 'https://github.com/floooh/sokol-tools-bin/raw/${shdc_full_hash}/bin/win32/sokol-shdc.exe'
54'macos': 'https://github.com/floooh/sokol-tools-bin/raw/${shdc_full_hash}/bin/osx/sokol-shdc'
55'linux': 'https://github.com/floooh/sokol-tools-bin/raw/${shdc_full_hash}/bin/linux/sokol-shdc'
56'osx_a64': 'https://github.com/floooh/sokol-tools-bin/raw/${shdc_full_hash}/bin/osx_arm64/sokol-shdc'
57}
58const shdc_version_file = os.join_path(cache_dir, 'sokol-shdc.version')
59const shdc_exe = os.join_path(cache_dir, 'sokol-shdc.exe')
60
61struct Options {
62show_help bool
63verbose bool
64force_update bool
65slangs []string
66}
67
68struct CompileOptions {
69verbose bool
70slangs []string
71invoke_path string
72}
73
74fn main() {
75if os.args.len == 1 {
76println('Usage: ${tool_name} PATH \n${tool_description}\n${tool_name} -h for more help...')
77exit(1)
78}
79mut fp := flag.new_flag_parser(os.args[1..])
80fp.application(tool_name)
81fp.version(tool_version)
82fp.description(tool_description)
83fp.arguments_description('PATH [PATH]...')
84fp.skip_executable()
85// Collect tool options
86opt := Options{
87show_help: fp.bool('help', `h`, false, 'Show this help text.')
88force_update: fp.bool('force-update', `u`, false, 'Force update of the sokol-shdc tool.')
89verbose: fp.bool('verbose', `v`, false, 'Be verbose about the tools progress.')
90slangs: fp.string_multi('slang', `l`, 'Shader dialects to generate code for. Default is all.\n Available dialects: ${supported_slangs}')
91}
92if opt.show_help {
93println(fp.usage())
94exit(0)
95}
96
97ensure_external_tools(opt) or { panic(err) }
98
99input_paths := fp.finalize() or { panic(err) }
100
101for path in input_paths {
102if os.exists(path) {
103compile_shaders(opt, path) or { panic(err) }
104}
105}
106}
107
108// shader_program_name returns the name of the program from `shader_file`.
109// shader_program_name returns a blank string if no @program entry could be found.
110fn shader_program_name(shader_file string) string {
111shader_program := os.read_lines(shader_file) or { return '' }
112for line in shader_program {
113if line.contains('@program ') {
114return line.all_after('@program ').all_before(' ')
115}
116}
117return ''
118}
119
120// validate_shader_file returns an error if `shader_file` isn't valid.
121fn validate_shader_file(shader_file string) ! {
122shader_program := os.read_lines(shader_file) or {
123return error('shader program at "${shader_file}" could not be opened for reading')
124}
125mut has_program_directive := false
126for line in shader_program {
127if line.contains('@program ') {
128has_program_directive = true
129break
130}
131}
132if !has_program_directive {
133return error('shader program at "${shader_file}" is missing a "@program" directive.')
134}
135}
136
137// compile_shaders compiles all `*.glsl` files found in `input_path`
138// to their C header file representatives.
139fn compile_shaders(opt Options, input_path string) ! {
140mut path := os.real_path(input_path)
141path = path.trim_right('/')
142if os.is_file(path) {
143path = os.dir(path)
144}
145
146mut shader_files := []string{}
147collect(path, mut shader_files)
148
149if shader_files.len == 0 {
150if opt.verbose {
151eprintln('${tool_name} found no shader files to compile for "${path}"')
152}
153return
154}
155
156for shader_file in shader_files {
157// It could be the user has WIP shader files lying around not used,
158// so we just report that there's something wrong
159validate_shader_file(shader_file) or {
160eprintln(err)
161continue
162}
163co := CompileOptions{
164verbose: opt.verbose
165slangs: opt.slangs
166invoke_path: path
167}
168// Currently sokol-shdc allows for multiple --input flags
169// - but it's only the last entry that's actually compiled/used
170// Given this fact - we can only compile one '.glsl' file to one C '.h' header
171compile_shader(co, shader_file)!
172}
173}
174
175// compile_shader compiles `shader_file` to a C header file.
176fn compile_shader(opt CompileOptions, shader_file string) ! {
177path := opt.invoke_path
178// The output convention, for now, is to use the name of the .glsl file
179mut out_file := os.file_name(shader_file).all_before_last('.') + '.h'
180out_file = os.join_path(path, out_file)
181
182mut slangs := opt.slangs.clone()
183if opt.slangs.len == 0 {
184slangs = default_slangs.clone()
185}
186
187header_name := os.file_name(out_file)
188if opt.verbose {
189eprintln('${tool_name} generating shader code for ${slangs} in header "${header_name}" in "${path}" from ${shader_file}')
190}
191
192cmd :=
193'${os.quoted_path(shdc_exe)} --input ${os.quoted_path(shader_file)} --output ${os.quoted_path(out_file)} --slang ' +
194os.quoted_path(slangs.join(':'))
195if opt.verbose {
196eprintln('${tool_name} executing:\n${cmd}')
197}
198res := os.execute(cmd)
199if res.exit_code != 0 {
200eprintln('${tool_name} failed generating shader includes:\n ${res.output}\n ${cmd}')
201exit(1)
202}
203if opt.verbose {
204program_name := shader_program_name(shader_file)
205eprintln('${tool_name} usage example in V:\n\nimport sokol.gfx\n\n#include "${header_name}"\n\nfn C.${program_name}_shader_desc(gfx.Backend) &gfx.ShaderDesc\n')
206}
207}
208
209// collect recursively collects `.glsl` file entries from `path` in `list`.
210fn collect(path string, mut list []string) {
211if !os.is_dir(path) {
212return
213}
214mut files := os.ls(path) or { return }
215for file in files {
216p := os.join_path(path, file)
217if os.is_dir(p) && !os.is_link(p) {
218collect(p, mut list)
219} else if os.exists(p) {
220if os.file_ext(p) == '.glsl' {
221list << os.real_path(p)
222}
223}
224}
225return
226}
227
228// ensure_external_tools returns nothing if the external
229// tools can be setup or is already in place.
230fn ensure_external_tools(opt Options) ! {
231if !os.exists(cache_dir) {
232os.mkdir_all(cache_dir)!
233}
234if opt.force_update {
235download_shdc(opt)!
236return
237}
238
239is_shdc_available := os.is_file(shdc_exe)
240is_shdc_executable := os.is_executable(shdc_exe)
241if opt.verbose {
242eprintln('reading version from ${shdc_version_file} ...')
243version := os.read_file(shdc_version_file) or { 'unknown' }
244eprintln('${tool_name} using sokol-shdc version ${version} at "${shdc_exe}"')
245eprintln('executable: ${is_shdc_executable}')
246eprintln(' available: ${is_shdc_available}')
247if is_shdc_available {
248eprintln(' file path: ${shdc_exe}')
249eprintln(' file size: ${os.file_size(shdc_exe)}')
250eprintln(' file time: ${time.unix_microsecond(os.file_last_mod_unix(shdc_exe),
2510)}')
252}
253}
254if is_shdc_available && is_shdc_executable {
255return
256}
257
258download_shdc(opt)!
259}
260
261// download_shdc downloads the `sokol-shdc` tool to an OS specific cache directory.
262fn download_shdc(opt Options) ! {
263// We want to use the same, runtime, OS type as this tool is invoked on.
264mut download_url := shdc_urls[runtime_os] or { '' }
265$if arm64 && macos {
266download_url = shdc_urls['osx_a64']
267}
268if download_url == '' {
269return error('${tool_name} failed to download an external dependency "sokol-shdc" for ${runtime_os}.\nThe supported host platforms for shader compilation is ${supported_hosts}')
270}
271if opt.verbose {
272eprintln('> reading version from ${shdc_version_file} ...')
273}
274update_to_shdc_version := os.read_file(shdc_version_file) or { shdc_version }
275if opt.verbose {
276eprintln('> update_to_shdc_version: ${update_to_shdc_version} | shdc_version: ${shdc_version}')
277}
278if opt.verbose {
279if shdc_version != update_to_shdc_version && os.exists(shdc_exe) {
280eprintln('${tool_name} updating sokol-shdc to version ${shdc_version} ...')
281} else {
282eprintln('${tool_name} installing sokol-shdc version ${update_to_shdc_version} ...')
283}
284}
285if os.exists(shdc_exe) {
286os.rm(shdc_exe)!
287}
288
289mut dtmp_file, dtmp_path := util.temp_file(util.TempFileOptions{ path: os.dir(shdc_exe) })!
290dtmp_file.close()
291if opt.verbose {
292eprintln('${tool_name} downloading sokol-shdc from ${download_url}')
293}
294http.download_file(download_url, dtmp_path) or {
295os.rm(dtmp_path)!
296return error('${tool_name} failed to download sokol-shdc needed for shader compiling: ${err}')
297}
298// Make it executable
299os.chmod(dtmp_path, 0o775)!
300// Move downloaded file in place
301os.mv(dtmp_path, shdc_exe)!
302// Update internal version file
303os.write_file(shdc_version_file, shdc_version)!
304}
305