'use strict'

modules['tendrils'] = {
    config: [
        ['texture', 'string', 'default'],
        ['brightness', 'float', 1],
        ['size', 'float', 1],
        ['pulsePosition', 'float', 1],
        ['pulseSize', 'float', 1],
    ],

    init: () => {
        const tendrils3D = []
        const tendrilRng = new Math.seedrandom('tendril')
        for (let tendril = 0; tendril < 50; ++tendril) {
            let pos = [0, 0, 0]
            let dir = randomNormal(tendrilRng)
            let startDistance = tendrilRng() * 20
            pos[0] += dir[0] * startDistance
            pos[1] += dir[1] * startDistance
            pos[2] += dir[2] * startDistance
            let tendrilLength = tendrilRng() * 20 + 90
            for (let i = 0; i < tendrilLength; ++i) {
                const a = 1 - (i / tendrilLength)
                const as = Math.sqrt(a)
                tendrils3D.push([[pos[0], pos[1], pos[2], 1], as*1+0.5, as*1.5+1, a * 2 * Math.PI])
                pos[0] += dir[0] * 1
                pos[1] += dir[1] * 1
                pos[2] += dir[2] * 1
    
                let dirMod = randomNormal(tendrilRng)
                dir[0] += dirMod[0] * 0.4 * as
                dir[1] += dirMod[1] * 0.4 * as
                dir[2] += dirMod[2] * 0.4 * as
                dir = m4.normalize(dir)
            }
        }
        return {
            tendrils3D
        }
    },

    render: async (time, self, config) => {
        const {
            texture,
            brightness,
            size,
            pulsePosition,
            pulseSize,
        } = { ...config }

        const balls2d = transformBalls(self.tendrils3D.map(x => {
            x = x.slice()
            x[1] *= brightness
            const pulseMod = Math.abs(Math.sin(x[3] + pulsePosition))
            x[2] = x[2] * (size + pulseSize * pulseMod*pulseMod)
            return x
        }))
        drawBalls(balls2d, texture)
    }
}
