"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _cesium = require("cesium");
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
 * @class
 * @description 3dtiles 模型按照(经纬度二维)范围裁剪
 */
var Clipping = /*#__PURE__*/function () {
  function Clipping(tileset, opt) {
    _classCallCheck(this, Clipping);
    if (!tileset) {
      throw new Error("参数错误！");
    }
    console.log("polygons:", opt.polygons);
    if (opt.polygons && opt.polygons instanceof Array && opt.polygons.length > 0) {
      var _iterator = _createForOfIteratorHelper(opt.polygons),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var polygon = _step.value;
          if (!(polygon instanceof Array && polygon.length >= 3)) {
            throw new Error("参数错误！");
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    } else {
      throw new Error("参数错误！");
    }
    this.tileset = tileset;
    if (typeof opt.excavate === "boolean") {
      this.excavate = opt.excavate;
    } else {
      this.excavate = false;
    }
    this.polygons = opt.polygons;
    this.center = tileset.boundingSphere.center.clone();
    this.matrix = _cesium.Transforms.eastNorthUpToFixedFrame(this.center.clone());
    this.localMatrix = _cesium.Matrix4.inverse(this.matrix, new _cesium.Matrix4());
    this.localPositionsArr = [];
    for (var pp = 0; pp < this.polygons.length; pp++) {
      var positions = this.polygons[pp];
      var localCoor = this.cartesiansToLocal(positions);
      this.localPositionsArr.push(localCoor);
    }
    this.initialize();
  }
  return _createClass(Clipping, [{
    key: "initialize",
    value: function initialize() {
      var out_v_str = "";
      var in_v_str = "";
      var temp_str = "";
      for (var m = 0; m < this.localPositionsArr.length; m++) {
        var polygon = this.localPositionsArr[m];
        out_v_str += "vec2 points_".concat(m, "[").concat(polygon.length, "];\n              bool isPointInPolygon_").concat(m, "(vec2 point){\n                int nCross = 0; // \u4EA4\u70B9\u6570\n                const int n = ").concat(polygon.length, ";\n                for(int i = 0; i < n; i++){\n                    vec2 p1 = points_").concat(m, "[i];\n                    vec2 p2 = points_").concat(m, "[int(mod(float(i+1),float(n)))];\n                    if(p1[1] == p2[1]){\n                        continue;\n                    }\n                    if(point[1] < min(p1[1], p2[1])){\n                        continue;\n                    }\n                    if(point[1] >= max(p1[1], p2[1])){\n                        continue;\n                    }\n                    float x = p1[0] + ((point[1] - p1[1]) * (p2[0] - p1[0])) / (p2[1] - p1[1]);\n                    if(x > point[0]){\n                    nCross++;\n                    }\n                }\n                return int(mod(float(nCross), float(2))) == 1;\n              }\n\n        ");
        for (var n = 0; n < polygon.length; n++) {
          in_v_str += "points_".concat(m, "[").concat(n, "] = vec2(").concat(polygon[n][0], ", ").concat(polygon[n][1], ");\n");
        }
        temp_str += "isPointInPolygon_".concat(m, "(position2D)||");
      }
      temp_str = temp_str.slice(0, -2);
      if (this.excavate == false) {
        in_v_str += "\n            if(".concat(temp_str, "){\n            }else{\n              vsOutput.positionMC *= 0.0;\n            }\n        ");
      } else if (this.excavate == true) {
        in_v_str += "\n        if(".concat(temp_str, "){\n          vsOutput.positionMC *= 0.0;\n        }\n        ");
      }
      this.updateShader(out_v_str, in_v_str);
    }

    /**
     * 销毁
     */
  }, {
    key: "destroy",
    value: function destroy() {
      this.tileset.customShader = undefined;
    }
  }, {
    key: "updateShader",
    value: function updateShader(vtx1, vtx2) {
      var v_text = "\n            // \u6240\u6709isPointInPolygon\u51FD\u6570\n            ".concat(vtx1, "\n            void vertexMain(VertexInput vsInput, inout czm_modelVertexOutput vsOutput){\n                vec3 modelMC = vsInput.attributes.positionMC;\n                vec4 model_local_position = vec4(modelMC.x, modelMC.y, modelMC.z, 1.0);\n                vec4 tileset_local_position = u_tileset_worldToLocalMatrix * czm_model * model_local_position;\n                vec2 position2D = vec2(tileset_local_position.x,tileset_local_position.y);\n                // \u591A\u4E2A\u591A\u8FB9\u5F62\u533A\u57DF\n                ").concat(vtx2, "\n            }");
      var flatCustomShader = new _cesium.CustomShader({
        uniforms: {
          u_tileset_localToWorldMatrix: {
            type: _cesium.UniformType.MAT4,
            value: this.matrix
          },
          u_tileset_worldToLocalMatrix: {
            type: _cesium.UniformType.MAT4,
            value: this.localMatrix
          },
          u_flatHeight: {
            type: _cesium.UniformType.FLOAT,
            value: this.flatHeight
          }
        },
        vertexShaderText: v_text
      });
      this.tileset.customShader = flatCustomShader;
    }

    // 世界坐标转数组局部坐标
  }, {
    key: "cartesiansToLocal",
    value: function cartesiansToLocal(positions) {
      var arr = [];
      for (var i = 0; i < positions.length; i++) {
        var position = positions[i];
        var localp = _cesium.Matrix4.multiplyByPoint(this.localMatrix, position.clone(), new _cesium.Cartesian3());
        arr.push([localp.x, localp.y]);
      }
      return arr;
    }
  }]);
}();
var _default = exports["default"] = Clipping;
//# sourceMappingURL=TilesetCut.js.map
