Up to date

This page is up to date for Godot 4.3. If you still find outdated information, please open an issue.

シェーディング言語

はじめに

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

既にGLSLに精通している場合は、Godot Shader Migration Guide が、通常の GLSL からGodotのシェーディング言語への移行に役立つ資料です。

データ型

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

タイプ(型)

説明

void

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

bool

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

bvec2

Bool値の2要素ベクトル。

bvec3

Bool値の3要素ベクトル。

bvec4

Bool値の4要素ベクトル。

int

32 bit signed scalar integer.

ivec2

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

ivec3

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

ivec4

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

uint

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

uvec2

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

uvec3

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

uvec4

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

float

32 bit floating-point scalar.

vec2

浮動小数点の2要素ベクトル。

vec3

浮動小数点の3要素ベクトル。

vec4

浮動小数点の4要素ベクトル。

mat2

列優先順の2x2行列。

mat3

列優先順の3x3行列。

mat4

列優先順の4x4行列。

sampler2D

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

isampler2D

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

usampler2D

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

sampler2DArray

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

isampler2DArray

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

usampler2DArray

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

sampler3D

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

isampler3D

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

usampler3D

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

samplerCube

キューブマップテクスチャをバインドするためのサンプラータイプ。floatとして読み込まれます。

samplerCubeArray

Sampler type for binding Cubemap arrays, which are read as float. Only supported in Forward+ and Mobile, not Compatibility.

警告

Local variables are not initialized to a default value such as 0.0. If you use a variable without assigning it first, it will contain whatever value was already present at that memory location, and unpredictable visual glitches will appear. However, uniforms and varyings are initialized to a default value.

コメント

The shading language supports the same comment syntax as used in C# and C++:

// Single-line comment.
int a = 2;  // Another single-line comment.

/*
Multi-line comment.
The comment ends when the ending delimiter is found
(here, it's on the line below).
*/
int b = 3;

Additionally, you can use documentation comments that are displayed in the inspector when hovering a shader parameter. Documentation comments are currently only supported when placed immediately above a uniform declaration. These documentation comments only support the multiline comment syntax and must use two leading asterisks (/**) instead of just one (/*):

/**
 * This is a documentation comment.
 * These lines will appear in the inspector when hovering the shader parameter
 * named "Something".
 * You can use [b]BBCode[/b] [i]formatting[/i] in the comment.
 */
uniform int something = 1;

The asterisks on the follow-up lines are not required, but are recommended as per the シェーダースタイルガイド. These asterisks are automatically stripped by the inspector, so they won't appear in the tooltip.

キャスト

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[column] to access a vector by column index. For example, for accessing the y-component of the translation from a mat4 transform matrix (4th column, 2nd line) you use m[3][1] or m[3].y.

構築

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

// 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);

Construction of matrix types requires vectors of the same dimension as the matrix, interpreted as columns. You can also build a diagonal matrix using matx(float) syntax. Accordingly, mat4(1.0) is an identity matrix.

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 つあります:

1. If a larger matrix is constructed from a smaller matrix, the additional rows and columns are set to the values they would have in an identity matrix. 2. If a smaller matrix is constructed from a larger matrix, the top, left submatrix of the larger matrix is used.

mat3 basis = mat3(MODEL_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 (32 bit default)

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

一部のアーキテクチャ (主にモバイル) では、これによって大きなメリットが得られますが、精度間の変換による追加のオーバーヘッドなどの欠点もあります。詳細については、ターゲットアーキテクチャのドキュメントを参照してください。多くの場合、モバイル環境のドライバーは一貫性のない動作や予期しない動作を引き起こすため、必要な場合を除いて精度を指定しないことをお勧めします。

配列

配列は複数の同じ型の変数のコンテナです。

ローカル配列

ローカル配列は関数内で宣言されます。サンプラーを除くすべての許可されたデータ型を使用できます。配列宣言は、Cスタイルの構文 [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++) {
    // ...
}

注釈

0未満または配列サイズより大きいインデックスを使用すると、シェーダーがクラッシュしてレンダリングが中断します。これを防ぐには、length()if または clamp() 関数を使用して、インデックスが0と配列の長さの間にあることを確認してください。コードは常に慎重にテストおよびチェックしてください。定数式または単純な数値を渡すと、エディタはその境界をチェックしてこのクラッシュを防ぎます。

グローバル配列

次のようにグローバルスコープで配列を宣言できます:

shader_type spatial;

const lowp vec3 v[1] = lowp vec3[1] ( vec3(0, 0, 1) );

void fragment() {
  ALBEDO = v[0];
}

注釈

グローバル配列はグローバル定数として宣言する必要があります。それ以外の場合はローカル配列と同じように宣言できます。

定数

変数宣言の前に 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 GOLDEN_RATIO = 1.618033988749894;

float 型の定数は整数部の後に . 表記を使用するか科学表記法を使用して初期化する必要があります。オプションの f 後置接尾語もサポートされています。

float a = 1.0;
float b = 1.0f; // same, using suffix for clarity
float c = 1e-1; // gives 0.1 by using the scientific notation

uint (unsigned int) 型の定数には、 int (signed int) 型と区別するために u 接尾辞が必要です。もしくは組み込み変換関数 uint(x) を使用することもできます。

uint a = 1u;
uint b = uint(1);

構造体

構造体はシェーダーコードをより適切に抽象化するために使用できる複合型です。次のようにグローバルスコープで宣言できます。

struct PointLight {
    vec3 position;
    vec3 color;
    float intensity;
};

宣言後、次のようにインスタンス化して初期化できます。

void fragment()
{
    PointLight light;
    light.position = vec3(0.0);
    light.color = vec3(1.0, 0.0, 0.0);
    light.intensity = 0.5;
}

また、同じ目的で構造体のコンストラクタを使用できます。

PointLight light = PointLight(vec3(0.0), vec3(1.0, 0.0, 0.0), 0.5);

構造体には他の構造体や配列を含めることができ、それらをグローバル定数としてインスタンス化することもできます。

shader_type spatial;

...

struct Scene {
    PointLight lights[2];
};

const Scene scene = Scene(PointLight[2](PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0)));

void fragment()
{
    ALBEDO = scene.lights[0].color;
}

構造体のインスタンスを関数へ渡すこともできます。

shader_type canvas_item;

...

Scene construct_scene(PointLight light1, PointLight light2) {
    return Scene({light1, light2});
}

void fragment()
{
    COLOR.rgb = construct_scene(PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0), 1.0), PointLight(vec3(0.0, 0.0, 0.0), vec3(1.0, 0.0, 1.0), 1.0)).lights[0].color;
}

オペレーター

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

優先順位

クラス

演算子

1 (最高)

カッコ内のグループ化

()

2

単項

+、-、!、~

3

乗除算

/、*、%

4

加減算

+、-

5

ビット単位のシフト

<<、>>

6

大小比較

<、>、<=、>=

7

一致、不一致

==、!=

8

ビット単位のAND

&

9

ビット単位の排他的OR

^

10

ビット単位の包括的OR

|

11

論理AND

&&

12 (最低)

論理OR

||

構文制御

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

// `if` and `else`.
if (cond) {

} else {

}

// Ternary operator.
// This is an expression that behaves like `if`/`else` and returns the value.
// If `cond` evaluates to `true`, `result` will be `9`.
// Otherwise, `result` will be `5`.
int result = cond ? 9 : 5;

// `switch`.
switch (i) { // `i` should be a signed integer expression.
    case -1:
        break;
    case 0:
        return; // `break` or `return` to avoid running the next `case`.
    case 1: // Fallthrough (no `break` or `return`): will run the next `case`.
    case 2:
        break;
    //...
    default: // Only run if no `case` above matches. Optional.
        break;
}

// `for` loop. Best used when the number of elements to iterate on
// is known in advance.
for (int i = 0; i < 10; i++) {

}

// `while` loop. Best used when the number of elements to iterate on
// is not known in advance.
while (cond) {

}

// `do while`. Like `while`, but always runs at least once even if `cond`
// never evaluates to `true`.
do {

} while (cond);

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

また、浮動小数点値を比較する場合は、正確な数値ではなく 範囲 と比較してください。

if (value == 0.3) のような比較は、 true と評価されない可能性があります。浮動小数点演算は近似的なことが多く、期待を裏切る可能性があります。また、ハードウェアに応じて動作が異なる場合もあります。

これは 書かないでください

float value = 0.1 + 0.2;

// May not evaluate to `true`!
if (value == 0.3) {
    // ...
}

代わりに、イプシロン値との範囲比較を行います。浮動小数点数が大きいほど (浮動小数点数の精度が低いほど)、イプシロン値も大きくする必要があります。

const float EPSILON = 0.0001;
if (value >= 0.3 - EPSILON && value <= 0.3 + EPSILON) {
    // ...
}

詳細については floating-point-gui.de を見てください。

ピクセルの破棄

fragment関数とlight関数では、 discard キーワードを使用できます。discardが実行されたフラグメントは破棄され、何も書き込まれません。

discard を使用すると、シェーダを使用するサーフェス上で深度プリパスが有効にならなくなるため、使用するとパフォーマンスが低下することに注意してください。また、破棄されたピクセルでも依然として頂点シェーダーで処理する必要があります。つまり、すべてのピクセルが 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: 引数が参照を介して完全に渡されることを意味します。

  • const: 引数が定数で変更できないことを意味します。 in 修飾子と組み合わせることができます。

以下はその例です:

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

注釈

GLSL とは異なり、Godot のシェーダ言語は関数のオーバーロードを**サポートしません**。これは、異なる引数の型や引数の数を受け入れる関数を複数回定義することはできないことを意味します。回避策として、異なる数の引数または異なる型の引数を受け入れる関数には別々の名前を指定します。

Varying(可変)

頂点からフラグメント (またはライト) プロセッサ関数にデータを送信するには、varying が使用されます。それらは 頂点プロセッサ のすべてのプリミティブ頂点に対して設定され、フラグメント プロセッサ のすべてのピクセルに対して値が補間されます。

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
}

variing キーワードを使用して、fragment から light プロセッサにデータを送信することもできます。これを行うには、fragment で割り当てて、後で light 関数で使用します。

shader_type spatial;

varying vec3 some_light;

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

void light() {
    DIFFUSE_LIGHT = some_light;
}

以下のようなカスタム関数や light 関数では、varying に代入することはできないことに注意してください。

shader_type spatial;

varying float test;

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

void vertex() {
    test = 0.0;
}

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

この制限は、初期化前の誤った使用を防ぐために導入されました。

補間修飾子

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

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 vec3 colors[3];

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

material.set_shader_parameter("some_value", some_value)

material.set_shader_parameter("colors", [Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(0, 0, 1)])

注釈

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

注釈

There is a limit to the total size of shader uniforms that you can use in a single shader. On most desktop platforms, this limit is 65536 bytes, or 4096 vec4 uniforms. On mobile platforms, the limit is typically 16384 bytes, or 1024 vec4 uniforms. Vector uniforms smaller than a vec4, such as vec2 or vec3, are padded to the size of a vec4. Scalar uniforms such as int or float are not padded, and bool is padded to the size of an int.

Arrays count as the total size of their contents. If you need a uniform array that is larger than this limit, consider packing the data into a texture instead, since the contents of a texture do not count towards this limit, only the size of the sampler uniform.

void を除くすべてのGLSLタイプはuniformにすることができます。さらに、Godot はuniformが何に使用されているか、およびエディターがユーザーにuniformをどのように変更できるようにするかをコンパイラーに理解させるためのオプションとしてシェーダーヒントを提供します。

shader_type spatial;

uniform vec4 color : source_color;
uniform float amount : hint_range(0, 1);
uniform vec4 other_color : source_color = vec4(1.0); // Default values go after the hint.
uniform sampler2D image : source_color;

Godot の 3D エンジンはリニア色空間でレンダリングするため、カラーとして提供される テクスチャには、適切な sRGB -> リニア変換 (すなわち、source_color) のためのヒントが必要であることを理解することが重要です。これを行わないとテクスチャが色あせたように見えます。

注釈

[レンダリング] > [ビューポート] > [HDR 2D] プロジェクト設定が有効になっている場合、2Dレンダラーはリニア 色空間でもレンダリングするため、 source_colorcanvas_item シェーダで使用する必要があります。 2D HDR が無効になっている場合でも、 source_colorcanvas_item シェーダで正しく動作し続けるため、どちらの方法でも使用することをお勧めします。

以下はヒントの一覧です:

タイプ(型)

ヒント

説明

vec3, vec4

source_color

色として使用します。

int, float

hint_range(min, max[, step])

値の制限範囲を指定します (min/max/step)。

sampler2D

source_color

アルベド色として使用します。

sampler2D

hint_normal

法線マップとして使用します。

sampler2D

hint_default_white

アルベド色として使用します。デフォルトは白色。

sampler2D

hint_default_black

アルベド色として使用します。デフォルトは黒色。

sampler2D

hint_default_transparent

アルベド色として使用します。デフォルトは黒色。

sampler2D

hint_anisotropy

フローマップとして使用します。デフォルトは右方向。

sampler2D

hint_roughness[_r, _g, _b, _a, _normal, _gray]

インポート時のラフネスリミッターに使用されます (鏡面反射光エイリアシングの軽減を試みます)。_normal は、ラフネスリミッターをガイドする法線マップであり、高周波のディテールを持つ領域では粗さが増加します。

sampler2D

filter[_nearest, _linear][_mipmap][_anisotropic]

指定されたテクスチャフィルタリングを有効にします。

sampler2D

repeat[_enable, _disable]

テクスチャのリピートを有効にします。

sampler2D

hint_screen_texture

スクリーンのテクスチャを指定します。

sampler2D

hint_depth_texture

深度テクスチャを指定します。

sampler2D

hint_normal_roughness_texture

法線とラフネスのテクスチャです (Forward+ でのみサポートされています)。

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

GLSL型

GDScript型

備考

bool

bool

bvec2

int

intに各ビットがパックされます。ビット0(LSB) がxに対応。

たとえば、 (bx, by) の bvec2 は次の方法で作成できます。

bvec2_input: int = (int(bx)) | (int(by) << 1)

bvec3

int

intに各ビットがパックされます。ビット0(LSB) がxに対応。

bvec4

int

intに各ビットがパックされます。ビット0(LSB) がxに対応。

int

int

ivec2

Vector2i

ivec3

Vector3i

ivec4

Vector4i

uint

int

uvec2

Vector2i

uvec3

Vector3i

uvec4

Vector4i

float

float

vec2

Vector2

vec3

Vector3, Color

Color が使用される場合、(r, g, b) として解釈されます。

vec4

Vector4, Color, Rect2, Plane, Quaternion

Color が使用される場合、(r, g, b, a) として解釈されます。

Rect2 が使用される場合、(position.x, position.y, size.x, size.y) として解釈されます。

Plane が使用される場合、(normal.x, normal.y, normal.z, d) として解釈されます。

mat2

Transform2D

mat3

Basis

mat4

Projection, Transform3D

Transform3D が使用される場合、w Vectorは単位行列になるように設定されます。

sampler2D

Texture2D

isampler2D

Texture2D

usampler2D

Texture2D

sampler2DArray

Texture2DArray

isampler2DArray

Texture2DArray

usampler2DArray

Texture2DArray

sampler3D

Texture3D

isampler3D

Texture3D

usampler3D

Texture3D

samplerCube

Cubemap

See インポートタイプの変更 for instructions on importing cubemaps for use in Godot.

samplerCubeArray

CubemapArray

Only supported in Forward+ and Mobile, not Compatibility.

注釈

GDScriptからシェーダーのuniformを設定するときは注意してください。タイプが一致しない場合でもエラーはスローされません。シェーダーは未定義の動作を示すだけです。

警告

As with the last note, no error will be thrown if the typing does not match while setting a shader uniform, this unintuitively includes setting a (GDscript) 64 bit int/float into a Godot shader language int/float (32 bit). This may lead to unintentional consequences in cases where high precision is required.

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

shader_type spatial;

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

デフォルト値とヒントを追加する場合、デフォルト値がヒントの後に来ることに注意してください。

複数のUniformをインスペクターの特定のカテゴリにグループ化する必要がある場合は、次のように group_uniform キーワードを使用できます。

group_uniforms MyGroup;
uniform sampler2D test;

そしてこちらを使用してグループを閉じることができます:

group_uniforms;

この構文はサブグループもサポートしています (これより前にベースのグループを宣言することは必須ではありません):

group_uniforms MyGroup.MySubgroup;

グローバルUniform

場合によっては多くの異なるシェーダのパラメータを一度に変更したいことがあります。通常のUniformの場合はすべてのシェーダーを探し、それぞれにUniformを設定する必要があるため、多くの作業が必要になります。グローバルUniformを使用するとすべてのシェーダーやすべてのシェーダータイプ ( canvas_itemspatialparticlesskyfog ) で使用できるUniformを作成および更新できます。

グローバルUniformは、プレイヤーが近くにいるときに葉が曲がったり、オブジェクトが風で動いたりするなど、シーン内の多くのオブジェクトに影響を与えるような効果で特に役立ちます。

グローバルUniformを作成するには、 プロジェクト設定 を開き、 シェーダーグローバル タブに移動します。uniformの名前 (大文字と小文字を区別に注意) と型を指定し、ダイアログの右上隅にある 追加 ボタンをクリックします。次にuniformのリスト内の項目をクリックして、uniformに割り当てられた値を編集できます。

プロジェクト設定のシェーダー グローバル タブにグローバルUniformを追加する

プロジェクト設定のシェーダー グローバル タブにグローバルUniformを追加する

グローバルUniformを作成した後、次のようにシェーダーで使用できます。

shader_type canvas_item;

global uniform vec4 my_color;

void fragment() {
    COLOR = my_color.rgb;
}

グローバルUniformはシェーダーの保存時にプロジェクト設定に存在する 必要があります 。存在しない場合はコンパイルは失敗します。シェーダーコードで global uniform vec4 my_color = ... を使用してデフォルト値を割り当てることはできますが、グローバルUniformの値は常にプロジェクト設定で指定する必要があるため、このデフォルト値は無視されます。

実行時にグローバルUniformの値を変更するには、スクリプトで RenderingServer.global_shader_parameter_set メソッドを使用します。

RenderingServer.global_shader_parameter_set("my_color", Color(0.3, 0.6, 1.0))

データの設定にはCPUとGPU間の同期が必要ないため、グローバルUniform値のセットは、パフォーマンスに影響を与えることなく何度でも行うことができます。

実行時にグローバルUniformを追加または削除することもできます:

RenderingServer.global_shader_parameter_add("my_color", RenderingServer.GLOBAL_VAR_TYPE_COLOR, Color(0.3, 0.6, 1.0))
RenderingServer.global_shader_parameter_remove("my_color")

実行時にグローバルUniformを追加または削除すると、スクリプトからグローバルUniform値を取得する場合ほど顕著ではありませんが、パフォーマンスコストが発生します (以下の警告を参照)。

警告

RenderingServer.global_shader_parameter_get("uniform_name") を使用してスクリプトで実行時にグローバルUniformの値を取得することは できます が、レンダリングスレッドは呼び出しスレッドと同期する必要があるため、パフォーマンスが大幅に低下します。

したがってスクリプト内でグローバルシェーダーのUniform値を連続的に読み取ることはお勧めできません。設定後にスクリプトで値を読み取る必要がある場合は、グローバルUniformとしてセットすると同時に取得するために値を保存するシングルトンクラス autoload を作成することを検討してください。

インスタンス単位のUniform

注釈

インスタンス単位のUniformは spatial (3D) シェーダーでのみ使用できます。

注釈

Per-instance uniforms are not supported when using the Compatibility renderer.

マテリアルを使用して各ノードのパラメータを変更したい場合があります。たとえば木々が生い茂る森で、それぞれの木に手動で編集できるわずかに異なる色を持たせたい場合です。インスタンスごとにUniformを持たない場合、木ごとに固有のマテリアル (それぞれがわずかに異なる色) を作成する必要があります。これによりマテリアル管理がより複雑になり、シーンではより固有のマテリアルインスタンスが必要になるため、パフォーマンスのオーバーヘッドも発生します。ここでは頂点カラーを使用することもできますが、異なる色ごとにメッシュの一意のコピーを作成する必要があり、パフォーマンスのオーバーヘッドも発生します。

インスタンス単位のUniformは、各マテリアルインスタンスではなく、各 GeometryInstance3D に設定されます。複数のマテリアルが割り当てられているメッシュ、またはマルチメッシュを操作する場合は、こちらを考慮してください。

shader_type spatial;

// Provide a hint to edit as a color. Optionally, a default value can be provided.
// If no default value is provided, the type's default is used (e.g. opaque black for colors).
instance uniform vec4 my_color : source_color = vec4(1.0, 0.5, 0.0, 1.0);

void fragment() {
    ALBEDO = my_color.rgb;
}

シェーダーを保存した後、インスペクターを使用してインスタンス単位のUniformの値を変更できます。

インスペクターの GeometryInstance3D セクションでインスタンス単位のUniformの値 (Instance Shader Parameters) を設定する

インスペクターの GeometryInstance3D セクションでインスタンス単位のUniformの値 (Instance Shader Parameters) を設定する

インスタンス単位のUniform値は、GeometryInstance3D を継承するノード上で set_instance_shader_parameter メソッドを使用して実行時にセットすることもできます。

$MeshInstance3D.set_instance_shader_parameter("my_color", Color(0.3, 0.6, 1.0))

インスタンス単位のUniformを使用する場合は、いくつかの制限事項に注意する必要があります:

  • インスタンス単位のUniformはテクスチャをサポートしません 。通常のスカラー型とベクター型のみをサポートします。回避策としてはテクスチャ配列を通常のUniformとして渡してから、インスタンス単位のUniformを使用して描画されるテクスチャのインデックスを渡すことができます。

  • 実際には1シェーダーあたりのインスタンスUniformの最大数は16までに制限されています。

  • メッシュが複数のマテリアルを使用している場合、名前、インデックス、型が同じでない限り、最初に見つかったメッシュマテリアルのパラメータが後続のメッシュマテリアルよりも「優先」されます。この場合すべてのパラメータが正しく影響されます。

  • 上記の状況に遭遇した場合は、 instance_index ヒントを使用してインスタンスUniformのインデックス (0~15) を手動で指定することで衝突を回避できます。

instance uniform vec4 my_color : source_color, instance_index(5);

ビルトイン変数

