<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebGL Triangle Gradient Example</title>
    <script src="static/gl-matrix-min.js"></script>
    <script src="static/triangles.js"></script>
<style>
    body { margin: 0; }
    canvas { display: block; }
</style>
</head>
<body>
<canvas id="webgl-canvas" width="800" height="800"></canvas>
<script>
  
    let lastX, lastY;
    let isDragging = false;
    let panX = -0.5, panY = -0.5;
    let tiltX = 0.0, tiltY = 0.0;
    let zoom = 1.0;
    let gl, shaderProgram, numVertices;

  
    function initShaderProgram(gl, vsSource, fsSource) {
        const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
        const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

        const shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            console.error('Unable to initialize the shader program:', gl.getProgramInfoLog(shaderProgram));
        }

        return shaderProgram;
    }

    function loadShader(gl, type, source) {
        const shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            console.error('An error occurred compiling the shader:', gl.getShaderInfoLog(shader));
            gl.deleteShader(shader);
            return null;
        }

        return shader;
    }

  function initBuffers(gl) {

      var zCoordinates = Array(164).fill([0.1, 0.1, 0.1]);

      zCoordinates[14] = [0.1, 0.4, 0.1]
      zCoordinates[15] = [0.4, 0.1, 0.1]
      
      // Function to build vertices using triangles and zCoordinates
      function buildVertices(triangles, zCoordinates) {
          const vertices = [];
          
          for (let i = 0; i < triangles.length; i++) {
              const triangle = triangles[i];
              const zCoords = zCoordinates[i];
              
              for (let j = 0; j < triangle.length; j++) {
            const vertex = triangle[j];
                  const z = zCoords[j]; // Use the corresponding Z coordinate
                  
                  // Add X, Y, Z coordinates to vertices array
                  vertices.push(vertex[0], vertex[1], z);
              }
          }

    return vertices;
}

// Build vertices array
                            const vertices = buildVertices(triangles, zCoordinates);
                            
      console.log(vertices)
        // const vertices = [            
        //     0.0, 0.0, 0.0,
        //     0.0, 0.2, 0.0,
        //     0.2, 0.2, 0.5, //
            
        //     0.0, 0.0, 0.0,
        //     0.2, 0.2, 0.5, //
        //     0.2, 0.0, 0.0,
            
        //     0.2, 0.0, 0.0,
        //     0.2, 0.2, 0.5, //
        //     0.4, 0.0, 0.0,
            
        // ];

        const positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

        const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition');
        gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aPosition);

        return vertices.length / 3;
    }

  function drawScene() {

      console.log(zoom, panX, panY, tiltX, tiltY)
      
      gl.clearColor(0.0, 0.0, 0.0, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT);
      
      // Set view matrix
      const viewMatrix = mat4.create();
      ///Set up gradient based on z-axis value
      
      const colors = [
          1.0, 0.0, 0.0, ///Red for z = 0
          0.0, 1.0, 0.0, ///Green for z = 0.5
          0.0, 0.0, 1.0  ///Blue for z = 1
      ];
      
      mat4.translate(viewMatrix, viewMatrix, [panX, panY, 0]);
      mat4.rotateX(viewMatrix, viewMatrix, tiltX);
      mat4.rotateY(viewMatrix, viewMatrix, tiltY);
      mat4.scale(viewMatrix, viewMatrix, [zoom, zoom, 1]);
      
      // Set view matrix uniform
      const uViewMatrix = gl.getUniformLocation(shaderProgram, 'uViewMatrix');
      gl.uniformMatrix4fv(uViewMatrix, false, viewMatrix);      
    
      // Pass colors to the fragment shader
      const uColors = gl.getUniformLocation(shaderProgram, 'uColors');
      gl.uniform3fv(uColors, colors);
      
      // Draw triangles
    gl.drawArrays(gl.TRIANGLES, 0, numVertices);
      
  }

    function handleMouseDown(event) {
        isDragging = true;
        lastX = event.clientX;
        lastY = event.clientY;
    }

    function handleMouseUp() {
        isDragging = false;
    }

    function handleMouseMove(event) {
        if (!isDragging) return;
        const deltaX = event.clientX - lastX;
        const deltaY = event.clientY - lastY;
        lastX = event.clientX;
        lastY = event.clientY;
        tiltX += deltaY * 0.01;
        tiltY += deltaX * 0.01;
        drawScene();
    }

    function handleWheel(event) {
        zoom += event.deltaY * -0.001;
        drawScene();
    }

    const canvas = document.getElementById('webgl-canvas');
    gl = canvas.getContext('webgl');
  
    if (!gl) {
        alert('Unable to initialize WebGL. Your browser may not support it.');
    }

    const vertexShaderSource = `
        attribute vec3 aPosition;
        varying float vZValue;
        uniform mat4 uViewMatrix;

        void main() {
            gl_Position = uViewMatrix * vec4(aPosition, 1.0);
            vZValue = aPosition.z;
        }
    `;

    const fragmentShaderSource = `
        precision mediump float;
        varying float vZValue;
        uniform vec3 uColors[3];

        void main() {
            vec3 color;

            if (vZValue <= 0.5) {
                color = mix(uColors[0], uColors[1], vZValue * 2.0);
            } else {
                color = mix(uColors[1], uColors[2], (vZValue - 0.5) * 2.0);
            }

            gl_FragColor = vec4(color, 1.0);
        }
    `;
    shaderProgram = initShaderProgram(gl, vertexShaderSource, fragmentShaderSource);
    gl.useProgram(shaderProgram);

    numVertices = initBuffers(gl);
    drawScene();

    canvas.addEventListener('mousedown', handleMouseDown);
    canvas.addEventListener('mouseup', handleMouseUp);
    canvas.addEventListener('mousemove', handleMouseMove);
    canvas.addEventListener('wheel', handleWheel);
     
</script>
</body>
</html>
