WGSL 還在積極討論中,雖然各位大佬不是很滿意這個新生兒。
不過,社區已經有了基礎的實驗性工具(VSCode 插件),並支持了較新的語法。
① WGSL 插件
這個插件支持對文件擴展名爲 .wgsl 的源代碼文件進行高亮顯示。
② WGSL Literal 插件
這個插件允許你在 JavaScript / TypeScript 的模板字符串中進行 wgsl 代碼高亮,需要加上模板字符串前置塊註釋:
const code = /* wgsl */`
struct FragmentInput {
@location(0) Color: vec3<f32>;
};
@stage(fragment)
fn main(input: FragmentInput) -> @location(0) vec4<f32> {
return vec4<f32>(input.Color, 1.0);
}
`;
遺憾的是,截至 2022年3月25日,這兩個插件並沒有代碼格式化功能(幾乎沒有),也沒有代碼智能提示功能。
③ WGSL Preprocessor
這是一個 JavaScript / TypeScript 模板字符串 wgsl 預處理函數包,模板字符串除了可插值外,還可以使用前置函數進行預處理。
這個函數包目前只是一個 esm 模塊文件,以後不排除會變成更大的 npm 包,由 toji(Brandon Jones)維護。
github.com/toji/wgsl-preprocessorgithub.com
這個使得 wgsl 擁有了 glsl 類似的宏定義等語法:
目前支持:
#if
#elif
#else
#endif
簡單用法:
import { wgsl } from './wgsl-preprocessor.js';
function getDebugShader(sRGB = false) {
return wgsl`
@stage(fragment)
fn main() -> @location(0) vec4<f32> {
let color = vec4(1.0, 0.0, 0.0, 1.0);
#if ${sRGB}
let rgb = pow(color.rgb, vec3(1.0 / 2.2));
return vec4(rgb, color.a);
#else
return color;
#endif
}`;
}
`
爲什麼沒有 #define 宏?
因爲模板字符串的插值功能已經可以當 #define 宏使用了,你甚至都不需要使用這個字符串預處理函數。
const ambientFactor = 1.0;
const sampleCount = 2;
const source = `
let ambientFactor = f32(${ambientFactor});
for (var i = 0u; i < ${sampleCount}u; i = i + 1u) {
// Etc...
}
`;