// src/js-tools/mapbox/mapbox-three.ts
import {
  LngLat,
  MercatorCoordinate
} from "mapbox-gl";
import {
  EventDispatcher,
  Matrix4,
  PerspectiveCamera,
  Scene,
  Vector3,
  WebGLRenderer
} from "three";
var CustomLayer = class extends EventDispatcher {
  constructor({
    id,
    anchor,
    renderingMode
  }) {
    super();
    this.type = "custom";
    this._map = null;
    this._renderer = null;
    this.id = id;
    this.renderingMode = renderingMode;
    this.anchor = LngLat.convert(anchor);
    this.worldAnchor = MercatorCoordinate.fromLngLat(this.anchor, 0);
    this._camera = new PerspectiveCamera();
    this._scene = new Scene();
  }
  get map() {
    return this._map;
  }
  add(object) {
    this._scene.add(object);
  }
  remove(object) {
    this._scene.remove(object);
  }
  onAdd(map, gl) {
    this._renderer = new WebGLRenderer({
      antialias: true,
      canvas: map.getCanvas(),
      context: gl
    });
    this._renderer.autoClear = false;
    this._map = map;
  }
  onRemove() {
    this._renderer?.dispose();
    this._renderer = null;
    this._map = null;
  }
  prerender(_gl, matrix) {
    if (!this._renderer) return;
    this._camera.projectionMatrix = new Matrix4().fromArray(matrix).multiply(
      new Matrix4().makeBasis(
        new Vector3(1, 0, 0),
        new Vector3(0, 0, 1),
        new Vector3(0, 1, 0)
      )
    ).multiply(new Matrix4().makeScale(1, 1, -1)).multiply(
      new Matrix4().makeTranslation(
        this.worldAnchor.x,
        this.worldAnchor.z ?? 0,
        -this.worldAnchor.y
      )
    );
    this.dispatchEvent({
      type: "beforerender",
      renderer: this._renderer,
      scene: this._scene,
      camera: this._camera
    });
  }
  render() {
    if (this._renderer) {
      this._renderer.resetState();
      this._renderer.render(this._scene, this._camera);
      this.dispatchEvent({
        type: "afterrender",
        renderer: this._renderer,
        scene: this._scene,
        camera: this._camera
      });
    }
  }
};

export {
  CustomLayer
};
