I wrote a simple shader which I want to apply to a mesh that I am procedurally generating in GDScript. I tested the shader in Godot in a test scene and it works perfectly. However I don't know how to instantiate the shader in GDScript. I was not able to find any resources about how this is done. The documentation of the Shader class seems incomplete.
I tried loading the shader code from a file and setting it. However as soon as I create a shader object, Godot throws an error:
SHADER ERROR: (null): Expected 'shader_type' at the beginning of shader.
At: :1.
ERROR: _update_shader: Condition ' err != OK ' is true.
At: drivers/gles3/rasterizer_storage_gles3.cpp:1698.
What is the correct way of loading a shader from a file at runtime and applying it to a ShaderMaterial without generating these errors?
The code I was trying out is of the following lines:
# read the shader code from a file
var file = File.new()
file.open("res://shaders/terrain_mix.shader", File.READ)
var code = ""
while !file.eof_reached():
code += file.get_line() + "\n"
# create the shader and shader material
var shader = Shader.new()
shader.set_code(code)
var material = ShaderMaterial.new()
material.set_shader_param("splatmap", ResourceManager.get_texture("splatmap"))
material.set_shader_param("texture1", ResourceManager.get_texture("sand"))
material.set_shader_param("texture2", ResourceManager.get_texture("grass"))
material.shader = shader
After setting the shader code, shader.get_code() returns the shader code correctly. However the problem is, that the error pops up as soon as the shader object instance is being created.
Here's the shader code although I don't think it's relevant, since it works when applied through the Godot editor:
shader_type spatial;
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform sampler2D texture3;
uniform sampler2D texture4;
uniform sampler2D splatmap;
void fragment () {
vec3 result;
float mix1 = texture(splatmap, UV).r;
float mix2 = texture(splatmap, UV).g;
float mix3 = texture(splatmap, UV).b;
float mix4 = texture(splatmap, UV).a;
vec3 color1 = texture(texture1, UV).rgb*mix1;
vec3 color2 = texture(texture1, UV).rgb*mix2;
vec3 color3 = texture(texture1, UV).rgb*mix3;
vec3 color4 = texture(texture1, UV).rgb*mix4;
result = color1 + color2 + color3 + color4;
ALBEDO = result;
}
Thanks!