"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = newTileGeometry;
var THREE = _interopRequireWildcard(require("three"));
var _TileGeometry = _interopRequireDefault(require("../TileGeometry"));
var _Cache = _interopRequireDefault(require("../Scheduler/Cache"));
var _computeBufferTileGeometry = _interopRequireDefault(require("./computeBufferTileGeometry"));
var _OBB = _interopRequireDefault(require("../../Renderer/OBB"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const cacheBuffer = new Map();
const cacheTile = new _Cache.default();
function newTileGeometry(builder, params) {
  const {
    sharableExtent,
    quaternion,
    position
  } = builder.computeSharableExtent(params.extent);
  const south = sharableExtent.south.toFixed(6);
  const bufferKey = `${builder.crs}_${params.disableSkirt ? 0 : 1}_${params.segment}`;
  let promiseGeometry = cacheTile.get(south, params.level, bufferKey);

  // build geometry if doesn't exist
  if (!promiseGeometry) {
    let resolve;
    promiseGeometry = new Promise(r => {
      resolve = r;
    });
    cacheTile.set(promiseGeometry, south, params.level, bufferKey);
    params.extent = sharableExtent;
    params.center = builder.center(params.extent).clone();
    // Read previously cached values (index and uv.wgs84 only depend on the # of triangles)
    let cachedBuffers = cacheBuffer.get(bufferKey);
    params.buildIndexAndUv_0 = !cachedBuffers;
    params.builder = builder;
    let buffers;
    try {
      buffers = (0, _computeBufferTileGeometry.default)(params);
    } catch (e) {
      return Promise.reject(e);
    }
    if (!cachedBuffers) {
      cachedBuffers = {};
      cachedBuffers.index = new THREE.BufferAttribute(buffers.index, 1);
      cachedBuffers.uv = new THREE.BufferAttribute(buffers.uvs[0], 2);

      // Update cacheBuffer
      cacheBuffer.set(bufferKey, cachedBuffers);
    }
    buffers.index = cachedBuffers.index;
    buffers.uvs[0] = cachedBuffers.uv;
    buffers.position = new THREE.BufferAttribute(buffers.position, 3);
    buffers.normal = new THREE.BufferAttribute(buffers.normal, 3);
    if (params.builder.uvCount > 1) {
      buffers.uvs[1] = new THREE.BufferAttribute(buffers.uvs[1], 1);
    }
    const geometry = new _TileGeometry.default(params, buffers);
    geometry.OBB = new _OBB.default(geometry.boundingBox.min, geometry.boundingBox.max);
    geometry._count = 0;
    geometry.dispose = () => {
      geometry._count--;
      if (geometry._count <= 0) {
        // To avoid remove index buffer and attribute buffer uv_0
        //  error un-bound buffer in webgl with VAO rendering.
        // Could be removed if the attribute buffer deleting is
        //  taken into account in the buffer binding state (in THREE.WebGLBindingStates code).
        geometry.index = null;
        delete geometry.attributes.uv_0;
        THREE.BufferGeometry.prototype.dispose.call(geometry);
        cacheTile.delete(south, params.level, bufferKey);
      }
    };
    resolve(geometry);
    return Promise.resolve({
      geometry,
      quaternion,
      position
    });
  }
  return promiseGeometry.then(geometry => ({
    geometry,
    quaternion,
    position
  }));
}