Skip to content

Instantly share code, notes, and snippets.

@cidicles
Last active September 6, 2017 23:41
Show Gist options
  • Save cidicles/825471f82a42b205f2c44d8465539b3e to your computer and use it in GitHub Desktop.
Save cidicles/825471f82a42b205f2c44d8465539b3e to your computer and use it in GitHub Desktop.
Testing shaders in react VR
import React from 'react';
import {
Box
} from 'react-vr';
import * as THREE from 'three';
/**
* Testing out custom shaders.
* NOTE: This does not currently allow for the animation of uniforms. Attempted a three clock and a interval setting state.
* @module components/shaderTest
*/
class ShaderTest extends React.Component {
constructor(props) {
super();
this.clock = new THREE.Clock(1);
this.state = {
elapsed: 0
};
this.vertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
}
`;
this.fragmentShader = `
uniform vec3 colour;
uniform float rows;
uniform float glow;
uniform float glowRadius;
uniform float charDetail;
uniform float speed;
uniform float iGlobalTime;
varying vec2 vUv;
float random(in float x){
return fract(sin(x)*43758.5453);
}
float random(in vec2 st){
return fract(sin(dot(st.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
float randomChar(in vec2 outer,in vec2 inner){
float grid = charDetail;
vec2 margin = vec2(.2,.05);
float seed = 23.;
vec2 borders = step(margin,inner)*step(margin,1.-inner);
return step(.5,random(outer*seed+floor(inner*grid))) * borders.x * borders.y;
}
vec3 matrix(in vec2 st){
vec2 ipos = floor(st*rows)+vec2(1.,0.);
ipos += vec2(.0,floor(iGlobalTime*speed*random(ipos.x)));
vec2 fpos = fract(st*rows);
vec2 center = (.5-fpos);
float pct = random(ipos);
float glowamount = (glowRadius-dot(center,center)*3.)*glow;
return vec3(randomChar(ipos,fpos) * pct * glowamount) * colour;
}
void main() {
gl_FragColor = vec4(matrix(vUv),1.0);
}
`;
}
componentDidMount(){
let start = Date.now();
this.timer = setInterval(()=>{this.tick(start)}, 50);
}
componentWillUnmount(){
clearInterval(this.timer);
}
tick(start){
this.setState({elapsed: new Date() - start});
}
render(){
let elapsed = Math.round(this.state.elapsed / 100);
let seconds = (elapsed / 10).toFixed(1);
console.log(seconds);
return (
<Box
dimWidth={1}
dimHeight={1}
style={{
transform: [
{translate: [7, 0, -2]},
{rotateY: '20deg'}
],
color: '#4444ff'
}}
lit={true}
materialParameters={{
uniforms: {
'colour': { value: new THREE.Color(0xff0000) },
'rows': { value: 15 },
'glow': { value: 2 },
'glowRadius': { value: 1.6 },
'charDetail': { value: 3.4 },
'speed': { value: 100 },
'iGlobalTime': { value: seconds }
},
vertexShader: this.vertexShader,
fragmentShader: this.fragmentShader,
}}
/>
);
}
}
module.exports = ShaderTest;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment