シェーディング言語

はじめに

Godotは、GLSL ES 3.0と同様のシェーディング言語を使用します。ほとんどのデータ型と関数がサポートされており、残りのいくつかのデータ型は今後追加される可能性があります。

If you are already familiar with GLSL, the Godot Shader Migration Guide is a resource that will help you transition from regular GLSL to Godot's shading language.

データ型

ほとんどのGLSL ES 3.0データ型がサポートされています:

タイプ(型)

説明

void

Voidデータ型。何も返さない関数にのみ有用です。

bool

Boolデータ型には、true または false のみを含めることができます。

bvec2

Bool値の2要素ベクトル。

bvec3

Bool値の3要素ベクトル。

bvec4

Bool値の4要素ベクトル。

int

符号付きスカラー整数。

ivec2

符号付き整数の2要素ベクトル。

ivec3

符号付き整数の3要素ベクトル。

ivec4

符号付き整数の4要素ベクトル。

uint

符号なしスカラー整数。負の数を含めることはできません。

uvec2

符号なし整数の2要素ベクトル。

uvec3

符号なし整数の3要素ベクトル。

uvec4

符号なし整数の4要素ベクトル。

float

Floating-point scalar.

vec2

Two-component vector of floating-point values.

vec3

Three-component vector of floating-point values.

vec4

Four-component vector of floating-point values.

mat2

列優先順の2x2マトリックス。

mat3

列優先順の3x3マトリックス。

mat4

列優先順の4x4マトリックス。

sampler2D

floatとして読み取られる2Dテクスチャをバインドするためのサンプラータイプ。

isampler2D

符号付き整数として読み取られる2Dテクスチャをバインドするためのサンプラータイプ。

usampler2D

符号なし整数として読み取られる2Dテクスチャをバインドするためのサンプラータイプ。

sampler2DArray

floatとして読み取られる2Dテクスチャ配列をバインドするためのサンプラータイプ。

isampler2DArray

符号付き整数として読み取られる2Dテクスチャ配列をバインドするためのサンプラータイプ。

usampler2DArray

符号なし整数として読み取られる2Dテクスチャ配列をバインドするためのサンプラータイプ。

sampler3D

floatとして読み取られる3Dテクスチャをバインドするためのサンプラータイプ。

isampler3D

符号付き整数として読み取られる3Dテクスチャをバインドするためのサンプラータイプ。

usampler3D

符号なし整数として読み取られる3Dテクスチャをバインドするためのサンプラータイプ。

samplerCube

Cubemapsをバインドするためのサンプラータイプ。floatとして読み込まれます。

キャスト

GLSL ES 3.0と同様に、同じサイズで異なるタイプのスカラーとベクトル間の暗黙的なキャストは許可されていません。異なるサイズの型のキャストも許可されていません。変換は、コンストラクターを介して明示的に実行する必要があります。

例:

float a = 2; // invalid
float a = 2.0; // valid
float a = float(2); // valid

デフォルトの整数定数は符号付きなので、符号なしに変換するには常にキャストが必要です:

int a = 2; // valid
uint a = 2; // invalid
uint a = uint(2); // valid

メンバー

ベクタータイプの個々のスカラーメンバーには、"x"、"y"、"z"、"w" メンバーを介してアクセスします。あるいは、"r"、"g"、"b" および "a" を使用しても機能し、同等です。ニーズに最適なものを使用してください。

For matrices, use the m[column][row] indexing syntax to access each scalar, or m[idx] to access a vector by row index. For example, for accessing the y position of an object in a mat4 you use m[3][1].

構築

ベクトル型の構築は常に代入する必要があります:

// The required amount of scalars
vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
// Complementary vectors and/or scalars
vec4 a = vec4(vec2(0.0, 1.0), vec2(2.0, 3.0));
vec4 a = vec4(vec3(0.0, 1.0, 2.0), 3.0);
// A single scalar for the whole vector
vec4 a = vec4(0.0);

行列タイプの構築には、行列と同じ次元のベクトルが必要です。matx(float) 構文を使用して対角行列を構築することもできます。したがって、mat4(1.0) は単位行列です。