UVCOLORVERTEX など、多くのビルトイン変数が使用可能です。どの変数が使用できるかは、シェーダのタイプ ( spatialcanvas_itemparticle) および使用される関数 ( vertexfragmentlight ) によって異なります。使用可能な組み込み変数のリストについては、対応するページを参照してください。

ビルトイン関数

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

関数

説明 /返り値

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)

アークコサイン(逆余弦)。

vec_type acos (vec_type x)

アークコサイン(逆余弦)。

vec_type atan (vec_type y_over_x)

アークタンジェント(逆正接)。

vec_type atan (vec_type y, vec_type x)

アークタンジェント(逆正接)。

vec_type sinh (vec_type x)

双曲線コサイン。

vec_type cosh (vec_type x)

双曲線コサイン。

vec_type tanh (vec_type x)

双曲線タンジェント。

vec_type asinh (vec_type x)

双曲線アークコサイン。

vec_type acosh (vec_type x)

双曲線アークコサイン。

vec_type atanh (vec_type x)

双曲線アークタンジェント。

vec_type pow (vec_type x, vec_type y)

xのy乗 (未定義条件: if x < 0 or if x == 0 and y <= 0)。

vec_type exp (vec_type x)

eを底とする指数。

vec_type exp2 (vec_type x)

2を底とする指数。

vec_type log (vec_type x)

自然対数。

vec_type log2 (vec_type x)

2を底とする対数。

vec_type sqrt (vec_type x)

平方根。

vec_type inversesqrt (vec_type x)

逆平方根。

vec_type abs (vec_type x)

ivec_type abs (ivec_type x)

絶対値 (負の場合は正の値を返す)。

vec_type sign (vec_type x)

ivec_type sign (ivec_type x)

符号 (正の時 1.0 を返し、負の時 -1.0 を返し、ゼロの時 0.0 を返す)。

vec_type floor (vec_type x)

x以下の最も近い整数に丸める。

vec_type round (vec_type x)

最も近い整数に丸める(四捨五入)。

vec_type roundEven (vec_type x)

最も近い偶数の整数に丸める。

vec_type trunc (vec_type x)

ゼロ方向の整数に丸める(小数点切り捨て)。

vec_type ceil (vec_type x)

x以上の最も近い整数に丸める。

vec_type fract (vec_type x)

小数部 (x - floor(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)

xの小数部を返し、iに整数部が代入される。

vec_type min (vec_type a, vec_type b)

ab の小さいほうを返す。

vec_type max (vec_type a, vec_type b)

ab の大きいほうを返す。

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

x を範囲内( minmax の間)に収めた値を返す。

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

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

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

ab の間を c で線形補間する。

vec_type fma (vec_type a, vec_type b, vec_type c)

融合積和演算 (a * b + c) を行う(手動で書くより高速です)。

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)

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

ab の間を c でエルミート補間する。

bvec_type isnan (vec_type x)

スカラーまたはベクトル要素が NaN の場合は true を返す。

bvec_type isinf (vec_type x)

スカラーまたはベクトル要素が INF の場合は、 true を返す。

ivec_type floatBitsToInt (vec_type x)

float型からint型へビットを維持してコピー。

uvec_type floatBitsToUint (vec_type x)

float型からuint型へビットを維持してコピー。

vec_type intBitsToFloat (ivec_type x)

int型からfloat型へビットを維持してコピー。

vec_type uintBitsToFloat (uvec_type x)

uint型からfloat型へビットを維持してコピー。

float length (vec_type x)

ベクトルの長さ。

float distance (vec_type a, vec_type b)

2つのベクトル間の距離。つまり 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)

dot(Nref, I) < 0 の場合は N を返し、それ以外の場合は -N を返す。

mat_type matrixCompMult (mat_type x, mat_type y)

行列要素の乗算。

mat_type outerProduct (vec_type column, vec_type row)

行列の外積。

mat_type transpose (mat_type m)

転置行列。

float determinant (mat_type m)

行列式。

mat_type inverse (mat_type m)

逆行列。

bvec_type lessThan (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x < y)した結果をboolベクトルとして返す。

bvec_type greaterThan (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x > y)した結果をboolベクトルとして返す。

bvec_type lessThanEqual (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x <= y)した結果をboolベクトルとして返す。

bvec_type greaterThanEqual (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x >= y)した結果をboolベクトルとして返す。

bvec_type equal (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x == y)した結果をboolベクトルとして返す。

bvec_type notEqual (vec_type x, vec_type y)

int/uint/floatベクトルの各要素を比較(x != y)した結果をboolベクトルとして返す。

bool any (bvec_type x)

いずれかの要素が true の場合は true 、それ以外の場合は false を返す。

bool all (bvec_type x)

すべての要素が true の場合は true 、それ以外の場合は false を返す。

