<template>
  <div ref="threeContainer"></div>
</template>

<script setup>
import * as THREE from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { onMounted, ref } from 'vue';

const threeContainer = ref(null);
let camera, scene, renderer, model, controls;
let width = 1920;
let height = 1080;
const init = () => {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0xbfe3dd);

  camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 2000);
  camera.position.set(0, 300, 200);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(width, height);
  threeContainer.value.appendChild(renderer.domElement);

  const objLoader = new OBJLoader();
  let mtlLoader = new MTLLoader();
  mtlLoader.load('/src/assets/obj/goats_R&D.mtl', function (materials) {
    materials.preload();
    objLoader.setMaterials(materials);
    objLoader.load('/src/assets/obj/goats_R&D.obj', function (obj) {
      var scale = 0.06 / obj.scale.x;
      obj.scale.set(scale, scale, scale);
      model = obj;
      const box = new THREE.Box3().setFromObject(model);
      const size = box.getSize(new THREE.Vector3())
      // console.log(size,'-----');
      obj.position.set(-size.x * 0.5, -size.y * 0.5, -size.z * 0.5);
      obj.children.forEach((child) => {
        const c = child;
        const cm = c.material;
        cm.emissive = cm.color;
        cm.emissiveMap = cm.map;
      });

      scene.add(model);
      animate();
    });
  });
  // loader.load(
  //   '/src/assets/obj/goats_R&D.obj',
  //   (obj) => {
  //     var scale = 0.1 / obj.scale.x;
  //     obj.scale.set(scale, scale, scale);
  //     model = obj;
  //     // 添加光照
  //     // scene.add(new THREE.AmbientLight(0x404040));
  //     scene.add(new THREE.DirectionalLight());
  //     scene.add(model);
  //   },
  //   (xhr) => {
  //     console.log((xhr.loaded / xhr.total * 100) + '% loaded');
  //   },
  //   (error) => {
  //     console.error('An error happened: ', error);
  //   }
  // );

  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;

  animate();
};

const animate = () => {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  controls.update();
};

onMounted(() => {
  init();
  window.addEventListener('resize', onWindowResize);
});

const onWindowResize = () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
};

onMounted(() => {
  window.removeEventListener('resize', onWindowResize);
});
</script>

<style>
#threeContainer {
  width: 1920px;
  height: 1080px;
  overflow: hidden;
}
</style>