mat2 m2 = mat2(vec2(1.0, 0.0), vec2(0.0, 1.0));
mat3 m3 = mat3(vec3(1.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0), vec3(0.0, 0.0, 1.0));
mat4 identity = mat4(1.0);

行列は、別の次元の行列から構築することもできます。次の2つのルールがあります。小さいマトリックスから大きいマトリックスを作成する場合、追加の行と列は単位マトリックスの値に設定されます。小さいマトリックスが大きいマトリックスから構築される場合、大きいマトリックスの左上のサブマトリックスが使用されます。

mat3 basis = mat3(WORLD_MATRIX);
mat4 m4 = mat4(basis);
mat2 m2 = mat2(m4);

Swizzling

結果が別のベクトル型(またはスカラー)である限り、任意の順序で要素の任意の組み合わせを取得することが可能です。これは説明されるよりも簡単に示されます:

vec4 a = vec4(0.0, 1.0, 2.0, 3.0);
vec3 b = a.rgb; // Creates a vec3 with vec4 components.
vec3 b = a.ggg; // Also valid; creates a vec3 and fills it with a single vec4 component.
vec3 b = a.bgr; // "b" will be vec3(2.0, 1.0, 0.0).
vec3 b = a.xyz; // Also rgba, xyzw are equivalent.
vec3 b = a.stp; // And stpq (for texture coordinates).
float c = b.w; // Invalid, because "w" is not present in vec3 b.
vec3 c = b.xrt; // Invalid, mixing different styles is forbidden.
b.rrr = a.rgb; // Invalid, assignment with duplication.
b.bgr = a.rgb; // Valid assignment. "b"'s "blue" component will be "a"'s "red" and vice versa.

精度

データ型に精度修飾子を追加することができます。それらをuniform、変数、引数、およびvaryingに使用します。

lowp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // low precision, usually 8 bits per component mapped to 0-1
mediump vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // medium precision, usually 16 bits or half float
highp vec4 a = vec4(0.0, 1.0, 2.0, 3.0); // high precision, uses full float or integer range (default)

一部の操作に低い精度を使用すると、関係する計算が高速化されます(精度は低下します)。これは、頂点プロセッサ関数ではほとんど必要ありません(ほとんどの場合、完全な精度が必要です)が、フラグメントプロセッサではしばしば有用です。

Some architectures (mainly mobile) can benefit significantly from this, but there are downsides such as the additional overhead of conversion between precisions. Refer to the documentation of the target architecture for further information. In many cases, mobile drivers cause inconsistent or unexpected behavior and it is best to avoid specifying precision unless necessary.

配列

配列は、類似したタイプの複数の変数のコンテナです。注: Godot 3.2では、ローカル配列と可変配列のみが実装されています。

ローカル配列

Local arrays are declared in functions. They can use all of the allowed datatypes, except samplers. The array declaration follows a C-style syntax: [const] + [precision] + typename + identifier + [array size].

void fragment() {
    float arr[3];
}

これらは、最初のように初期化することができます:

float float_arr[3] = float[3] (1.0, 0.5, 0.0); // first constructor

int int_arr[3] = int[] (2, 1, 0); // second constructor

vec2 vec2_arr[3] = { vec2(1.0, 1.0), vec2(0.5, 0.5), vec2(0.0, 0.0) }; // third constructor

bool bool_arr[] = { true, true, false }; // fourth constructor - size is defined automatically from the element count

1つの式で複数の配列(サイズが異なる場合でも)を宣言できます:

float a[3] = float[3] (1.0, 0.5, 0.0),
b[2] = { 1.0, 0.5 },
c[] = { 0.7 },
d = 0.0,
e[5];

配列要素にアクセスするには、インデックス構文を使用します:

float arr[3];

arr[0] = 1.0; // setter

COLOR.r = arr[0]; // getter

配列には組み込み関数 .length() もあります(組み込みの length() 関数と混同しないでください)。パラメーターを受け入れず、配列のサイズを返します。

float arr[] = { 0.0, 1.0, 0.5, -1.0 };
for (int i = 0; i < arr.length(); i++) {
    // ...
}

注釈

If you use an index below 0 or greater than array size - the shader will crash and break rendering. To prevent this, use length(), if, or clamp() functions to ensure the index is between 0 and the array's length. Always carefully test and check your code. If you pass a constant expression or a simple number, the editor will check its bounds to prevent this crash.

定数

変数宣言の前に const キーワードを使用して、その変数を変更できないようにします。サンプラーを除くすべての基本型は、定数として宣言できます。定数値へのアクセスと使用は、ユニフォームの使用よりもわずかに高速です。定数は、宣言時に初期化する必要があります。

const vec2 a = vec2(0.0, 1.0);
vec2 b;

a = b; // invalid
b = a; // valid

定数は変更できず、さらにヒントを持つことはできませんが、複数の(同じ型の場合)を単一の式で宣言できます。例:

const vec2 V1 = vec2(1, 1), V2 = vec2(2, 2);

変数と同様に、配列は const で宣言することもできます。

const float arr[] = { 1.0, 0.5, 0.0 };

arr[0] = 1.0; // invalid

COLOR.r = arr[0]; // valid

定数は、グローバル(関数の外部)またはローカル(関数の内部)の両方で宣言できます。グローバル定数は、変更する必要のないシェーダー全体の値にアクセスする場合に役立ちます。ユニフォームと同様に、グローバル定数はすべてのシェーダーステージ間で共有されますが、シェーダーの外部からはアクセスできません。

shader_type spatial;

const float PI = 3.14159265358979323846;

オペレーター

Godotシェーディング言語は、GLSL ES 3.0と同じ一連の演算子をサポートしています。以下に優先順位のリストを示します:

優先順位

クラス

演算子

1 (最高)

カッコ内のグループ化

()

2

単項

+、-、!、~

3

乗除算

/、*、%

4

加減算

+、-

5

ビット単位のシフト

<<、>>

6

大小比較

<、>、<=、>=

7

一致、不一致

==、!=

8

bit-wise AND

&

9

bit-wise exclusive OR

^

10

bit-wise inclusive OR

|

11

logical AND

&&

12 (最低)

logical inclusive OR

||

構文制御

Godotシェーディング言語は、最も一般的なタイプの構文制御をサポートしています:

// if and else
if (cond) {

} else {

}

// switch
switch(i) { // signed integer expression
    case -1:
        break;
    case 0:
        return; // break or return
    case 1: // pass-through
    case 2:
        break;
    //...
    default: // optional
        break;
}

// for loops
for (int i = 0; i < 10; i++) {

}

// while
while (true) {

}

// do while
do {

} while(true);

最新のGPUでは、無限ループが存在し、アプリケーション(エディタを含む)がフリーズする可能性があることに注意してください。 Godotはこれからあなたを守ることはできないので、この間違いをしないように注意してください!

警告

When exporting a GLES2 project to HTML5, WebGL 1.0 will be used. WebGL 1.0 doesn't support dynamic loops, so shaders using those won't work there.

廃棄

フラグメントおよびライト関数では、discard キーワードを使用できます。使用すると、フラグメントは破棄され、何も書き込まれません。

関数

Godotシェーダーで関数を定義することが可能です。次の構文を使用します:

ret_type func_name(args) {
    return ret_type; // if returning a value
}

// a more specific example:

int sum2(int a, int b) {
    return a + b;
}

呼び出し元の関数から見て上記(エディタの上方)で定義された関数のみを使用できます。

関数の引数には特別な修飾子を含めることができます:

  • in: 引数が読み取り専用であることを意味します(デフォルト)。

  • out: 引数が書き込み専用であることを意味します。

  • inout: 引数が参照を介して完全に渡されることを意味します。

以下はその例です:

void sum2(int a, int b, inout int result) {
    result = a + b;
}

Varying(可変)

To send data from the vertex to the fragment (or light) processor function, varyings are used. They are set for every primitive vertex in the vertex processor, and the value is interpolated for every pixel in the fragment processor.

shader_type spatial;

varying vec3 some_color;

void vertex() {
    some_color = NORMAL; // Make the normal the color.
}

void fragment() {
    ALBEDO = some_color;
}

void light() {
    DIFFUSE_LIGHT = some_color * 100; // optionally
}

Varyingは配列にも指定できます:

shader_type spatial;

varying float var_arr[3];

void vertex() {
    var_arr[0] = 1.0;
    var_arr[1] = 0.0;
}

