0

Im learning shaders in Godot, and I need to read the value of a variable from a shader. I currently have a similar setup to the following:

shader_type canvas_item;

varying float value;

void fragment()
{
    value = some_data;
}

Now, having a GDScript attached to the same Node, how can I read value? Ive tried using custom Viewports and ComputeBuffers, but I cant get them to work.

What I am trying to do is to create a kind of like "light" shader, so that the alpha from each pixel decreases as the mouse gets further from that pixel. However, I wasnt able to get it to work, and so I was trying to print said distance from a GDScript, and that lead to this question. The following is my current attempt to that shader:

shader_type canvas_item;

uniform vec2 mousePos; //This variable is filled from another GDScript
uniform float lightRadius = 10.0;

void fragment() {
    // Called for every pixel the material is visible on.
    //COLOR = vec4(sin(UV.x), cos(UV.y), 0.0, 1.0);
    COLOR = texture(TEXTURE, UV);
    float dist = distance(mousePos, FRAGCOORD.xy);
    COLOR.a = dist;
}

Since I couldnt get it to work, I was trying to print dist from another script.

Edit: explanation of my problem. Thanks in advance!

1
  • This sounds like a XY Problem. What are you trying to do? Reading from the GPU is expensive; currently, I would suggest to reconstruct value from the same logic of some_data in your script. If you elaborate more and provide details, we will be able to give a more precise solution to your issue. Commented Apr 25 at 20:36

1 Answer 1

0

Depending on the type of your node, you may have a method for recovering the current material applied to it. Please refer to the godot documentation: https://docs.godotengine.org/.

This varies from 3d or 2d, it can be get_material_overlay or get_material_override ...

So, in your gdscript, you can get the material with (for example) get_material_overlay. And you can read the shader value with get_shader_parameter.

This gives :

func _ready():
    print(get_material_overlay().get_shader_parameter("dist"))

And your shader :

shader_type canvas_item;

uniform float dist;

uniform vec2 mousePos; //This variable is filled from another GDScript
uniform float lightRadius = 10.0;

void fragment() {
    // Called for every pixel the material is visible on.
    //COLOR = vec4(sin(UV.x), cos(UV.y), 0.0, 1.0);
    COLOR = texture(TEXTURE, UV);
    dist = distance(mousePos, FRAGCOORD.xy);
    COLOR.a = dist;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.