three.js加载和使用纹理-normalMap使用法向贴图创建表面不同凹凸程度的三维物体(vue中使用three.js75)

1.demo效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 知识要点

2.1 法向贴图

法向贴图 保存的是每个像素的法向量,这样的好处是使用非常少的顶点和面就可以创建出有丰富细节的模型

2.2 使用法向贴图

使用法向贴图的方法和使用凹凸贴图一样,只需要将material的 normalMap 属性设置成一个法向纹理即可,同时也可以通过material的 mormalScale 属性设置法向纹理的的凹凸程度,
设置方法如下:

//设置法线贴图
const normal = new THREE.TextureLoader().load(url)
this.cube2.material.normalMap = normal

//设置法向贴图的凹凸程度
material.normalScale.set(x, y)

3. 实现要点

3.1 创建模型

通过demo效果可知,每次切换页面中展示两个模型一个使用法向贴图,一个没有,先来说说如何创建带法向贴图和不带法向贴图的模型

//创建网格对象
createMesh(geom, imageFile, normal) {
  // 设置法向贴图
  const publicPath = process.env.BASE_URL
  const texture = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` + imageFile
  )
  const material = new THREE.MeshPhongMaterial()
  material.map = texture

  // 设置法向贴图的凹凸程度
  if (normal) {
    const normalMap = new THREE.TextureLoader().load(
      `${publicPath}textures/general/` + normal
    )
    material.normalMap = normalMap
  }
  const mesh = new THREE.Mesh(geom, material)
  return mesh
}
// 创建模型
createModels() {
  this.cube1 = this.createMesh(
    new THREE.BoxGeometry(15, 15, 15),
    'bathroom.jpg'
  )
  this.cube1.rotation.y = -0.5
  this.cube1.position.x = 12
  this.scene.add(this.cube1)

  this.cube2 = this.createMesh(
    new THREE.BoxGeometry(15, 15, 15),
    'bathroom.jpg',
    'bathroom-normal.jpg'
  )
  this.cube2.rotation.y = 0.5
  this.cube2.position.x = -12
  this.scene.add(this.cube2)

  this.createFloor()
}

3.2 模型贴图与法向贴图更新

每次切换不同的贴图时,模型的纹理贴图和法向贴图都需要更新,如何实现参照以下代码

propertiesChange() {
  const publicPath = process.env.BASE_URL

  // 更新物体表面纹理贴图
  const texture = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` + this.properties.textureType + '.jpg'
  )
  this.cube1.material.map = texture
  this.cube2.material.map = texture

  // 更新法向贴图
  const normal = new THREE.TextureLoader().load(
    `${publicPath}textures/general/` +
      this.properties.textureType +
      '-normal.jpg'
  )
  this.cube2.material.normalMap = normal

  // 更新法向贴图的凹凸程度
  this.cube2.material.normalScale.set(
    this.properties.normalScale.value,
    this.properties.normalScale.value
  ) // normalScale(x,y)
}

3.3 点光源绕物体8字型运动

// 创建球形光源
createSmallSphereLight() {
  const sphereLight = new THREE.SphereGeometry(0.2)
  const sphereLightMaterial = new THREE.MeshBasicMaterial({
    color: 0xac6c25
  })
  this.sphereLightMesh = new THREE.Mesh(sphereLight, sphereLightMaterial)
  this.sphereLightMesh.castShadow = true

  this.sphereLightMesh.position = new THREE.Vector3(3, 3, 3)
  this.scene.add(this.sphereLightMesh)
}
//球形点光源动画函数
smallShpereLightAnimation() {
  if (this.phase > 2 * Math.PI) {
    this.invert = this.invert * -1
    this.phase -= 2 * Math.PI
  } else {
    this.phase += 0.03
  }

  this.sphereLightMesh.position.z = +(21 * Math.sin(this.phase))
  this.sphereLightMesh.position.x = -14 + 14 * Math.cos(this.phase)

  if (this.invert < 0) {
    const pivot = 0
    this.sphereLightMesh.position.x =
      this.invert * (this.sphereLightMesh.position.x - pivot) + pivot
  }

  this.pointLight.position.copy(this.sphereLightMesh.position) // 把小球光源的坐标复制给点光源
}