void fragment() {
    ALBEDO = vec3(var_arr[0], var_arr[1], var_arr[2]); // red color
}

It's also possible to send data from fragment to light processors using varying keyword. To do so you can assign it in the fragment and later use it in the light function.

shader_type spatial;

varying vec3 some_light;

void fragment() {
    some_light = ALBEDO * 100.0; // Make a shining light.
}

void light() {
    DIFFUSE_LIGHT = some_light;
}

Note that varying may not be assigned in custom functions or a light processor function like:

shader_type spatial;

varying float test;

void foo() {
    test = 0.0; // Error.
}

void vertex() {
    test = 0.0;
}

void light() {
    test = 0.0; // Error too.
}

This limitation was introduced to prevent incorrect usage before initialization.

補間修飾子

特定の値は、シェーディングパイプライン中に補間されます。補間修飾子 を使用して、これらの補間の実行方法を変更できます。

shader_type spatial;

varying flat vec3 our_color;

void vertex() {
    our_color = COLOR.rgb;
}

void fragment() {
    ALBEDO = our_color;
}

次の2つの補間修飾子があります:

修飾子

説明

flat

値は補間されません。

smooth

値は、パースペクティブに応じた方法で補間されます。これがデフォルトです。

Uniform(ユニフォーム)

シェーダーに値を渡すことは可能です。これらはシェーダー全体に対してグローバルであり、uniform と呼ばれます。シェーダーが後でマテリアルに割り当てられると、uniformはその中の編集可能なパラメーターとして表示されます。シェーダー内からuniformを書くことはできません。

shader_type spatial;

uniform float some_value;

マテリアルのエディタでuniformを設定できます。または、GDScriptを使用して設定できます:

material.set_shader_param("some_value", some_value)

注釈

set_shader_param の最初の引数はシェーダーのuniformの名前です。シェーダーのuniformの名前と完全に一致する必要があります。一致しない場合、認識されません。

Any GLSL type except for void can be a uniform. Additionally, Godot provides optional shader hints to make the compiler understand for what the uniform is used, and how the editor should allow users to modify it.

shader_type spatial;

uniform vec4 color : hint_color;
uniform float amount : hint_range(0, 1);
uniform vec4 other_color : hint_color = vec4(1.0);

It's important to understand that textures that are supplied as color require hints for proper sRGB->linear conversion (i.e. hint_albedo), as Godot's 3D engine renders in linear color space.

以下のヒントの完全なリスト:

タイプ(型)

ヒント

説明

vec4

hint_color

Used as color.

int、float

hint_range(min, max[, step])

Restricted to values in a range (with min/max/step).

sampler2D

hint_albedo

Used as albedo color, default white.

sampler2D

hint_black_albedo

Used as albedo color, default black.

sampler2D

hint_normal

Used as normalmap.

sampler2D

hint_white

値として、デフォルトは白です。

sampler2D

hint_black

値として、デフォルトは黒です。

sampler2D

hint_aniso

フローマップとして、デフォルトは右です。

GDScriptはGLSLとは異なる変数タイプを使用するため、GDScriptからシェーダーに変数を渡すと、Godotはタイプを自動的に変換します。以下は、対応するタイプの表です:

GDScript型

GLSL型

bool

bool

int

int

float

float

Vector2

vec2

Vector3

vec3

Color

vec4

Transform

mat4

Transform2D

mat4

注釈

Be careful when setting shader uniforms from GDScript, no error will be thrown if the type does not match. Your shader will just exhibit undefined behavior.

Uniformにはデフォルト値を割り当てることもできます:

shader_type spatial;

uniform vec4 some_vector = vec4(0.0);
uniform vec4 some_color : hint_color = vec4(1.0);

Built-in variables

A large number of built-in variables are available, like UV, COLOR and VERTEX. What variables are available depends on the type of shader (spatial, canvas_item or particle) and the function used (vertex, fragment or light). For a list of the build-in variables that are available, please see the corresponding pages:

組み込み関数

GLSL ES 3.0に準拠した多数の組み込み関数がサポートされています。 vec_type(float)、vec_int_type、vec_uint_type、vec_bool_type 命名法を使用する場合、スカラーまたはベクトルを使用できます。

注釈

GLES2バックエンドで使用できない関数のリストについては、Differences between GLES2 and GLES3 doc を参照してください。

