"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const three_module = require("../../../../../../../three@0.154.0/node_modules/three/build/three.module.js");
const material = require("./material.js");
const primitiveNode = require("./nodes/primitive-node.js");
const threeDomElement = require("./three-dom-element.js");
/* @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var _a, _b, _c, _d, _e, _f;
const $materials = Symbol("materials");
const $hierarchy = Symbol("hierarchy");
const $roots = Symbol("roots");
const $primitivesList = Symbol("primitives");
const $prepareVariantsForExport = Symbol("prepareVariantsForExport");
const $switchVariant = Symbol("switchVariant");
const $materialFromPoint = Symbol("materialFromPoint");
const $nodeFromPoint = Symbol("nodeFromPoint");
const $nodeFromIndex = Symbol("nodeFromIndex");
const $variantData = Symbol("variantData");
const $availableVariants = Symbol("availableVariants");
const $modelOnUpdate = Symbol("modelOnUpdate");
const $cloneMaterial = Symbol("cloneMaterial");
class LazyLoader {
  constructor(gltf, gltfElementMap, mapKey, doLazyLoad) {
    this.gltf = gltf;
    this.gltfElementMap = gltfElementMap;
    this.mapKey = mapKey;
    this.doLazyLoad = doLazyLoad;
  }
}
class Model {
  constructor(correlatedSceneGraph, onUpdate = () => {
  }) {
    this[_a] = new Array();
    this[_b] = new Array();
    this[_c] = new Array();
    this[_d] = new Array();
    this[_e] = () => {
    };
    this[_f] = /* @__PURE__ */ new Map();
    this[$modelOnUpdate] = onUpdate;
    const { gltf, threeGLTF, gltfElementMap } = correlatedSceneGraph;
    for (const [i, material$1] of gltf.materials.entries()) {
      const correlatedMaterial = gltfElementMap.get(material$1);
      if (correlatedMaterial != null) {
        this[$materials].push(new material.Material(onUpdate, i, true, this[$variantData], correlatedMaterial, material$1.name));
      } else {
        const elementArray = gltf["materials"] || [];
        const gltfMaterialDef = elementArray[i];
        const capturedMatIndex = i;
        const materialLoadCallback = async () => {
          const threeMaterial = await threeGLTF.parser.getDependency("material", capturedMatIndex);
          const threeMaterialSet = /* @__PURE__ */ new Set();
          gltfElementMap.set(gltfMaterialDef, threeMaterialSet);
          threeMaterialSet.add(threeMaterial);
          return { set: threeMaterialSet, material: threeMaterial };
        };
        this[$materials].push(new material.Material(onUpdate, i, false, this[$variantData], correlatedMaterial, material$1.name, new LazyLoader(gltf, gltfElementMap, gltfMaterialDef, materialLoadCallback)));
      }
    }
    const parentMap = /* @__PURE__ */ new Map();
    const nodeStack = new Array();
    for (const object of threeGLTF.scene.children) {
      nodeStack.push(object);
    }
    while (nodeStack.length > 0) {
      const object = nodeStack.pop();
      let node = null;
      if (object instanceof three_module.Mesh) {
        node = new primitiveNode.PrimitiveNode(object, this.materials, this[$variantData], correlatedSceneGraph);
        this[$primitivesList].push(node);
      } else {
        node = new primitiveNode.Node(object.name);
      }
      const parent = parentMap.get(object);
      if (parent != null) {
        parent.children.push(node);
      } else {
        this[$roots].push(node);
      }
      this[$hierarchy].push(node);
      for (const child of object.children) {
        nodeStack.push(child);
        parentMap.set(object, node);
      }
    }
  }
  /**
   * Materials are listed in the order of the GLTF materials array, plus a
   * default material at the end if one is used.
   *
   * TODO(#1003): How do we handle non-active scenes?
   */
  get materials() {
    return this[$materials];
  }
  [(_a = $materials, _b = $hierarchy, _c = $roots, _d = $primitivesList, _e = $modelOnUpdate, _f = $variantData, $availableVariants)]() {
    const variants = Array.from(this[$variantData].values());
    variants.sort((a, b) => {
      return a.index - b.index;
    });
    return variants.map((data) => {
      return data.name;
    });
  }
  getMaterialByName(name) {
    const matches = this[$materials].filter((material2) => {
      return material2.name === name;
    });
    if (matches.length > 0) {
      return matches[0];
    }
    return null;
  }
  [$nodeFromIndex](mesh, primitive) {
    const found = this[$hierarchy].find((node) => {
      if (node instanceof primitiveNode.PrimitiveNode) {
        const { meshes, primitives } = node.mesh.userData.associations;
        if (meshes == mesh && primitives == primitive) {
          return true;
        }
      }
      return false;
    });
    return found == null ? null : found;
  }
  [$nodeFromPoint](hit) {
    return this[$hierarchy].find((node) => {
      if (node instanceof primitiveNode.PrimitiveNode) {
        const primitive = node;
        if (primitive.mesh === hit.object) {
          return true;
        }
      }
      return false;
    });
  }
  /**
   * Intersects a ray with the Model and returns the first material whose
   * object was intersected.
   */
  [$materialFromPoint](hit) {
    return this[$nodeFromPoint](hit).getActiveMaterial();
  }
  /**
   * Switches model variant to the variant name provided, or switches to
   * default/initial materials if 'null' is provided.
   */
  async [$switchVariant](variantName) {
    for (const primitive of this[$primitivesList]) {
      await primitive.enableVariant(variantName);
    }
    for (const material$1 of this.materials) {
      material$1[material.$setActive](false);
    }
    for (const primitive of this[$primitivesList]) {
      this.materials[primitive.getActiveMaterial().index][material.$setActive](true);
    }
  }
  async [$prepareVariantsForExport]() {
    const promises = new Array();
    for (const primitive of this[$primitivesList]) {
      promises.push(primitive.instantiateVariants());
    }
    await Promise.all(promises);
  }
  [$cloneMaterial](index, newMaterialName) {
    const material$1 = this.materials[index];
    if (!material$1.isLoaded) {
      console.error(`Cloning an unloaded material,
           call 'material.ensureLoaded() before cloning the material.`);
    }
    const threeMaterialSet = material$1[threeDomElement.$correlatedObjects];
    const clonedSet = /* @__PURE__ */ new Set();
    for (const [i, threeMaterial] of threeMaterialSet.entries()) {
      const clone = threeMaterial.clone();
      clone.name = newMaterialName + (threeMaterialSet.size > 1 ? "_inst" + i : "");
      clonedSet.add(clone);
    }
    const clonedMaterial = new material.Material(
      this[$modelOnUpdate],
      this[$materials].length,
      false,
      // Cloned as inactive.
      this[$variantData],
      clonedSet,
      newMaterialName
    );
    this[$materials].push(clonedMaterial);
    return clonedMaterial;
  }
  createMaterialInstanceForVariant(originalMaterialIndex, newMaterialName, variantName, activateVariant = true) {
    let variantMaterialInstance = null;
    for (const primitive of this[$primitivesList]) {
      const variantData = this[$variantData].get(variantName);
      if (variantData != null && primitive.variantInfo.has(variantData.index)) {
        continue;
      }
      if (primitive.getMaterial(originalMaterialIndex) == null) {
        continue;
      }
      if (!this.hasVariant(variantName)) {
        this.createVariant(variantName);
      }
      if (variantMaterialInstance == null) {
        variantMaterialInstance = this[$cloneMaterial](originalMaterialIndex, newMaterialName);
      }
      primitive.addVariant(variantMaterialInstance, variantName);
    }
    if (activateVariant && variantMaterialInstance != null) {
      variantMaterialInstance[material.$setActive](true);
      this.materials[originalMaterialIndex][material.$setActive](false);
      for (const primitive of this[$primitivesList]) {
        primitive.enableVariant(variantName);
      }
    }
    return variantMaterialInstance;
  }
  createVariant(variantName) {
    if (!this[$variantData].has(variantName)) {
      this[$variantData].set(variantName, { name: variantName, index: this[$variantData].size });
    } else {
      console.warn(`Variant '${variantName}'' already exists`);
    }
  }
  hasVariant(variantName) {
    return this[$variantData].has(variantName);
  }
  setMaterialToVariant(materialIndex, targetVariantName) {
    if (this[$availableVariants]().find((name) => name === targetVariantName) == null) {
      console.warn(`Can't add material to '${targetVariantName}', the variant does not exist.'`);
      return;
    }
    if (materialIndex < 0 || materialIndex >= this.materials.length) {
      console.error(`setMaterialToVariant(): materialIndex is out of bounds.`);
      return;
    }
    for (const primitive of this[$primitivesList]) {
      const material2 = primitive.getMaterial(materialIndex);
      if (material2 != null) {
        primitive.addVariant(material2, targetVariantName);
      }
    }
  }
  updateVariantName(currentName, newName) {
    const variantData = this[$variantData].get(currentName);
    if (variantData == null) {
      return;
    }
    variantData.name = newName;
    this[$variantData].set(newName, variantData);
    this[$variantData].delete(currentName);
  }
  deleteVariant(variantName) {
    const variant = this[$variantData].get(variantName);
    if (variant == null) {
      return;
    }
    for (const material$1 of this.materials) {
      if (material$1.hasVariant(variantName)) {
        material$1[material.$variantSet].delete(variant.index);
      }
    }
    for (const primitive of this[$primitivesList]) {
      primitive.deleteVariant(variant.index);
    }
    this[$variantData].delete(variantName);
  }
}
exports.$availableVariants = $availableVariants;
exports.$materialFromPoint = $materialFromPoint;
exports.$materials = $materials;
exports.$nodeFromIndex = $nodeFromIndex;
exports.$nodeFromPoint = $nodeFromPoint;
exports.$prepareVariantsForExport = $prepareVariantsForExport;
exports.$primitivesList = $primitivesList;
exports.$switchVariant = $switchVariant;
exports.$variantData = $variantData;
exports.LazyLoader = LazyLoader;
exports.Model = Model;
//# sourceMappingURL=model.js.map
