'use strict'

modules['modelCam'] = {
    config: [
        ['model', 'model', ''],
        ['upVector', 'float3', [0, 1, 0]],
        ['fromPosition', 'float', 0],
        ['fromPathObjectName', 'string', ''],
        ['fromPathSubObjectIndex', 'int', 0],
        ['toPosition', 'float', 0],
        ['toPathObjectName', 'string', ''],
        ['toPathSubObjectIndex', 'int', 0],
        ['yaw', 'angle', 0],
        ['pitch', 'angle', 0],
        ['roll', 'angle', 0],
        ['fov', 'angle', 90],
    ],

    render: async (time, self, config) => {
        const {
            model,
            upVector,
            fromPosition,
            fromPathObjectName,
            fromPathSubObjectIndex,
            toPosition,
            toPathObjectName,
            toPathSubObjectIndex,
            yaw,
            pitch,
            roll,
            fov,
        } = { ...config }
  
        const getPointFromPath = (objectName, subObjectIndex, t) => {
            const object = model.objects.find(x => x.name === objectName)
            const subObject = object.subObjects[subObjectIndex]
            const segmentCount = subObject.lines.length
            t *= segmentCount
            const segmentIndex = Math.floor(t) % segmentCount
            const segment = subObject.lines[segmentIndex]
            const segmentAlpha = t % 1
            const p0 = model.verts[segment[0]]
            const p1 = model.verts[segment[1]]
            return m4.lerpVectors(p0, p1, segmentAlpha)
        }

        const from = getPointFromPath(fromPathObjectName, fromPathSubObjectIndex, fromPosition)
        const to = getPointFromPath(toPathObjectName, toPathSubObjectIndex, toPosition)
        const camera = m4.lookAt(from, to, m4.normalize(upVector))
        const yawMat = m4.yRotation(yaw)
        const pitchMat = m4.xRotation(pitch)
        const rollMat = m4.zRotation(roll)
        const view = m4.multiply(m4.multiply(m4.multiply(rollMat, pitchMat), yawMat), m4.inverse(camera))
        const perspective = m4.perspective(fov, 640/480, 1, 500)
        camViewPersp = m4.multiply(perspective, view)
    }
}
