import { Vector } from "../../Math/Vector";
var vertexI = Vector.CreateVec3();
var vertexJ = Vector.CreateVec3();
var vertexK = Vector.CreateVec3();
var iXj = Vector.CreateVec3();
var jXk = Vector.CreateVec3();
var kXi = Vector.CreateVec3();
/**
 * calculate nearness weighting of a vertex towards a bunch of triangles
 * @param vertex
 * @param boundaryVertex
 * @param triangles
 */
export var getCoordinate = function (vertex, boundaryVertex, triangles) {
    var wI = 0;
    for (var j = 0, triLen = triangles.length; j < triLen; j++) {
        // const add2 = getPiFactor(vertex, triangles[j]);
        var add = getPiFactor(vertex, triangles[j][0], triangles[j][1], triangles[j][2]);
        // if (Math.abs(add - add2) > 1e-8) {
        // 	console.log("nonononon " + (add - add2));
        // }
        wI += add;
    }
    return wI / Vector.Distance3(vertex, boundaryVertex);
};
export var getPiFactor = function (v, T0, T1, T2) {
    // vertexI = Vector.normalize3(Vector.sub3(triangle[0], v));
    var vtxI = vertexI;
    vtxI.x = T0.x - v.x;
    vtxI.y = T0.y - v.y;
    vtxI.z = T0.z - v.z;
    var tILength = 1 / Vector.Magnitude3(vtxI);
    vtxI.x *= tILength;
    vtxI.y *= tILength;
    vtxI.z *= tILength;
    // vertexJ = Vector.normalize3(Vector.sub3(triangle[1], v));
    var vtxJ = vertexJ;
    vtxJ.x = T1.x - v.x;
    vtxJ.y = T1.y - v.y;
    vtxJ.z = T1.z - v.z;
    var tJLength = 1 / Vector.Magnitude3(vtxJ);
    vtxJ.x *= tJLength;
    vtxJ.y *= tJLength;
    vtxJ.z *= tJLength;
    // vertexK = Vector.normalize3(Vector.sub3(triangle[2], v));
    var vtxK = vertexK;
    vtxK.x = T2.x - v.x;
    vtxK.y = T2.y - v.y;
    vtxK.z = T2.z - v.z;
    var tKLength = 1 / Vector.Magnitude3(vtxK);
    vtxK.x *= tKLength;
    vtxK.y *= tKLength;
    vtxK.z *= tKLength;
    var angleJK = angleBetweenVectors(vtxJ, vtxK);
    var angleIJ = angleBetweenVectors(vtxI, vtxJ);
    var angleKI = angleBetweenVectors(vtxK, vtxI);
    crossToRef(vtxI, vtxJ, iXj);
    crossToRef(vtxJ, vtxK, jXk);
    crossToRef(vtxK, vtxI, kXi);
    jXk = Vector.Normalize3(jXk);
    var addJK = angleJK;
    var addIJ = (dot(iXj, jXk) * angleIJ) / Vector.Magnitude3(iXj);
    var addKI = (dot(kXi, jXk) * angleKI) / Vector.Magnitude3(kXi);
    var divAll = dot(vtxI, jXk) * 2;
    var result = (addJK + addIJ + addKI) / divAll;
    return result;
};
export var crossToRef = function (vecA, vecB, out) {
    out.x = vecA.y * vecB.z - vecA.z * vecB.y;
    out.y = vecA.z * vecB.x - vecA.x * vecB.z;
    out.z = vecA.x * vecB.y - vecA.y * vecB.x;
};
export var dot = function (vecA, vecB) {
    return vecA.x * vecB.x + vecA.y * vecB.y + vecA.z * vecB.z;
};
export var angleBetweenVectors = function (v, w) {
    var dotVW = v.x * w.x + v.y * w.y + v.z * w.z;
    if (dotVW <= -1) {
        return Math.PI;
    }
    else if (dotVW >= 1) {
        return 0;
    }
    return Math.acos(dotVW);
};
