Tree Shader

by roomyrooms

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.2.2/pixi.min.js"></script>
<script type="x-data-url" id="tree-url">
 ...

JavaScript

var treeUrl = document.getElementById('tree-url').textContent;
var treeImg = document.getElementById('tree-preview');

treeImg.src = treeUrl;

var vertexShader = `
attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;
attribute vec4 aColor;

uniform mat3 projectionMatrix;

varying vec2 vTextureCoord;

void main(void){
  gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);
  vTextureCoord = aTextureCoord;
}`

var fragmentShader = `
precision mediump float;

varying vec2 vTextureCoord;

uniform sampler2D uSampler;
uniform vec4 filterClamp;

uniform float uWaveStrength;
uniform float uWaveHeight;

uniform float time;

void main() {
  vec2 offset = vec2(sin(time * 0.02) * uWaveStrength * smoothstep(uWaveHeight, 0.0, vTextureCoord.y), 0.0);
    
  vec2 coord = vTextureCoord + offset;
  vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);
  
  vec4 color = texture2D(uSampler, clampedCoord);
  gl_FragColor = color;
}`

function defaultValue(inputValue, defaultValue) {
    inputValue = typeof inputValue !== 'undefined' ? inputValue : defaultValue;
    return inputValue;
}


function TreeHitFilter(waveStrength, waveHeight) {
    PIXI.Filter.call(this,vertexShader,fragmentShader);
        
    //this.lightSprite = lightSprite;
    //this.lightMatrix = new PIXI.Matrix();

    this.uniforms.uWaveStrength = defaultValue(waveStrength, 1.0);
    this.uniforms.uWaveHeight = defaultValue(waveHeight, 1.0);
    this.uniforms.time = performance.now();
}

TreeHitFilter.prototype = Object.create(PIXI.Filter.prototype);
TreeHitFilter.prototype.constructor = TreeHitFilter;

TreeHitFilter.prototype.apply = function (filterManager, input, output) {
    //this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.lightMatrix, this.lightSprite);

		this.padding = 5;
    this.uniforms.time = performance.now();
    // draw the filter...
    filterManager.applyFilter(this, input, output);
}

var stage = new PIXI.Container();

//...