precision highp float;

uniform vec2 u_cellUVSize;
uniform vec2 u_detailAreaUVSize;
uniform vec2 u_detailAreaScale;
uniform vec2 u_detailAreaUVMul;
uniform vec2 u_detailUVSize;
uniform vec2 u_detailPixelUVSize;
uniform vec2 u_gridToDetailRatio;

uniform vec2 u_gridUVSize;

uniform float u_timeCurliness;
uniform float u_timeSpeed;
varying vec2 v_texCoord;
varying vec2 v_cellTexCoord;
#define PI2 6.28318530717959
#define PI 3.141592653589793

void main()
{
    
    vec2 snappedCellTexCoord = (floor(v_texCoord / u_cellUVSize ) + 0.5 ) * u_cellUVSize * u_gridUVSize;
    vec4 Att = texture2D(CC_Texture1, snappedCellTexCoord);
    vec4 col =texture2D(CC_Texture0, snappedCellTexCoord);
    vec4 cellAtt = texture2D(CC_Texture2, snappedCellTexCoord );
    
    vec4 finalColor = vec4(0.0);
    
    float noMask = step(0.001, cellAtt.a);          // 0 -> commonParticle
    float fullMask = 1.0 - step(0.7, cellAtt.a);    // 0 -> water
    float middleMask = noMask * fullMask;           // 1 -> foreground particle
    float mask1 = 1.0 - noMask;
    
    if (cellAtt.rg != vec2(0.0)) { //if the particle has texture index/coordinates
        
        if ( middleMask < 0.001){ //regular particle. This should skip foreground painted particles

            //common particle
            vec2 detailOffset = floor(cellAtt.rg * 255.0 + 0.5) * u_detailUVSize; //Which cell to use

            //LavaAlt
            vec2 noiseOffset = vec2(0.0,0.0);
            vec2 detailUV;
            
            if (cellAtt.b == 0.0) { //no scale
                
                vec2 cellUV = mod (v_texCoord , u_cellUVSize );
                detailUV = clamp(cellUV  * u_gridToDetailRatio, vec2(0.0) , u_detailUVSize) + detailOffset;
                
            }else { //scale
                
                float scale = cellAtt.b;
                if(Att.g > 0.1){ //lava rendering
                    float tpi2 = u_timeCurliness * PI2 ;
                    
                    noiseOffset = vec2(0.0, -u_timeSpeed * u_detailAreaScale.y * scale);
                    
                    vec2 uva = vec2(v_cellTexCoord.x, v_cellTexCoord.y);
                    noiseOffset.x += .2 * cos(10. * uva.y + tpi2 ) * u_detailAreaUVSize.x  * Att.g;
                    noiseOffset.y += .2 * sin(10. * uva.x + tpi2 ) * u_detailAreaUVSize.y * Att.g;
                }
                
                detailUV = mod(v_cellTexCoord * u_detailAreaUVMul + noiseOffset, u_detailAreaScale * scale) / (u_detailAreaScale * scale);
                detailUV = clamp(detailUV * u_detailAreaUVSize  , vec2(0.0),u_detailAreaUVSize) + detailOffset;
            }
            finalColor = texture2D(CC_Texture3, detailUV) * mask1;
        }
        
    }else {
        finalColor = col * mask1;
        
    }
    
    gl_FragColor = finalColor;
}