'use strict'

modules['brightSpot'] = {
    config: [
        ['brightness', 'float', 1],
        ['spotRange', 'float', 1],
        ['offset', 'float2', [0, 0]],
        ['noiseGridSize', 'int', 80],
        ['noiseScale', 'float', 0.1],
        ['noiseStrength', 'float', 0],
        ['noisePosition', 'float', 0],
    ],

    render: async (time, self, config) => {
        const {
            brightness,
            spotRange,
            offset,
            noiseGridSize,
            noiseScale,
            noiseStrength,
            noisePosition,
        } = { ...config }

        const greyscaleBuffer = greyscaleBuffers[getOutputBufferId()]
        let index = 0
        const iHalfHeight = 1 / 320
        const iNoiseGridSize = 1 / noiseGridSize
        let noiseValue = 0
        for (var y = 0; y < 480; ++y) {
            const vy = (y - 240) * iHalfHeight + offset[1]
            const vys = vy*vy
            for (var x = 0; x < 640; ++x) {
                const vx = (x - 320) * iHalfHeight - offset[0]
                const vxs = vx*vx
                const v = 1 - Math.sqrt(vxs + vys) * spotRange

                if ((x % noiseGridSize) === 0) {
                    noiseValue = noise.simplex3(Math.floor(x*iNoiseGridSize)*noiseScale, Math.floor(y*iNoiseGridSize)*noiseScale, noisePosition) * noiseStrength
                }

                const value = Math.max(v*v*v + noiseValue, 0)
                greyscaleBuffer[index++] = Math.sin(value) * brightness
            }
        }
    }
}

