简体   繁体   中英

Passing variables to GLSL in Kivy

I am trying to do some basic 3D in Kivy, and am having trouble sending variables to the .glsl fragment shader. I've started with this example . I managed to write the movement and rotation of objects in the scene, but now I'm trying to apply custom shaders. This is vertex shader found in the example:

#ifdef GL_ES
    precision highp float;
#endif

varying vec4 normal_vec;
varying vec4 vertex_pos;
uniform mat4 normal_mat;

void main (void) {
    vec4 v_normal = normalize(normal_mat*normal_vec);
    vec4 v_light = normalize(vec4(0, 0, 0, 1)-vertex_pos);
    float theta = clamp(dot(v_normal, v_light), 0.0, 1.0);
    gl_FragColor = vec4(theta, theta, theta, 1.0);
}

I just wanted to set my own colours to the objects dynamically, but I was unable to pass colour values to the shader. Currently I'm dynamically generating .glsl files in

cache/shaders/diffuse_xxxxxx.glsl

where xxxxxx is hex value of the colour and its line

gl_FragColor = vec4(theta, theta, theta, 1.0);

is replaced with

gl_FragColor = vec4(theta*{0}, theta*{1}, theta*{2}, 1.0);

where {0}, {1}, {2} are r, g, b floats between 0 and 1. How can I pass vec4 to the fragment shader so that I don't have to do this every time my app wants to display an object with a new colour?

I found out how to do it.

To pass variable to GLSL, one just needs to add the variable as key to widget's canvas. In my case, adding a vec4 variable to fragment shader means having

self.canvas["object_colour"] = (1., )*4  # colour tuple here

in my widget's code and now I can use it like this:

#ifdef GL_ES
    precision highp float;
#endif

varying vec4 normal_vec;
varying vec4 vertex_pos;
uniform mat4 normal_mat;
uniform vec4 object_colour;

void main (void) {
    vec4 v_normal = normalize(normal_mat*normal_vec);
    vec4 v_light = normalize(vec4(0, 0, 0, 1)-vertex_pos);
    float theta = clamp(dot(v_normal, v_light), 0.0, 1.0);
    gl_FragColor = vec4(theta, theta, theta, 1.0)*object_colour;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM