//
// 鼠标点击绘制点.
//

Qt.include("cuon-utils.js")

var VSHADER_SOURCE = null;
var FSHADER_SOURCE = null;

var gl;
var canvas;
var a2v_Position

function main(canvas3d) {
    canvas = canvas3d;

    gl = canvas.getContext("experimental-webgl", {depth:true});
    if (!gl) {
        console.log("获取webGL渲染内容失败");
        return;
    }

    // 从文件中加载着色器
    loadShaderFile(gl, "clickedpoints.vsh", gl.VERTEX_SHADER);
    loadShaderFile(gl, "clickedpoints.fsh", gl.FRAGMENT_SHADER);
}

function start(gl) {
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log("Shader初始化失败");
        return;
    }

    // 获取attribute变量的存储位置
    a2v_Position = gl.getAttribLocation(gl.program, 'a2v_Position');

    //设置<canvas>的背景色
    gl.clearColor(0.0, 0.0, 0.0, 1.0);

    //清空<canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

}

function loadShaderFile(gl, fileName, shader) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status !== 404) {
            onLoadShader(gl, xhr.responseText, shader);
        }
    }

    xhr.open('GET', fileName, true);
    xhr.send();
}

function onLoadShader(gl, fileString, type) {
    if (type == gl.VERTEX_SHADER) { // 加载了定点着色器
        VSHADER_SOURCE = fileString;
    } else if (type == gl.FRAGMENT_SHADER) { // 加载了片元着色器
        FSHADER_SOURCE = fileString;
    }

    // 加载着色器之后，开始进行渲染
    if (VSHADER_SOURCE && FSHADER_SOURCE) start(gl);
}

var g_points = []; // 鼠标点击位置数组
function click(clientX, clientY) {
    var x = clientX; //鼠标点击处x坐标
    var y = clientY; //鼠标点击处y坐标

    x = (x - canvas.height/2) / (canvas.height/2);
    y = (canvas.width/2 - y) / (canvas.width/2);
    //将坐标存储到g_points数组中
    g_points.push(x); g_points.push(y);

    //清除<canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);

    var len = g_points.length;
    for (var i = 0; i < len; i += 2) {
        //将点的位置传递到变量a_Position中
        gl.vertexAttrib3f(a2v_Position, g_points[i], g_points[i+1], 0.0);

        //绘制点
        gl.drawArrays(gl.POINTS, 0, 1);
    }
}
