import Filter from "../Filter";
import { defaultVert } from "../defaultVerts";

const extractBrightnessFrag = [
    "precision mediump float;",
    'uniform sampler2D uSampler;',
    'varying vec2 vTextureCoord;',

    'uniform float threshold;',

    'void main() {',
    'vec4 color = texture2D(uSampler, vTextureCoord);',

    // A simple & fast algorithm for getting brightness.
    // It's inaccuracy , but good enought for this feature.
    'float _max = max(max(color.r, color.g), color.b);',
    'float _min = min(min(color.r, color.g), color.b);',
    'float brightness = (_max + _min) * 0.5;',

    'if(brightness > threshold) {',
    'gl_FragColor = color;',
    '} else {',
    'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);',
    '}',
    '}'

].join("\n")
/**
 * Internal filter for AdvancedBloomFilter to get brightness.
 * @class
 * @private
 * @param {number} [threshold=0.5] Defines how bright a color needs to be extracted.
 */
export class ExtractBrightnessFilter extends Filter {

    constructor(threshold = 0.5) {
        super(defaultVert, extractBrightnessFrag);

        this.threshold = threshold;
    }

    /**
     * Defines how bright a color needs to be extracted.
     *
     * @member {number}
     * @default 0.5
     */
    get threshold() {
        return this.uniforms.threshold;
    }
    set threshold(value) {
        this.uniforms.threshold = value;
    }
}

