Created
April 16, 2015 18:51
-
-
Save kived/65d2aebd8d5fa0943be3 to your computer and use it in GitHub Desktop.
Kivy: glsl function plot test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kivy | |
kivy.require('1.9.0') | |
from kivy.app import App | |
from kivy.uix.effectwidget import EffectWidget, AdvancedEffectBase | |
effect_plot = ''' | |
uniform float scale_x, scale_y; | |
uniform float center_x, center_y; | |
uniform int t; | |
uniform vec4 line_color, above_color, below_color, grid_color; | |
uniform float line_thickness, grid_thickness; | |
float plot_fn(float x) { | |
if (t == 0) { | |
return x; | |
} else if (t == 1) { | |
return pow(x, 2); | |
} else if (t == 2) { | |
return pow(x, 2.0) + x - 1.0; | |
} else { | |
return sin(x); | |
} | |
} | |
vec4 effect(vec4 color, sampler2D texture, vec2 tex_coords, vec2 coords) { | |
vec4 out_color; | |
float value = plot_fn((coords.x - center_x) * scale_x); | |
float y_comp = (value * scale_y) + center_y; | |
float lthick = line_thickness / 2.0; | |
float gthick = grid_thickness / 2.0; | |
if (coords.y > y_comp + lthick) { | |
out_color = above_color; | |
} else if (coords.y < y_comp - lthick) { | |
out_color = below_color; | |
} else { | |
out_color = line_color; | |
} | |
if ((coords.y > center_y - gthick && coords.y < center_y + gthick) | |
|| (coords.x > center_x - gthick && coords.x < center_x + gthick)) { | |
out_color = mix(out_color, grid_color, grid_color.a); | |
} | |
return out_color; | |
} | |
''' | |
class PlotEffect(AdvancedEffectBase): | |
def __init__(self, *args, **kwargs): | |
super(PlotEffect, self).__init__(*args, **kwargs) | |
self.glsl = effect_plot | |
class Plot(EffectWidget): | |
def __init__(self, **kwargs): | |
self.plot_effect = PlotEffect(uniforms={ | |
'scale_x': 0.05, | |
'scale_y': 10.0, | |
'center_x': 0.0, | |
'center_y': 0.0, | |
'line_color': (1.0, 0.0, 0.0, 1.0), | |
'above_color': (0.0, 0.5, 0.0, 1.0), | |
'below_color': (0.0, 0.0, 0.5, 1.0), | |
'grid_color': (1.0, 1.0, 1.0, 0.5), | |
'line_thickness': 4.0, | |
'grid_thickness': 2.0, | |
't': 0, | |
}) | |
super(Plot, self).__init__(**kwargs) | |
self.effects = [self.plot_effect] | |
def _update_glsl(self, *args): | |
super(Plot, self)._update_glsl() | |
self.plot_effect.uniforms['t'] = int(self.canvas['time']) % 4 | |
def on_size(self, *args): | |
self.plot_effect.uniforms['center_x'] = self.center_x | |
self.plot_effect.uniforms['center_y'] = self.center_y | |
class TestApp(App): | |
def build(self): | |
return Plot() | |
if __name__ == '__main__': | |
TestApp().run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment