<template>
  <div ref="wrap"></div>
</template>
<script setup>
import * as THREE from "three";
import * as SceneUtils from "three/examples/jsm/utils/SceneUtils";
import { onMounted, ref } from "vue";

/**
 * @type {import("vue").Ref<HTMLDivElement>}
 */
const wrap = ref();

const [canvasW, canvasH] = [1000, 500];

onMounted(() => {
  var scene = new THREE.Scene();
  var camera = new THREE.PerspectiveCamera(50, canvasW / canvasH, 0.1, 1000);
  camera.position.set(10, 10, 10);
  var renderer = new THREE.WebGLRenderer();
  renderer.setSize(canvasW, canvasH);
  wrap.value.appendChild(renderer.domElement);
  var geometry = new THREE.BoxGeometry(4, 4, 4, 4, 4, 4);
  var materialBasic = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    wireframe: true,
  });
  var materialLambert = new THREE.MeshLambertMaterial({
    color: 0x777777,
    wireframe: true,
  });
  var materialNormal = new THREE.MeshNormalMaterial({
    color: 0x777777,
    wireframe: true,
  });
  var cube = SceneUtils.createMultiMaterialObject(geometry, [
    // materialBasic,
    materialNormal,
    // materialLambert,
  ]);

  // var cube = new THREE.Mesh(geometry, materialLambert);
  cube.position.set(0, 0, 0);
  camera.lookAt(cube.position);
  scene.add(cube);
  var spotLight = new THREE.SpotLight(0xffffff);
  spotLight.position.set(20, 20, 20);
  spotLight.intensity = 1;
  scene.add(spotLight);
  var axes = new THREE.AxesHelper(1000);
  scene.add(axes);
  renderer.render(scene, camera);
  let [cx, cy, cz] = [10, 10, 10];
  window.addEventListener("keydown", function (e) {
    console.log(e.keyCode);
    switch (e.keyCode) {
      case 38: // up
        cy -= 1;
        cx -= 1;
        cz -= 1;
        break;
      case 40: // down
        cy += 1;
        cx += 1;
        cz += 1;
        break;
      case 37: // left
        cube.rotation.x -= 0.01;
        cube.rotation.y -= 0.01;
        break;
      case 39: // right
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
        break;
    }
    camera.position.set(cx, cy, cz);
    camera.lookAt(cube.position);
    renderer.render(scene, camera);
  });

  // 9、创建动画循环渲染函数
  function animate() {
    // 9.1 循环调用函数
    requestAnimationFrame(animate);
    // 每一次animate函数调用，都让网格比上一次 X 轴、Y 轴各旋转增加 0.01 弧度
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    cube.rotation.z += 0.01;
    // cube.rotation.y += 0.01;
    // 3.3 结合场景和相机进行渲染，即用摄像机拍下此刻的场景
    renderer.render(scene, camera);
  }
  // 调用动画函数
  animate();
});
</script>
