表达式(Expressions)是描述值是如何计算的。
不同类型的值表达式在计算时间和表达能力之间提供了一种权衡, 计算越快,限制就越严格,而且使用值的地方越多,这种权衡导致每种类型的值声明具有不同的灵活性。
早期求值的表达式:
WGSL 有两类早期就被求值的表达式:
- const-expressions , at shader-creation time;
- overrride-expressions , at pipeline-creation time;
可以在着色器创建时计算的表达式称为常量表达式, 如果标识符被解析为以下形式,则为 const-expression:
- const-declarations, or
- const-functions, or
- type aliases, or
- structure names.
override 表达式在 管线创建时被计算:
-
const-functions, or
-
type aliases, or
-
structure names.
无法确定值的表达式:
fn fun() {
var extracted_values: array<i32,2>;
const v = vec2<i32>(0,1);
for (var i: i32 = 0; i < 2 ; i++) {
// A runtime-expression used to index a vector, but outside the
// indexing bounds of the vector, produces an indeterminate value
// of the vector component type.
let extract = v[i+5];
// Now 'extract' is any value of type i32.
// Save it for later.
extracted_values[i] = extract;
if extract == extract {
// This is always executed
}
if extract < 2 {
// This might be executed, but might not be executed.
// Even though the original vector components are 0 and 1,
// the extracted value might not be either of those values.
}
}
if extracted_value[0] == extracted_values[1] {
// This might be executed, but might not be executed.
}
}
fn float_fun(runtime_index: u32) {
const v = vec2<f32>(0,1); // A vector of floating point values
// As in the previous example, 'float_extract' is an indeterminate value.
// Since it is a floating point type, it may be a NaN.
let float_extract: f32 = v[runtime_index+5];
if float_extract == float_extract {
// This *might not* be executed, because:
// - 'float_extract' may be NaN, and
// - a NaN is never equal to any other floating point number,
// even another NaN.
}
}
字面量表达式
括号表达式
类型构造表达式
类型构造函数表达式显式地创建给定具体可构造类型的值。
使用类型别名的类型构造表达式代码示例:
alias my_vec3f = vec3<f32>;
alias my_vec4f = vec4<f32>;
// Computes vec3<f32>(0.0f, 1.0f, 0.0f)
const threeD_e2 = my_vec3f(0.0, 1.0, 0.0);
// Same as writing vec4<f32>(threeD_e2, 0.0)
// Computes vec4<f32>(0.0f, 1.0f, 0.0f, 0.0f)
const fourD_e2 = my_vec4f(threeD_e2, 0.0);
// Same as writing vec3<f32>()
// Computes vec3<f32>(0.0f, 0.0f, 0.0f)
const threeD_zero = my_vec3f();
// Use the fully-elaborated name for a 4-element vector of f32.
const fourD_ones_first = vec4<f32>(1.0f);
// Use vec4f, the predeclared alias to vec4<f32>.
const fourD_ones_second = vec4f(1.0f);
零初始化表达式:
bool() : bool
i32():32
u32():u32
f32():f32
f16(): f16
vec2<T>():vec2<T>
vec3<T>(): vec3<T>
vec4<T>(): vec4<T>
array<T, N>() : array<T, N>
struct Student {
grade: i32,
GPU: f32,
attendance: array<bool ,4>
}
var s:Student = Student();
也就是构造函数为空,默认会用零值初始化。