関数

説明

vec_type radians (vec_type degrees)

度をラジアンに変換する

vec_type degrees (vec_type radians)

ラジアンを度に変換

vec_type sin (vec_type x)

サイン(正弦)

vec_type cos (vec_type x)

コサイン(余弦)

vec_type tan (vec_type x)

タンジェント(正接)

vec_type asin (vec_type x)

Arcsine

vec_type acos (vec_type x)

Arccosine

vec_type atan (vec_type y_over_x)

Arctangent

vec_type atan (vec_type y, vec_type x)

Arctangent to convert vector to angle

vec_type sinh (vec_type x)

Hyperbolic sine

vec_type cosh (vec_type x)

Hyperbolic cosine

vec_type tanh (vec_type x)

Hyperbolic tangent

vec_type asinh (vec_type x)

Inverse hyperbolic sine

vec_type acosh (vec_type x)

Inverse hyperbolic cosine

vec_type atanh (vec_type x)

Inverse hyperbolic tangent

vec_type pow (vec_type x, vec_type y)

Power (undefined if x < 0 or if x = 0 and y <= 0)

vec_type exp (vec_type x)

Base-e exponential

vec_type exp2 (vec_type x)

Base-2 exponential

vec_type log (vec_type x)

Natural logarithm

vec_type log2 (vec_type x)

Base-2 logarithm

vec_type sqrt (vec_type x)

Square root

vec_type inversesqrt (vec_type x)

Inverse square root

vec_type abs (vec_type x)

絶対値

ivec_type abs (ivec_type x)

絶対値

vec_type sign (vec_type x)

符号

ivec_type sign (ivec_type x)

符号

vec_type floor (vec_type x)

フロア(床関数)

vec_type round (vec_type x)

ラウンド(四捨五入)

vec_type roundEven (vec_type x)

Round to the nearest even number

vec_type trunc (vec_type x)

小数点切り捨て

vec_type ceil (vec_type x)

シィール(天井関数)

vec_type fract (vec_type x)

小数部

vec_type mod (vec_type x, vec_type y)

余剰

vec_type mod (vec_type x , float y)

余剰

vec_type modf (vec_type x, out vec_type i)

Fractional of x, with i as integer part

vec_type min (vec_type a, vec_type b)

小さい方の値

vec_type max (vec_type a, vec_type b)

大きい方の値

vec_type clamp (vec_type x, vec_type min, vec_type max)

Clamp to min..max

float mix (float a, float b, float c)

Linear interpolate

vec_type mix (vec_type a, vec_type b, float c)

Linear interpolate (scalar coefficient)

vec_type mix (vec_type a, vec_type b, vec_type c)

Linear interpolate (vector coefficient)

vec_type mix (vec_type a, vec_type b, bvec_type c)

Linear interpolate (boolean-vector selection)

vec_type step (vec_type a, vec_type b)

b[i] < a[i] ? 0.0 : 1.0

vec_type step (float a, vec_type b)

b[i] < a ? 0.0 : 1.0

vec_type smoothstep (vec_type a, vec_type b, vec_type c)

Hermite interpolate

vec_type smoothstep (float a, float b, vec_type c)

Hermite interpolate

bvec_type isnan (vec_type x)

Returns true if scalar or vector component is NaN

bvec_type isinf (vec_type x)

Returns true if scalar or vector component is INF

ivec_type floatBitsToInt (vec_type x)

浮動小数点数->Int ビットコピー、変換なし

uvec_type floatBitsToUint (vec_type x)

浮動小数点数->UInt ビットコピー、変換なし

vec_type intBitsToFloat (ivec_type x)

Int->浮動小数点 ビットコピー、変換なし

vec_type uintBitsToFloat (uvec_type x)

UInt->浮動小数点 ビットコピー、変換なし

float length (vec_type x)

Vector length

float distance (vec_type a, vec_type b)

ベクトル間の距離、つまり length(a-b)

float dot (vec_type a, vec_type b)

内積 (ドット積)

vec3 cross (vec3 a, vec3 b)

外積 (クロス積)

vec_type normalize (vec_type x)

単位長に正規化

vec3 reflect (vec3 I, vec3 N)

反射

