<script setup lang="ts">
import { ACESFilmicToneMapping, AmbientLight, Color, Fog, Object3D, Scene, sRGBEncoding } from 'three'

import { Model } from '~/composables/useModel'

const scene = new Scene()
const { createCamera } = useCamera()

const camera = createCamera(CameraType.Perspective)

const bgColor = new Color('#E1F0C2')
// Fog
scene.fog = new Fog(bgColor, 0.1, 75)
scene.background = bgColor

camera.position.set(15, 15, 15)
scene.add(camera)

// Lights
const light = new AmbientLight(0xffaaff)
light.position.set(10, 10, 10)
light.intensity = 1
scene.add(light)

// Model
const { loadModel } = useModel()

const cardbobot: Model = await loadModel('/models/cardbobot/CardBoBotv2.gltf')

if (cardbobot) scene.add(cardbobot as Object3D<Event>)

// Renderer

const { experience, initRenderer, updateRenderer, renderScene, updateControls, disposeRenderer } = useRenderer()

const loop = () => {
  // Update renderer

  updateControls()

  renderScene(scene, camera)
  requestAnimationFrame(loop)
}

onMounted(() => {
  initRenderer(camera, {
    renderer: {
      antialias: true,
      alpha: true,
      preserveDrawingBuffer: true,
    },
    shadows: true,
    controls: true,
    physicallyCorrectLights: true,
    outputEncoding: sRGBEncoding,
    toneMapping: ACESFilmicToneMapping,
  })
  loop()
  updateRenderer()
})

onBeforeUnmount(() => {
  disposeRenderer()
})
</script>

<template>
  <canvas ref="experience" />
</template>

<route lang="yaml">
meta:
  layout: experiment
  title: CardBoBot
  media: '/models/gltf_composables.png'
  description: 'Using composition API to load a GLTF model'
  tags: ['gltf', 'loader', 'model', 'composition']
</route>