3. demo代码

<template>
  <div>
    <div id="container" />
    <div class="controls-box">
      <section>
        <el-row>
          <el-checkbox v-model="properties.rotate">
            rotate
          </el-checkbox>
        </el-row>
        <el-row>
          <div v-for="(item,key) in properties" :key="key">
            <div v-if="item&&item.name!=undefined">
              <el-col :span="8">
                <span class="vertice-span">{{ item.name }}</span>
              </el-col>
              <el-col :span="13">
                <el-slider v-model="item.value" :min="item.min" :max="item.max" :step="item.step" :format-tooltip="formatTooltip" @change="propertiesChange" />
              </el-col>
              <el-col :span="3">
                <span class="vertice-span">{{ item.value }}</span>
              </el-col>
            </div>
          </div>
        </el-row>
        <el-row>
          <el-col :span="8" class="label-col">
            <label>texture</label>
          </el-col>
          <el-col :span="16">
            <el-select v-model="properties.textureType" placeholder="请选择" @change="propertiesChange">
              <el-option v-for="item in texturesOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-col>
        </el-row>
      </section>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
export default {
  data() {
    return {
      texturesOptions: [
        {
          value: 'bathroom',
          label: 'bathroom'
        },
        {
          value: 'plaster',
          label: 'plaster'
        },
        {
          value: 'metal-floor',
          label: 'metal-floor'
        }
      ],
      properties: {
        normalScale: {
          name: 'normalScale',
          value: 0.2,
          min: -2,
          max: 2,
          step: 0.1
        },
        textureType: 'bathroom',
        rotate: false
      },
      cube1: null,
      cube2: null,
      sphereLightMesh: null,
      pointLight: null,
      camera: null,
      scene: null,
      renderer: null,
      controls: null,
      invert: 1,
      phase: 0
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    formatTooltip(val) {
      return val
    },

    // 初始化
    init() {
      this.createScene() // 创建场景
      this.createModels() // 创建模型
      this.createLight() // 创建光源
      this.createCamera() // 创建相机
      this.createRender() // 创建渲染器
      this.createControls() // 创建控件对象
      this.render() // 渲染
    },
    // 创建场景
    createScene() {
      this.scene = new THREE.Scene()
    },
    // 创建模型
    createModels() {
      this.cube1 = this.createMesh(
        new THREE.BoxGeometry(15, 15, 15),
        'bathroom.jpg'
      )
      this.cube1.rotation.y = -0.5
      this.cube1.position.x = 12
      this.scene.add(this.cube1)

      this.cube2 = this.createMesh(
        new THREE.BoxGeometry(15, 15, 15),
        'bathroom.jpg',
        'bathroom-normal.jpg'
      )
      this.cube2.rotation.y = 0.5
      this.cube2.position.x = -12
      this.scene.add(this.cube2)

      this.createFloor()
    },
    //创建网格对象
    createMesh(geom, imageFile, normal) {
      // 设置法向贴图
      const publicPath = process.env.BASE_URL
      const texture = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` + imageFile
      )
      const material = new THREE.MeshPhongMaterial()
      material.map = texture

      // 设置法向贴图的凹凸程度
      if (normal) {
        const normalMap = new THREE.TextureLoader().load(
          `${publicPath}textures/general/` + normal
        )
        material.normalMap = normalMap
      }
      const mesh = new THREE.Mesh(geom, material)
      return mesh
    },
    createFloor() {
      const publicPath = process.env.BASE_URL
      const floorTex = new THREE.TextureLoader().load(
        `${publicPath}textures/general/floor-wood.jpg`
      )
      const plane = new THREE.Mesh(
        new THREE.BoxGeometry(200, 100, 0.1, 30),
        new THREE.MeshPhongMaterial({
          color: 0x3c3c3c,
          map: floorTex
        })
      )
      plane.position.y = -7.5
      plane.rotation.x = -0.5 * Math.PI
      this.scene.add(plane)
    },
    // 创建光源
    createLight() {
      // 环境光
      const ambientLight = new THREE.AmbientLight(0x242424, 0.1) // 创建环境光
      this.scene.add(ambientLight) // 将环境光添加到场景

      const spotLight = new THREE.SpotLight(0xffffff) // 创建聚光灯
      spotLight.position.set(0, 30, 30)
      spotLight.intensity = 1.2
      this.scene.add(spotLight)

      // 点光源
      const pointColor = '#ff5808'
      this.pointLight = new THREE.PointLight(pointColor)
      //this.pointLight.distance = 0
      //this.pointLight.intensity = 0.5
      this.scene.add(this.pointLight)

      this.createSmallSphereLight()
    },
    // 创建球形光源
    createSmallSphereLight() {
      const sphereLight = new THREE.SphereGeometry(0.2)
      const sphereLightMaterial = new THREE.MeshBasicMaterial({
        color: 0xac6c25
      })
      this.sphereLightMesh = new THREE.Mesh(sphereLight, sphereLightMaterial)
      this.sphereLightMesh.castShadow = true

      this.sphereLightMesh.position = new THREE.Vector3(3, 3, 3)
      this.scene.add(this.sphereLightMesh)
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById('container')
      const width = element.clientWidth // 窗口宽度
      const height = element.clientHeight // 窗口高度
      const k = width / height // 窗口宽高比
      // PerspectiveCamera( fov, aspect, near, far )
      this.camera = new THREE.PerspectiveCamera(45, k, 0.1, 1000)
      this.camera.position.set(0, 12, 38) // 设置相机位置

      this.camera.lookAt(new THREE.Vector3(0, 0, 0)) // 设置相机方向
      this.scene.add(this.camera)
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById('container')
      this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true })
      this.renderer.setSize(element.clientWidth, element.clientHeight) // 设置渲染区域尺寸
      this.renderer.shadowMap.enabled = true // 显示阴影
      // this.renderer.shadowMap.type = THREE.PCFSoftShadowMap
      this.renderer.setClearColor(0xeeeeee, 1) // 设置背景颜色
      element.appendChild(this.renderer.domElement)
    },

    propertiesChange() {
      const publicPath = process.env.BASE_URL

      // 更新物体表面纹理贴图
      const texture = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` + this.properties.textureType + '.jpg'
      )
      this.cube1.material.map = texture
      this.cube2.material.map = texture

      // 更新法向贴图
      const normal = new THREE.TextureLoader().load(
        `${publicPath}textures/general/` +
          this.properties.textureType +
          '-normal.jpg'
      )
      this.cube2.material.normalMap = normal

      // 更新法向贴图的凹凸程度
      this.cube2.material.normalScale.set(
        this.properties.normalScale.value,
        this.properties.normalScale.value
      ) // normalScale(x,y)
    },

    updateRotation() {
      if (this.properties.rotate) {
        this.cube1.rotation.y += 0.01
        this.cube2.rotation.y -= 0.01
      }
    },
    //球形点光源动画函数
    smallShpereLightAnimation() {
      if (this.phase > 2 * Math.PI) {
        this.invert = this.invert * -1
        this.phase -= 2 * Math.PI
      } else {
        this.phase += 0.03
      }

      this.sphereLightMesh.position.z = +(21 * Math.sin(this.phase))
      this.sphereLightMesh.position.x = -14 + 14 * Math.cos(this.phase)

      if (this.invert < 0) {
        const pivot = 0
        this.sphereLightMesh.position.x =
          this.invert * (this.sphereLightMesh.position.x - pivot) + pivot
      }

      this.pointLight.position.copy(this.sphereLightMesh.position) // 把小球光源的坐标复制给点光源
    },

    render() {
      this.smallShpereLightAnimation()
      this.updateRotation()
      this.renderer.render(this.scene, this.camera)
      requestAnimationFrame(this.render)
    },
    // 创建控件对象
    createControls() {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    }
  }
}
</script>

<style>
#container {
  position: absolute;
  width: 100%;
  height: 100%;
}
.controls-box {
  position: absolute;
  right: 5px;
  top: 5px;
  width: 300px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #c3c3c3;
}
.label-col {
  padding: 8px 5px;
}

.vertice-span {
  line-height: 38px;
  padding: 0 2px 0 10px;
}
</style>

评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值