vec3 refract (vec3 I, vec3 N, float eta)

屈折

vec_type faceforward (vec_type N, vec_type I, vec_type Nref)

If dot(Nref, I) < 0, return N, otherwise –N

mat_type matrixCompMult (mat_type x, mat_type y)

Matrix component multiplication

mat_type outerProduct (vec_type column, vec_type row)

Matrix outer product

mat_type transpose (mat_type m)

Transpose matrix

float determinant (mat_type m)

Matrix determinant

mat_type inverse (mat_type m)

Inverse matrix

bvec_type lessThan (vec_type x, vec_type y)

Bool vector comparison on < int/uint/float vectors

bvec_type greaterThan (vec_type x, vec_type y)

Bool vector comparison on > int/uint/float vectors

bvec_type lessThanEqual (vec_type x, vec_type y)

Bool vector comparison on <= int/uint/float vectors

bvec_type greaterThanEqual (vec_type x, vec_type y)

Bool vector comparison on >= int/uint/float vectors

bvec_type equal (vec_type x, vec_type y)

Bool vector comparison on == int/uint/float vectors

bvec_type notEqual (vec_type x, vec_type y)

Bool vector comparison on != int/uint/float vectors

bool any (bvec_type x)

任意の要素が true

bool all (bvec_type x)

全ての要素が true

bvec_type not (bvec_type x)

ブールベクトルの反転

ivec2 textureSize (sampler2D_type s, int lod)

2Dテクスチャのサイズを取得する

ivec3 textureSize (sampler2DArray_type s, int lod)

2Dテクスチャ配列のサイズを取得する

ivec3 textureSize (sampler3D s, int lod)

3Dテクスチャのサイズを取得する

ivec2 textureSize (samplerCube s, int lod)

Get the size of a cubemap texture

vec4_type texture (sampler2D_type s, vec2 uv [, float bias])

2Dテクスチャの読み取りを実行する

vec4_type texture (sampler2DArray_type s, vec3 uv [, float bias])

2D テクスチャ配列の読み取りを実行する

vec4_type texture (sampler3D_type s, vec3 uv [, float bias])

3Dテクスチャの読み取りを実行する

vec4 texture (samplerCube s, vec3 uv [, float bias])

Perform a cubemap texture read

vec4_type textureProj (sampler2D_type s, vec3 uv [, float bias])

投影を使用して2Dテクスチャの読み取りを実行する

vec4_type textureProj (sampler2D_type s, vec4 uv [, float bias])

投影を使用して2Dテクスチャの読み取りを実行する

vec4_type textureProj (sampler3D_type s, vec4 uv [, float bias])

投影を使用して3Dテクスチャの読み取りを実行する

vec4_type textureLod (sampler2D_type s, vec2 uv, float lod)

カスタムミップマップで2Dテクスチャの読み取りを実行する

vec4_type textureLod (sampler2DArray_type s, vec3 uv, float lod)

カスタムミップマップで2Dテクスチャ配列の読み取りを実行します

vec4_type textureLod (sampler3D_type s, vec3 uv, float lod)

カスタムミップマップで3Dテクスチャの読み取りを実行する

vec4 textureLod (samplerCube s, vec3 uv, float lod)

カスタムミップマップで3Dテクスチャの読み取りを実行する

vec4_type textureProjLod (sampler2D_type s, vec3 uv, float lod)

Perform a 2D texture read with projection/LOD

vec4_type textureProjLod (sampler2D_type s, vec4 uv, float lod)

Perform a 2D texture read with projection/LOD

vec4_type textureProjLod (sampler3D_type s, vec4 uv, float lod)

Perform a 3D texture read with projection/LOD

vec4_type texelFetch (sampler2D_type s, ivec2 uv, int lod)

Fetch a single texel using integer coordinates

vec4_type texelFetch (sampler2DArray_type s, ivec3 uv, int lod)

Fetch a single texel using integer coordinates

vec4_type texelFetch (sampler3D_type s, ivec3 uv, int lod)

Fetch a single texel using integer coordinates

vec_type dFdx (vec_type p)

Derivative in x using local differencing

vec_type dFdy (vec_type p)

Derivative in y using local differencing

vec_type fwidth (vec_type p)

Sum of absolute derivative in x and y