'use strict'

modules['insideCylinder'] = {
    config: [
        ['texture', 'texture', 'default'],
        ['brightness', 'float', 1],
        ['textureRepeats', 'float', 8],
        ['textureScale', 'float', 1],
    ],

    render: async (time, self, config) => {
        const {
            texture,
            brightness,
            textureRepeats,
            textureScale
        } = { ...config }
        const texSize = texture.size
        const texData = texture.data

        const texScale = Math.abs(textureRepeats * 0.5 * texSize) * textureScale

        const iHalfWidth = 1 / 240*10
        const iHalfHeight = 1 / 320*10
        const greyscaleBuffer = greyscaleBuffers[getOutputBufferId()]
        const mat = JSON.parse(JSON.stringify(camViewPersp))
        mat[12]=mat[13]=mat[14]=0
        mat[15]=1
        const right = [mat[0], mat[4], mat[8]]
        const up = [mat[1], mat[5], mat[9]]
        const fwd = [mat[2]*15.5, mat[6]*15.5, mat[10]*15.5]
        let index = 0
        for (let y = 0; y < 480; ++y) {
            for (let x = 0; x < 640; x+=2) {
                let direction = [(x - 320) * iHalfWidth, (y - 240 ) * iHalfHeight, -1.0, 0.0]
                //direction = m4.transformVector(mat, direction)
                //const xd = Math.sqrt(direction[0]*direction[0] + direction[2]*direction[2])
                const ray = m4.normalize([
                    fwd[0] + direction[0]*right[0] + direction[1]*up[0],
                    fwd[1] + direction[0]*right[1] + direction[1]*up[1],
                    fwd[2] + direction[0]*right[2] + direction[1]*up[2],
                ])

                const tu = Math.floor(Math.abs(Math.tan(ray[1])*texScale*.25)) % texSize
                const tv = Math.floor(Math.abs(Math.atan2(ray[0], ray[2]) / Math.PI) * texScale) % texSize
                const value = texData[tu + tv*texSize]
                
                greyscaleBuffer[index++] += value * brightness
                greyscaleBuffer[index++] += value * brightness
            }
        }
    }
}