bvec_type not (bvec_type x)

boolベクトルの反転。

ivec2 textureSize (gsampler2D s, int lod)

ivec3 textureSize (gsampler2DArray s, int lod)

ivec3 textureSize (gsampler3D s, int lod)

ivec2 textureSize (samplerCube s, int lod)

ivec2 textureSize (samplerCubeArray s, int lod)

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

LOD はどのミップマップレベルが使用されるかを指定します。 LOD値が 0 の場合は、フル解像度のテクスチャが使用されます。

vec2 textureQueryLod (gsampler2D s, vec2 p)

vec3 textureQueryLod (gsampler2DArray s, vec2 p)

vec2 textureQueryLod (gsampler3D s, vec3 p)

vec2 textureQueryLod (samplerCube s, vec3 p)

Compute the level-of-detail that would be used to sample from a texture. The x component of the resulted value is the mipmap array that would be accessed. The y component is computed level-of-detail relative to the base level (regardless of the mipmap levels of the texture).

int textureQueryLevels (gsampler2D s)

int textureQueryLevels (gsampler2DArray s)

int textureQueryLevels (gsampler3D s)

int textureQueryLevels (samplerCube s)

テクスチャのアクセス可能なミップマップレベルの数を取得する。

テクスチャがサンプラーに割り当てられていない場合は 1 が返る。(Godot は空のサンプラーにも常に内部でテクスチャを割り当てます)。

gvec4_type texture (gsampler2D s, vec2 p [, float bias])

gvec4_type texture (gsampler2DArray s, vec3 p [, float bias])

gvec4_type texture (gsampler3D s, vec3 p [, float bias])

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

vec4 texture (samplerCubeArray s, vec4 p [, float bias])

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

gvec4_type textureProj (gsampler2D s, vec3 p [, float bias])

gvec4_type textureProj (gsampler2D s, vec4 p [, float bias])

gvec4_type textureProj (gsampler3D s, vec4 p [, float bias])

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

gvec4_type textureLod (gsampler2D s, vec2 p, float lod)

gvec4_type textureLod (gsampler2DArray s, vec3 p, float lod)

gvec4_type textureLod (gsampler3D s, vec3 p, float lod)

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

vec4 textureLod (samplerCubeArray s, vec4 p, float lod)

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

The LOD defines which mipmap level is used. An LOD value of 0.0 will use the full resolution texture. If the texture lacks mipmaps, all LOD values will act like 0.0.

gvec4_type textureProjLod (gsampler2D s, vec3 p, float lod)

gvec4_type textureProjLod (gsampler2D s, vec4 p, float lod)

gvec4_type textureProjLod (gsampler3D s, vec4 p, float lod)

Performs a texture read with projection/LOD.

The LOD defines which mipmap level is used. An LOD value of 0.0 will use the full resolution texture. If the texture lacks mipmaps, all LOD values will act like 0.0.

