import {getDisconnectedVertices} from "../geometry/Figure.js";

/**
 * Programa de sombreado para figuras 3D con un solo color.
 * @author Melissa Méndez Servín.
 */
const colorDefault = [0,0,1,1];
export default class SolidColor {
    /**
     * 
     * @param {WebGLRenderingContext} gl 
     * @param {*} WebGL 
     * @param {*} attributes 
     */
    constructor(gl, WebGL, figure, color){
        var vsh = `#version 300 es
            uniform mat4 u_PVM_matrix;
        
            in vec4 a_position;
        
            void main(){
                
                gl_Position =  u_PVM_matrix * a_position;
            }
            `;
        var fsh = `#version 300 es
            precision highp float;
            
            uniform vec4 u_color;
            
            out vec4 glColor;
            
            void main(){
                glColor = u_color;
            }
            `; 
        if (WebGL.programs["Solid3D"])
            this.program = WebGL.programs["Solid3D"];
        else
            this.program = WebGL.createProgram(gl, vsh, fsh, "Solid3D");
        
        this.vertices = (figure.byIndices || figure.getNormals) ?  figure.getVertices() : getDisconnectedVertices(figure.getVertices(), figure.getFaces());
        
        let attributes = {  position: { numComponents: 3, 
                            data: this.vertices}
                         };
        if(figure.byIndices){
            let vaoAndIndices = WebGL.setVAOAndAttributes(gl, this.program, attributes, figure.getFaces());
            this.vao = vaoAndIndices.vao;
            this.indexBuffer = vaoAndIndices.indexBuffer;
            this.numIndices = figure.numIndices;
        }else{
            this.vao = WebGL.setVAOAndAttributes(gl, this.program, attributes);  
            this.numElements = attributes.position.data.length/3;
        }
        this.setUniforms = WebGL.setUniforms(gl, this.program);
        this.uniforms = { u_color: color || colorDefault };
    }
}