"use strict";

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

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

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

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

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

var _layerManager = _interopRequireDefault(require("./layer-manager"));

var _viewManager = _interopRequireDefault(require("./view-manager"));

var _mapView = _interopRequireDefault(require("../views/map-view"));

var _effectManager = _interopRequireDefault(require("./effect-manager"));

var _deckRenderer = _interopRequireDefault(require("./deck-renderer"));

var _deckPicker = _interopRequireDefault(require("./deck-picker"));

var _widgetManager = require("./widget-manager");

var _tooltip = _interopRequireDefault(require("./tooltip"));

var _log = _interopRequireDefault(require("../utils/log"));

var _deepEqual = require("../utils/deep-equal");

var _typedArrayManager = _interopRequireDefault(require("../utils/typed-array-manager"));

var _init = require("./init");

var _env = require("@probe.gl/env");

var _core = require("@luma.gl/core");

var _webgl = require("@luma.gl/webgl");

var _engine = require("@luma.gl/engine");

var _constants = require("@luma.gl/constants");

var _stats = require("@probe.gl/stats");

var _mjolnir = require("mjolnir.js");

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

var _constants2 = require("./constants");

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2.default)(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function noop() {}

var getCursor = function getCursor(_ref) {
  var isDragging = _ref.isDragging;
  return isDragging ? 'grabbing' : 'grab';
};

var defaultProps = {
  id: '',
  width: '100%',
  height: '100%',
  style: null,
  viewState: null,
  initialViewState: null,
  pickingRadius: 0,
  layerFilter: null,
  parameters: {},
  parent: null,
  device: null,
  deviceProps: {
    type: 'webgl'
  },
  gl: null,
  glOptions: {},
  canvas: null,
  layers: [],
  effects: [],
  views: null,
  controller: null,
  useDevicePixels: true,
  touchAction: 'none',
  eventRecognizerOptions: {},
  _framebuffer: null,
  _animate: false,
  _pickable: true,
  _typedArrayManagerProps: {},
  _customRender: null,
  widgets: [],
  onDeviceInitialized: noop,
  onWebGLInitialized: noop,
  onResize: noop,
  onViewStateChange: noop,
  onInteractionStateChange: noop,
  onBeforeRender: noop,
  onAfterRender: noop,
  onLoad: noop,
  onError: function onError(error) {
    return _log.default.error(error.message, error.cause)();
  },
  onHover: null,
  onClick: null,
  onDragStart: null,
  onDrag: null,
  onDragEnd: null,
  _onMetrics: null,
  getCursor: getCursor,
  getTooltip: null,
  debug: false,
  drawPickingColors: false
};

var Deck = function () {
  function Deck(props) {
    var _this = this;

    (0, _classCallCheck2.default)(this, Deck);
    this.props = void 0;
    this.width = 0;
    this.height = 0;
    this.userData = {};
    this.device = null;
    this.canvas = null;
    this.viewManager = null;
    this.layerManager = null;
    this.effectManager = null;
    this.deckRenderer = null;
    this.deckPicker = null;
    this.eventManager = null;
    this.widgetManager = null;
    this.tooltip = null;
    this.animationLoop = null;
    this.viewState = void 0;
    this.cursorState = {
      isHovering: false,
      isDragging: false
    };
    this.stats = new _stats.Stats({
      id: 'deck.gl'
    });
    this.metrics = {
      fps: 0,
      setPropsTime: 0,
      updateAttributesTime: 0,
      framesRedrawn: 0,
      pickTime: 0,
      pickCount: 0,
      gpuTime: 0,
      gpuTimePerFrame: 0,
      cpuTime: 0,
      cpuTimePerFrame: 0,
      bufferMemory: 0,
      textureMemory: 0,
      renderbufferMemory: 0,
      gpuMemory: 0
    };
    this._metricsCounter = 0;
    this._needsRedraw = 'Initial render';
    this._pickRequest = {
      mode: 'hover',
      x: -1,
      y: -1,
      radius: 0,
      event: null
    };
    this._lastPointerDownInfo = null;

    this._onPointerMove = function (event) {
      var _pickRequest = _this._pickRequest;

      if (event.type === 'pointerleave') {
        _pickRequest.x = -1;
        _pickRequest.y = -1;
        _pickRequest.radius = 0;
      } else if (event.leftButton || event.rightButton) {
        return;
      } else {
        var pos = event.offsetCenter;

        if (!pos) {
          return;
        }

        _pickRequest.x = pos.x;
        _pickRequest.y = pos.y;
        _pickRequest.radius = _this.props.pickingRadius;
      }

      if (_this.layerManager) {
        _this.layerManager.context.mousePosition = {
          x: _pickRequest.x,
          y: _pickRequest.y
        };
      }

      _pickRequest.event = event;
    };

    this._onEvent = function (event) {
      var eventOptions = _constants2.EVENTS[event.type];
      var pos = event.offsetCenter;

      if (!eventOptions || !pos || !_this.layerManager) {
        return;
      }

      var layers = _this.layerManager.getLayers();

      var info = _this.deckPicker.getLastPickedObject({
        x: pos.x,
        y: pos.y,
        layers: layers,
        viewports: _this.getViewports(pos)
      }, _this._lastPointerDownInfo);

      var layer = info.layer;
      var layerHandler = layer && (layer[eventOptions.handler] || layer.props[eventOptions.handler]);
      var rootHandler = _this.props[eventOptions.handler];
      var handled = false;

      if (layerHandler) {
        handled = layerHandler.call(layer, info, event);
      }

      if (!handled) {
        rootHandler === null || rootHandler === void 0 ? void 0 : rootHandler(info, event);

        _this.widgetManager.onEvent(info, event);
      }
    };

    this._onPointerDown = function (event) {
      var pos = event.offsetCenter;

      var pickedInfo = _this._pick('pickObject', 'pickObject Time', {
        x: pos.x,
        y: pos.y,
        radius: _this.props.pickingRadius
      });

      _this._lastPointerDownInfo = pickedInfo.result[0] || pickedInfo.emptyInfo;
    };

    this.props = _objectSpread(_objectSpread({}, defaultProps), props);
    props = this.props;

    if (props.viewState && props.initialViewState) {
      _log.default.warn('View state tracking is disabled. Use either `initialViewState` for auto update or `viewState` for manual update.')();
    }

    if ((0, _env.getBrowser)() === 'IE') {
      _log.default.warn('IE 11 is not supported')();
    }

    this.viewState = props.initialViewState;

    if (props.device) {
      this.device = props.device;
    } else if (props.gl) {
      this.device = _webgl.WebGLDevice.attach(props.gl);
    }

    var deviceOrPromise = this.device;

    if (!deviceOrPromise) {
      _core.luma.registerDevices([_webgl.WebGLDevice]);

      deviceOrPromise = _core.luma.createDevice(_objectSpread(_objectSpread({}, props.deviceProps), {}, {
        canvas: this._createCanvas(props)
      }));
      deviceOrPromise.then(function (device) {
        _this.device = device;
      });
    }

    this.animationLoop = this._createAnimationLoop(deviceOrPromise, props);
    this.setProps(props);

    if (props._typedArrayManagerProps) {
      _typedArrayManager.default.setOptions(props._typedArrayManagerProps);
    }

    this.animationLoop.start();
  }

  var _proto = Deck.prototype;

  _proto.finalize = function finalize() {
    var _this$animationLoop, _this$animationLoop2, _this$layerManager, _this$viewManager, _this$effectManager, _this$deckRenderer, _this$deckPicker, _this$eventManager, _this$widgetManager;

    (_this$animationLoop = this.animationLoop) === null || _this$animationLoop === void 0 ? void 0 : _this$animationLoop.stop();
    (_this$animationLoop2 = this.animationLoop) === null || _this$animationLoop2 === void 0 ? void 0 : _this$animationLoop2.destroy();
    this.animationLoop = null;
    this._lastPointerDownInfo = null;
    (_this$layerManager = this.layerManager) === null || _this$layerManager === void 0 ? void 0 : _this$layerManager.finalize();
    this.layerManager = null;
    (_this$viewManager = this.viewManager) === null || _this$viewManager === void 0 ? void 0 : _this$viewManager.finalize();
    this.viewManager = null;
    (_this$effectManager = this.effectManager) === null || _this$effectManager === void 0 ? void 0 : _this$effectManager.finalize();
    this.effectManager = null;
    (_this$deckRenderer = this.deckRenderer) === null || _this$deckRenderer === void 0 ? void 0 : _this$deckRenderer.finalize();
    this.deckRenderer = null;
    (_this$deckPicker = this.deckPicker) === null || _this$deckPicker === void 0 ? void 0 : _this$deckPicker.finalize();
    this.deckPicker = null;
    (_this$eventManager = this.eventManager) === null || _this$eventManager === void 0 ? void 0 : _this$eventManager.destroy();
    this.eventManager = null;
    (_this$widgetManager = this.widgetManager) === null || _this$widgetManager === void 0 ? void 0 : _this$widgetManager.finalize();
    this.widgetManager = null;

    if (!this.props.canvas && !this.props.device && this.canvas) {
      var _this$canvas$parentEl;

      (_this$canvas$parentEl = this.canvas.parentElement) === null || _this$canvas$parentEl === void 0 ? void 0 : _this$canvas$parentEl.removeChild(this.canvas);
      this.canvas = null;
    }
  };

  _proto.setProps = function setProps(props) {
    var _this$animationLoop3;

    this.stats.get('setProps Time').timeStart();

    if ('onLayerHover' in props) {
      _log.default.removed('onLayerHover', 'onHover')();
    }

    if ('onLayerClick' in props) {
      _log.default.removed('onLayerClick', 'onClick')();
    }

    if (props.initialViewState && !(0, _deepEqual.deepEqual)(this.props.initialViewState, props.initialViewState, 3)) {
      this.viewState = props.initialViewState;
    }

    Object.assign(this.props, props);

    this._setCanvasSize(this.props);

    var resolvedProps = Object.create(this.props);
    Object.assign(resolvedProps, {
      views: this._getViews(),
      width: this.width,
      height: this.height,
      viewState: this._getViewState()
    });
    (_this$animationLoop3 = this.animationLoop) === null || _this$animationLoop3 === void 0 ? void 0 : _this$animationLoop3.setProps(resolvedProps);

    if (this.layerManager) {
      this.viewManager.setProps(resolvedProps);
      this.layerManager.activateViewport(this.getViewports()[0]);
      this.layerManager.setProps(resolvedProps);
      this.effectManager.setProps(resolvedProps);
      this.deckRenderer.setProps(resolvedProps);
      this.deckPicker.setProps(resolvedProps);
      this.widgetManager.setProps(resolvedProps);
    }

    this.stats.get('setProps Time').timeEnd();
  };

  _proto.needsRedraw = function needsRedraw() {
    var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
      clearRedrawFlags: false
    };

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

    if (this.props._animate) {
      return 'Deck._animate';
    }

    var redraw = this._needsRedraw;

    if (opts.clearRedrawFlags) {
      this._needsRedraw = false;
    }

    var viewManagerNeedsRedraw = this.viewManager.needsRedraw(opts);
    var layerManagerNeedsRedraw = this.layerManager.needsRedraw(opts);
    var effectManagerNeedsRedraw = this.effectManager.needsRedraw(opts);
    var deckRendererNeedsRedraw = this.deckRenderer.needsRedraw(opts);
    redraw = redraw || viewManagerNeedsRedraw || layerManagerNeedsRedraw || effectManagerNeedsRedraw || deckRendererNeedsRedraw;
    return redraw;
  };

  _proto.redraw = function redraw(reason) {
    if (!this.layerManager) {
      return;
    }

    var redrawReason = this.needsRedraw({
      clearRedrawFlags: true
    });
    redrawReason = reason || redrawReason;

    if (!redrawReason) {
      return;
    }

    this.stats.get('Redraw Count').incrementCount();

    if (this.props._customRender) {
      this.props._customRender(redrawReason);
    } else {
      this._drawLayers(redrawReason);
    }
  };

  _proto.getViews = function getViews() {
    (0, _assert.default)(this.viewManager);
    return this.viewManager.views;
  };

  _proto.getViewports = function getViewports(rect) {
    (0, _assert.default)(this.viewManager);
    return this.viewManager.getViewports(rect);
  };

  _proto.getCanvas = function getCanvas() {
    return this.canvas;
  };

  _proto.pickObject = function pickObject(opts) {
    var infos = this._pick('pickObject', 'pickObject Time', opts).result;

    return infos.length ? infos[0] : null;
  };

  _proto.pickMultipleObjects = function pickMultipleObjects(opts) {
    opts.depth = opts.depth || 10;
    return this._pick('pickObject', 'pickMultipleObjects Time', opts).result;
  };

  _proto.pickObjects = function pickObjects(opts) {
    return this._pick('pickObjects', 'pickObjects Time', opts);
  };

  _proto._addResources = function _addResources(resources) {
    var forceUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    for (var _id in resources) {
      this.layerManager.resourceManager.add({
        resourceId: _id,
        data: resources[_id],
        forceUpdate: forceUpdate
      });
    }
  };

  _proto._removeResources = function _removeResources(resourceIds) {
    var _iterator = _createForOfIteratorHelper(resourceIds),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _id2 = _step.value;
        this.layerManager.resourceManager.remove(_id2);
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  };

  _proto._addDefaultEffect = function _addDefaultEffect(effect) {
    this.effectManager.addDefaultEffect(effect);
  };

  _proto._pick = function _pick(method, statKey, opts) {
    (0, _assert.default)(this.deckPicker);
    var stats = this.stats;
    stats.get('Pick Count').incrementCount();
    stats.get(statKey).timeStart();
    var infos = this.deckPicker[method](_objectSpread({
      layers: this.layerManager.getLayers(opts),
      views: this.viewManager.getViews(),
      viewports: this.getViewports(opts),
      onViewportActive: this.layerManager.activateViewport,
      effects: this.effectManager.getEffects()
    }, opts));
    stats.get(statKey).timeEnd();
    return infos;
  };

  _proto._createCanvas = function _createCanvas(props) {
    var canvas = props.canvas;

    if (typeof canvas === 'string') {
      canvas = document.getElementById(canvas);
      (0, _assert.default)(canvas);
    }

    if (!canvas) {
      canvas = document.createElement('canvas');
      canvas.id = props.id || 'deckgl-overlay';
      var parent = props.parent || document.body;
      parent.appendChild(canvas);
    }

    Object.assign(canvas.style, props.style);
    return canvas;
  };

  _proto._setCanvasSize = function _setCanvasSize(props) {
    if (!this.canvas) {
      return;
    }

    var width = props.width,
        height = props.height;

    if (width || width === 0) {
      var cssWidth = Number.isFinite(width) ? "".concat(width, "px") : width;
      this.canvas.style.width = cssWidth;
    }

    if (height || height === 0) {
      var _props$style;

      var cssHeight = Number.isFinite(height) ? "".concat(height, "px") : height;
      this.canvas.style.position = ((_props$style = props.style) === null || _props$style === void 0 ? void 0 : _props$style.position) || 'absolute';
      this.canvas.style.height = cssHeight;
    }
  };

  _proto._updateCanvasSize = function _updateCanvasSize() {
    var _canvas$clientWidth, _canvas$clientHeight;

    var canvas = this.canvas;

    if (!canvas) {
      return;
    }

    var newWidth = (_canvas$clientWidth = canvas.clientWidth) !== null && _canvas$clientWidth !== void 0 ? _canvas$clientWidth : canvas.width;
    var newHeight = (_canvas$clientHeight = canvas.clientHeight) !== null && _canvas$clientHeight !== void 0 ? _canvas$clientHeight : canvas.height;

    if (newWidth !== this.width || newHeight !== this.height) {
      var _this$viewManager2, _this$layerManager2;

      this.width = newWidth;
      this.height = newHeight;
      (_this$viewManager2 = this.viewManager) === null || _this$viewManager2 === void 0 ? void 0 : _this$viewManager2.setProps({
        width: newWidth,
        height: newHeight
      });
      (_this$layerManager2 = this.layerManager) === null || _this$layerManager2 === void 0 ? void 0 : _this$layerManager2.activateViewport(this.getViewports()[0]);
      this.props.onResize({
        width: newWidth,
        height: newHeight
      });
    }
  };

  _proto._createAnimationLoop = function _createAnimationLoop(deviceOrPromise, props) {
    var _this2 = this;

    var gl = props.gl,
        onError = props.onError,
        useDevicePixels = props.useDevicePixels;
    return new _engine.AnimationLoop({
      device: deviceOrPromise,
      useDevicePixels: useDevicePixels,
      autoResizeDrawingBuffer: !gl,
      autoResizeViewport: false,
      onInitialize: function onInitialize(context) {
        return _this2._setDevice(context.device);
      },
      onRender: this._onRenderFrame.bind(this),
      onError: onError
    });
  };

  _proto._getViewState = function _getViewState() {
    return this.props.viewState || this.viewState;
  };

  _proto._getViews = function _getViews() {
    var views = this.props.views || [new _mapView.default({
      id: 'default-view'
    })];
    views = Array.isArray(views) ? views : [views];

    if (views.length && this.props.controller) {
      views[0].props.controller = this.props.controller;
    }

    return views;
  };

  _proto._onContextLost = function _onContextLost() {
    var onError = this.props.onError;

    if (this.animationLoop && onError) {
      onError(new Error('WebGL context is lost'));
    }
  };

  _proto._pickAndCallback = function _pickAndCallback() {
    var _pickRequest = this._pickRequest;

    if (_pickRequest.event) {
      var _this$_pick = this._pick('pickObject', 'pickObject Time', _pickRequest),
          result = _this$_pick.result,
          emptyInfo = _this$_pick.emptyInfo;

      this.cursorState.isHovering = result.length > 0;
      var pickedInfo = emptyInfo;
      var handled = false;

      var _iterator2 = _createForOfIteratorHelper(result),
          _step2;

      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var _info$layer;

          var _info = _step2.value;
          pickedInfo = _info;
          handled = ((_info$layer = _info.layer) === null || _info$layer === void 0 ? void 0 : _info$layer.onHover(_info, _pickRequest.event)) || handled;
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }

      if (!handled) {
        var _this$props$onHover, _this$props;

        (_this$props$onHover = (_this$props = this.props).onHover) === null || _this$props$onHover === void 0 ? void 0 : _this$props$onHover.call(_this$props, pickedInfo, _pickRequest.event);
        this.widgetManager.onHover(pickedInfo, _pickRequest.event);
      }

      _pickRequest.event = null;
    }
  };

  _proto._updateCursor = function _updateCursor() {
    var container = this.props.parent || this.canvas;

    if (container) {
      container.style.cursor = this.props.getCursor(this.cursorState);
    }
  };

  _proto._setDevice = function _setDevice(device) {
    var _this$canvas;

    this.device = device;

    if (this.layerManager) {
      return;
    }

    if (!this.canvas) {
      var _this$device$canvasCo;

      this.canvas = (_this$device$canvasCo = this.device.canvasContext) === null || _this$device$canvasCo === void 0 ? void 0 : _this$device$canvasCo.canvas;
    }

    (0, _webgl.setGLParameters)(this.device, {
      blend: true,
      blendFunc: [770, 771, 1, 771],
      polygonOffsetFill: true,
      depthTest: true,
      depthFunc: 515
    });
    this.props.onDeviceInitialized(this.device);

    if (this.device instanceof _webgl.WebGLDevice) {
      this.props.onWebGLInitialized(this.device.gl);
    }

    var timeline = new _engine.Timeline();
    timeline.play();
    this.animationLoop.attachTimeline(timeline);
    this.eventManager = new _mjolnir.EventManager(this.props.parent || this.canvas, {
      touchAction: this.props.touchAction,
      recognizerOptions: this.props.eventRecognizerOptions,
      events: {
        pointerdown: this._onPointerDown,
        pointermove: this._onPointerMove,
        pointerleave: this._onPointerMove
      }
    });

    for (var eventType in _constants2.EVENTS) {
      this.eventManager.on(eventType, this._onEvent);
    }

    this.viewManager = new _viewManager.default({
      timeline: timeline,
      eventManager: this.eventManager,
      onViewStateChange: this._onViewStateChange.bind(this),
      onInteractionStateChange: this._onInteractionStateChange.bind(this),
      views: this._getViews(),
      viewState: this._getViewState(),
      width: this.width,
      height: this.height
    });
    var viewport = this.viewManager.getViewports()[0];
    this.layerManager = new _layerManager.default(this.device, {
      deck: this,
      stats: this.stats,
      viewport: viewport,
      timeline: timeline
    });
    this.effectManager = new _effectManager.default();
    this.deckRenderer = new _deckRenderer.default(this.device);
    this.deckPicker = new _deckPicker.default(this.device);
    this.widgetManager = new _widgetManager.WidgetManager({
      deck: this,
      parentElement: (_this$canvas = this.canvas) === null || _this$canvas === void 0 ? void 0 : _this$canvas.parentElement
    });
    this.widgetManager.addDefault(new _tooltip.default());
    this.setProps(this.props);

    this._updateCanvasSize();

    this.props.onLoad();
  };

  _proto._drawLayers = function _drawLayers(redrawReason, renderOptions) {
    var _this$deckRenderer2;

    var _context = this.layerManager.context,
        device = _context.device,
        gl = _context.gl;
    (0, _webgl.setGLParameters)(device, this.props.parameters);
    this.props.onBeforeRender({
      device: device,
      gl: gl
    });

    var opts = _objectSpread({
      target: this.props._framebuffer,
      layers: this.layerManager.getLayers(),
      viewports: this.viewManager.getViewports(),
      onViewportActive: this.layerManager.activateViewport,
      views: this.viewManager.getViews(),
      pass: 'screen',
      effects: this.effectManager.getEffects()
    }, renderOptions);

    (_this$deckRenderer2 = this.deckRenderer) === null || _this$deckRenderer2 === void 0 ? void 0 : _this$deckRenderer2.renderLayers(opts);

    if (opts.pass === 'screen') {
      this.widgetManager.onRedraw({
        viewports: opts.viewports,
        layers: opts.layers
      });
    }

    this.props.onAfterRender({
      device: device,
      gl: gl
    });
  };

  _proto._onRenderFrame = function _onRenderFrame(animationProps) {
    this._getFrameStats();

    if (this._metricsCounter++ % 60 === 0) {
      this._getMetrics();

      this.stats.reset();

      _log.default.table(4, this.metrics)();

      if (this.props._onMetrics) {
        this.props._onMetrics(this.metrics);
      }
    }

    this._updateCanvasSize();

    this._updateCursor();

    this.layerManager.updateLayers();

    this._pickAndCallback();

    this.redraw();

    if (this.viewManager) {
      this.viewManager.updateViewStates();
    }
  };

  _proto._onViewStateChange = function _onViewStateChange(params) {
    var viewState = this.props.onViewStateChange(params) || params.viewState;

    if (this.viewState) {
      this.viewState = _objectSpread(_objectSpread({}, this.viewState), {}, (0, _defineProperty2.default)({}, params.viewId, viewState));

      if (!this.props.viewState) {
        if (this.viewManager) {
          this.viewManager.setProps({
            viewState: this.viewState
          });
        }
      }
    }
  };

  _proto._onInteractionStateChange = function _onInteractionStateChange(interactionState) {
    this.cursorState.isDragging = interactionState.isDragging || false;
    this.props.onInteractionStateChange(interactionState);
  };

  _proto._getFrameStats = function _getFrameStats() {
    var stats = this.stats;
    stats.get('frameRate').timeEnd();
    stats.get('frameRate').timeStart();
    var animationLoopStats = this.animationLoop.stats;
    stats.get('GPU Time').addTime(animationLoopStats.get('GPU Time').lastTiming);
    stats.get('CPU Time').addTime(animationLoopStats.get('CPU Time').lastTiming);
  };

  _proto._getMetrics = function _getMetrics() {
    var metrics = this.metrics,
        stats = this.stats;
    metrics.fps = stats.get('frameRate').getHz();
    metrics.setPropsTime = stats.get('setProps Time').time;
    metrics.updateAttributesTime = stats.get('Update Attributes').time;
    metrics.framesRedrawn = stats.get('Redraw Count').count;
    metrics.pickTime = stats.get('pickObject Time').time + stats.get('pickMultipleObjects Time').time + stats.get('pickObjects Time').time;
    metrics.pickCount = stats.get('Pick Count').count;
    metrics.gpuTime = stats.get('GPU Time').time;
    metrics.cpuTime = stats.get('CPU Time').time;
    metrics.gpuTimePerFrame = stats.get('GPU Time').getAverageTime();
    metrics.cpuTimePerFrame = stats.get('CPU Time').getAverageTime();

    var memoryStats = _core.luma.stats.get('Memory Usage');

    metrics.bufferMemory = memoryStats.get('Buffer Memory').count;
    metrics.textureMemory = memoryStats.get('Texture Memory').count;
    metrics.renderbufferMemory = memoryStats.get('Renderbuffer Memory').count;
    metrics.gpuMemory = memoryStats.get('GPU Memory').count;
  };

  (0, _createClass2.default)(Deck, [{
    key: "isInitialized",
    get: function get() {
      return this.viewManager !== null;
    }
  }]);
  return Deck;
}();

exports.default = Deck;
Deck.defaultProps = defaultProps;
Deck.VERSION = _init.VERSION;
//# sourceMappingURL=deck.js.map