"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _dataColumn = _interopRequireDefault(require("./data-column"));

var _assert = _interopRequireDefault(require("../../utils/assert"));

var _iterableUtils = require("../../utils/iterable-utils");

var _flatten = require("../../utils/flatten");

var range = _interopRequireWildcard(require("../../utils/range"));

var _glUtils = require("./gl-utils");

var _attributeTransitionUtils = require("./attribute-transition-utils");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(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; }

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, 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 normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var Attribute = function (_DataColumn) {
  (0, _inherits2.default)(Attribute, _DataColumn);

  var _super = _createSuper(Attribute);

  function Attribute(device, opts) {
    var _this;

    (0, _classCallCheck2.default)(this, Attribute);
    _this = _super.call(this, device, opts, {
      startIndices: null,
      lastExternalBuffer: null,
      binaryValue: null,
      binaryAccessor: null,
      needsUpdate: true,
      needsRedraw: false,
      layoutChanged: false,
      updateRanges: range.FULL
    });
    _this.constant = false;
    _this.settings.update = opts.update || (opts.accessor ? _this._autoUpdater : undefined);
    Object.seal(_this.settings);
    Object.seal(_this.state);

    _this._validateAttributeUpdaters();

    return _this;
  }

  var _proto = Attribute.prototype;

  _proto.needsUpdate = function needsUpdate() {
    return this.state.needsUpdate;
  };

  _proto.needsRedraw = function needsRedraw() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$clearChangedFlag = _ref.clearChangedFlags,
        clearChangedFlags = _ref$clearChangedFlag === void 0 ? false : _ref$clearChangedFlag;

    var needsRedraw = this.state.needsRedraw;
    this.state.needsRedraw = needsRedraw && !clearChangedFlags;
    return needsRedraw;
  };

  _proto.layoutChanged = function layoutChanged() {
    return this.state.layoutChanged;
  };

  _proto.setAccessor = function setAccessor(accessor) {
    var _this$state;

    (_this$state = this.state).layoutChanged || (_this$state.layoutChanged = !(0, _glUtils.bufferLayoutEqual)(accessor, this.getAccessor()));
    (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "setAccessor", this).call(this, accessor);
  };

  _proto.getUpdateTriggers = function getUpdateTriggers() {
    var accessor = this.settings.accessor;
    return [this.id].concat(typeof accessor !== 'function' && accessor || []);
  };

  _proto.supportsTransition = function supportsTransition() {
    return Boolean(this.settings.transition);
  };

  _proto.getTransitionSetting = function getTransitionSetting(opts) {
    if (!opts || !this.supportsTransition()) {
      return null;
    }

    var accessor = this.settings.accessor;
    var layerSettings = this.settings.transition;
    var userSettings = Array.isArray(accessor) ? opts[accessor.find(function (a) {
      return opts[a];
    })] : opts[accessor];
    return (0, _attributeTransitionUtils.normalizeTransitionSettings)(userSettings, layerSettings);
  };

  _proto.setNeedsUpdate = function setNeedsUpdate() {
    var reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.id;
    var dataRange = arguments.length > 1 ? arguments[1] : undefined;
    this.state.needsUpdate = this.state.needsUpdate || reason;
    this.setNeedsRedraw(reason);

    if (dataRange) {
      var _dataRange$startRow = dataRange.startRow,
          startRow = _dataRange$startRow === void 0 ? 0 : _dataRange$startRow,
          _dataRange$endRow = dataRange.endRow,
          endRow = _dataRange$endRow === void 0 ? Infinity : _dataRange$endRow;
      this.state.updateRanges = range.add(this.state.updateRanges, [startRow, endRow]);
    } else {
      this.state.updateRanges = range.FULL;
    }
  };

  _proto.clearNeedsUpdate = function clearNeedsUpdate() {
    this.state.needsUpdate = false;
    this.state.updateRanges = range.EMPTY;
  };

  _proto.setNeedsRedraw = function setNeedsRedraw() {
    var reason = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.id;
    this.state.needsRedraw = this.state.needsRedraw || reason;
  };

  _proto.allocate = function allocate(numInstances) {
    var state = this.state,
        settings = this.settings;

    if (settings.noAlloc) {
      return false;
    }

    if (settings.update) {
      (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "allocate", this).call(this, numInstances, state.updateRanges !== range.FULL);
      return true;
    }

    return false;
  };

  _proto.updateBuffer = function updateBuffer(_ref2) {
    var numInstances = _ref2.numInstances,
        data = _ref2.data,
        props = _ref2.props,
        context = _ref2.context;

    if (!this.needsUpdate()) {
      return false;
    }

    var updateRanges = this.state.updateRanges,
        _this$settings = this.settings,
        update = _this$settings.update,
        noAlloc = _this$settings.noAlloc;
    var updated = true;

    if (update) {
      var _iterator = _createForOfIteratorHelper(updateRanges),
          _step;

      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var _step$value = (0, _slicedToArray2.default)(_step.value, 2),
              _startRow = _step$value[0],
              _endRow = _step$value[1];

          update.call(context, this, {
            data: data,
            startRow: _startRow,
            endRow: _endRow,
            props: props,
            numInstances: numInstances
          });
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }

      if (!this.value) {} else if (this.constant || this.buffer.byteLength < this.value.byteLength + this.byteOffset) {
        this.setData({
          value: this.value,
          constant: this.constant
        });
        this.constant = false;
      } else {
        var _iterator2 = _createForOfIteratorHelper(updateRanges),
            _step2;

        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var _step2$value = (0, _slicedToArray2.default)(_step2.value, 2),
                startRow = _step2$value[0],
                endRow = _step2$value[1];

            var startOffset = Number.isFinite(startRow) ? this.getVertexOffset(startRow) : 0;
            var endOffset = Number.isFinite(endRow) ? this.getVertexOffset(endRow) : noAlloc || !Number.isFinite(numInstances) ? this.value.length : numInstances * this.size;
            (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "updateSubBuffer", this).call(this, {
              startOffset: startOffset,
              endOffset: endOffset
            });
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }

      this._checkAttributeArray();
    } else {
      updated = false;
    }

    this.clearNeedsUpdate();
    this.setNeedsRedraw();
    return updated;
  };

  _proto.setConstantValue = function setConstantValue(value) {
    if (value === undefined || typeof value === 'function') {
      return false;
    }

    var hasChanged = this.setData({
      constant: true,
      value: value
    });

    if (hasChanged) {
      this.setNeedsRedraw();
    }

    this.clearNeedsUpdate();
    return true;
  };

  _proto.setExternalBuffer = function setExternalBuffer(buffer) {
    var state = this.state;

    if (!buffer) {
      state.lastExternalBuffer = null;
      return false;
    }

    this.clearNeedsUpdate();

    if (state.lastExternalBuffer === buffer) {
      return true;
    }

    state.lastExternalBuffer = buffer;
    this.setNeedsRedraw();
    this.setData(buffer);
    return true;
  };

  _proto.setBinaryValue = function setBinaryValue(buffer) {
    var startIndices = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var state = this.state,
        settings = this.settings;

    if (!buffer) {
      state.binaryValue = null;
      state.binaryAccessor = null;
      return false;
    }

    if (settings.noAlloc) {
      return false;
    }

    if (state.binaryValue === buffer) {
      this.clearNeedsUpdate();
      return true;
    }

    state.binaryValue = buffer;
    this.setNeedsRedraw();
    var needsUpdate = settings.transform || startIndices !== this.startIndices;

    if (needsUpdate) {
      if (ArrayBuffer.isView(buffer)) {
        buffer = {
          value: buffer
        };
      }

      var binaryValue = buffer;
      (0, _assert.default)(ArrayBuffer.isView(binaryValue.value), "invalid ".concat(settings.accessor));
      var needsNormalize = Boolean(binaryValue.size) && binaryValue.size !== this.size;
      state.binaryAccessor = (0, _iterableUtils.getAccessorFromBuffer)(binaryValue.value, {
        size: binaryValue.size || this.size,
        stride: binaryValue.stride,
        offset: binaryValue.offset,
        startIndices: startIndices,
        nested: needsNormalize
      });
      return false;
    }

    this.clearNeedsUpdate();
    this.setData(buffer);
    return true;
  };

  _proto.getVertexOffset = function getVertexOffset(row) {
    var startIndices = this.startIndices;
    var vertexIndex = startIndices ? row < startIndices.length ? startIndices[row] : this.numInstances : row;
    return vertexIndex * this.size;
  };

  _proto.getValue = function getValue() {
    var shaderAttributeDefs = this.settings.shaderAttributes;
    var result = (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "getValue", this).call(this);

    if (!shaderAttributeDefs) {
      return result;
    }

    for (var shaderAttributeName in shaderAttributeDefs) {
      Object.assign(result, (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "getValue", this).call(this, shaderAttributeName, shaderAttributeDefs[shaderAttributeName]));
    }

    return result;
  };

  _proto.getBufferLayout = function getBufferLayout() {
    this.state.layoutChanged = false;
    var shaderAttributeDefs = this.settings.shaderAttributes;
    var result = (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "getBufferLayout", this).call(this);

    if (!shaderAttributeDefs) {
      return result;
    }

    for (var shaderAttributeName in shaderAttributeDefs) {
      var _result$attributes;

      var map = (0, _get2.default)((0, _getPrototypeOf2.default)(Attribute.prototype), "getBufferLayout", this).call(this, shaderAttributeName, shaderAttributeDefs[shaderAttributeName]);

      (_result$attributes = result.attributes).push.apply(_result$attributes, (0, _toConsumableArray2.default)(map.attributes));
    }

    return result;
  };

  _proto._autoUpdater = function _autoUpdater(attribute, _ref3) {
    var data = _ref3.data,
        startRow = _ref3.startRow,
        endRow = _ref3.endRow,
        props = _ref3.props,
        numInstances = _ref3.numInstances;

    if (attribute.constant) {
      return;
    }

    var settings = attribute.settings,
        state = attribute.state,
        value = attribute.value,
        size = attribute.size,
        startIndices = attribute.startIndices;
    var accessor = settings.accessor,
        transform = settings.transform;
    var accessorFunc = state.binaryAccessor || (typeof accessor === 'function' ? accessor : props[accessor]);
    (0, _assert.default)(typeof accessorFunc === 'function', "accessor \"".concat(accessor, "\" is not a function"));
    var i = attribute.getVertexOffset(startRow);

    var _createIterable = (0, _iterableUtils.createIterable)(data, startRow, endRow),
        iterable = _createIterable.iterable,
        objectInfo = _createIterable.objectInfo;

    var _iterator3 = _createForOfIteratorHelper(iterable),
        _step3;

    try {
      for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
        var _object = _step3.value;
        objectInfo.index++;
        var objectValue = accessorFunc(_object, objectInfo);

        if (transform) {
          objectValue = transform.call(this, objectValue);
        }

        if (startIndices) {
          var numVertices = (objectInfo.index < startIndices.length - 1 ? startIndices[objectInfo.index + 1] : numInstances) - startIndices[objectInfo.index];

          if (objectValue && Array.isArray(objectValue[0])) {
            var startIndex = i;

            var _iterator4 = _createForOfIteratorHelper(objectValue),
                _step4;

            try {
              for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
                var item = _step4.value;

                attribute._normalizeValue(item, value, startIndex);

                startIndex += size;
              }
            } catch (err) {
              _iterator4.e(err);
            } finally {
              _iterator4.f();
            }
          } else if (objectValue && objectValue.length > size) {
            value.set(objectValue, i);
          } else {
            attribute._normalizeValue(objectValue, objectInfo.target, 0);

            (0, _flatten.fillArray)({
              target: value,
              source: objectInfo.target,
              start: i,
              count: numVertices
            });
          }

          i += numVertices * size;
        } else {
          attribute._normalizeValue(objectValue, value, i);

          i += size;
        }
      }
    } catch (err) {
      _iterator3.e(err);
    } finally {
      _iterator3.f();
    }
  };

  _proto._validateAttributeUpdaters = function _validateAttributeUpdaters() {
    var settings = this.settings;
    var hasUpdater = settings.noAlloc || typeof settings.update === 'function';

    if (!hasUpdater) {
      throw new Error("Attribute ".concat(this.id, " missing update or accessor"));
    }
  };

  _proto._checkAttributeArray = function _checkAttributeArray() {
    var value = this.value;
    var limit = Math.min(4, this.size);

    if (value && value.length >= limit) {
      var valid = true;

      switch (limit) {
        case 4:
          valid = valid && Number.isFinite(value[3]);

        case 3:
          valid = valid && Number.isFinite(value[2]);

        case 2:
          valid = valid && Number.isFinite(value[1]);

        case 1:
          valid = valid && Number.isFinite(value[0]);
          break;

        default:
          valid = false;
      }

      if (!valid) {
        throw new Error("Illegal attribute generated for ".concat(this.id));
      }
    }
  };

  (0, _createClass2.default)(Attribute, [{
    key: "startIndices",
    get: function get() {
      return this.state.startIndices;
    },
    set: function set(layout) {
      this.state.startIndices = layout;
    }
  }]);
  return Attribute;
}(_dataColumn.default);

exports.default = Attribute;
//# sourceMappingURL=attribute.js.map