gvec4_type textureGrad (gsampler2D s, vec2 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureGrad (gsampler2DArray s, vec3 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureGrad (gsampler3D s, vec3 p, vec2 dPdx, vec2 dPdy)

vec4 textureGrad (samplerCube s, vec3 p, vec3 dPdx, vec3 dPdy)

vec4 textureGrad (samplerCubeArray s, vec3 p, vec3 dPdx, vec3 dPdy)

Performs a texture read with explicit gradients.

gvec4_type textureProjGrad (gsampler2D s, vec3 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureProjGrad (gsampler2D s, vec4 p, vec2 dPdx, vec2 dPdy)

gvec4_type textureProjGrad (gsampler3D s, vec4 p, vec3 dPdx, vec3 dPdy)

Performs a texture read with projection/LOD and with explicit gradients.

gvec4_type texelFetch (gsampler2D s, ivec2 p, int lod)

gvec4_type texelFetch (gsampler2DArray s, ivec3 p, int lod)

gvec4_type texelFetch (gsampler3D s, ivec3 p, int lod)

整数座標を使用して単一のテクセルを取得する。

LOD はどのミップマップレベルが使用されるかを指定します。 LOD値が 0 の場合は、フル解像度のテクスチャが使用されます。

gvec4_type textureGather (gsampler2D s, vec2 p [, int comps])

gvec4_type textureGather (gsampler2DArray s, vec3 p [, int comps])

vec4 textureGather (samplerCube s, vec3 p [, int comps])

Gathers four texels from a texture. Use comps within range of 0..3 to define which component (x, y, z, w) is returned. If comps is not provided: 0 (or x-component) is used.

vec_type dFdx (vec_type p)

Derivative in x using local differencing. Internally, can use either dFdxCoarse or dFdxFine, but the decision for which to use is made by the GPU driver.

vec_type dFdxCoarse (vec_type p)

Calculates derivative with respect to x window coordinate using local differencing based on the value of p for the current fragment neighbour(s), and will possibly, but not necessarily, include the value for the current fragment. This function is not available on gl_compatibility profile.

vec_type dFdxFine (vec_type p)

Calculates derivative with respect to x window coordinate using local differencing based on the value of p for the current fragment and its immediate neighbour(s). This function is not available on gl_compatibility profile.

vec_type dFdy (vec_type p)

Derivative in y using local differencing. Internally, can use either dFdyCoarse or dFdyFine, but the decision for which to use is made by the GPU driver.

vec_type dFdyCoarse (vec_type p)

Calculates derivative with respect to y window coordinate using local differencing based on the value of p for the current fragment neighbour(s), and will possibly, but not necessarily, include the value for the current fragment. This function is not available on gl_compatibility profile.

vec_type dFdyFine (vec_type p)

Calculates derivative with respect to y window coordinate using local differencing based on the value of p for the current fragment and its immediate neighbour(s). This function is not available on gl_compatibility profile.

vec_type fwidth (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdx(p)) + abs(dFdy(p)).

vec_type fwidthCoarse (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdxCoarse(p)) + abs(dFdyCoarse(p)). This function is not available on gl_compatibility profile.

vec_type fwidthFine (vec_type p)

Sum of absolute derivative in x and y. This is the equivalent of using abs(dFdxFine(p)) + abs(dFdyFine(p)). This function is not available on gl_compatibility profile.

uint packHalf2x16 (vec2 v)

vec2 unpackHalf2x16 (uint v)

Convert two 32-bit floating-point numbers into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packUnorm2x16 (vec2 v)

vec2 unpackUnorm2x16 (uint v)

Convert two 32-bit floating-point numbers (clamped within 0..1 range) into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packSnorm2x16 (vec2 v)

vec2 unpackSnorm2x16 (uint v)

Convert two 32-bit floating-point numbers (clamped within -1..1 range) into 16-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packUnorm4x8 (vec4 v)

vec4 unpackUnorm4x8 (uint v)

Convert four 32-bit floating-point numbers (clamped within 0..1 range) into 8-bit and pack them into a 32-bit unsigned integer and vice-versa.

uint packSnorm4x8 (vec4 v)

vec4 unpackSnorm4x8 (uint v)

Convert four 32-bit floating-point numbers (clamped within -1..1 range) into 8-bit and pack them into a 32-bit unsigned integer and vice-versa.

ivec_type bitfieldExtract (ivec_type value, int offset, int bits)

uvec_type bitfieldExtract (uvec_type value, int offset, int bits)

Extracts a range of bits from an integer.

ivec_type bitfieldInsert (ivec_type base, ivec_type insert, int offset, int bits)

uvec_type bitfieldInsert (uvec_type base, uvec_type insert, int offset, int bits)

Insert a range of bits into an integer.

ivec_type bitfieldReverse (ivec_type value)

uvec_type bitfieldReverse (uvec_type value)

Reverse the order of bits in an integer.

ivec_type bitCount (ivec_type value)

uvec_type bitCount (uvec_type value)

Counts the number of 1 bits in an integer.

ivec_type findLSB (ivec_type value)

uvec_type findLSB (uvec_type value)

Find the index of the least significant bit set to 1 in an integer.

ivec_type findMSB (ivec_type value)

uvec_type findMSB (uvec_type value)

Find the index of the most significant bit set to 1 in an integer.

void imulExtended (ivec_type x, ivec_type y, out ivec_type msb, out ivec_type lsb)

void umulExtended (uvec_type x, uvec_type y, out uvec_type msb, out uvec_type lsb)

Multiplies two 32-bit numbers and produce a 64-bit result. x - the first number. y - the second number. msb - will contain the most significant bits. lsb - will contain the least significant bits.

uvec_type uaddCarry (uvec_type x, uvec_type y, out uvec_type carry)

Adds two unsigned integers and generates carry.

uvec_type usubBorrow (uvec_type x, uvec_type y, out uvec_type borrow)

Subtracts two unsigned integers and generates borrow.

vec_type ldexp (vec_type x, out ivec_type exp)

Assemble a floating-point number from a value and exponent.

If this product is too large to be represented in the floating-point type the result is undefined.

vec_type frexp (vec_type x, out ivec_type exp)

Splits a floating-point number(x) into significand (in the range of [0.5, 1.0]) and an integral exponent.

For x equals zero the significand and exponent are both zero. For x of infinity or NaN, the results are undefined.