使用vue学习three.js之加载和使用纹理-设置material.normalMap属性使用法向贴图创建表面不同凹凸程度的三维物体

Posted 点燃火柴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用vue学习three.js之加载和使用纹理-设置material.normalMap属性使用法向贴图创建表面不同凹凸程度的三维物体相关的知识,希望对你有一定的参考价值。

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以上是关于使用vue学习three.js之加载和使用纹理-设置material.normalMap属性使用法向贴图创建表面不同凹凸程度的三维物体的主要内容,如果未能解决你的问题,请参考以下文章

使用vue学习three.js之加载和使用纹理-用视频输出作为纹理,使用VideoTexture视频纹理实现物体表面播放视频

使用vue学习three.js之加载和使用纹理- 通过设置纹理的wrapSwrapTrepeat属性实现纹理的重复平铺,纹理的重复映射

使用vue学习three.js之加载和使用纹理-使用canvas画布上的绘画作为纹理渲染到方块上,使用动态绘画纹理

使用vue学习three.js之加载和使用纹理-设置material.bumpMap属性使用凹凸贴图创建皱纹

使用vue学习three.js之加载和使用纹理-在canvas画布上生成噪音图,然后创建凹凸贴图

使用vue学习three.js之加载和使用纹理-使用CubeCamera创建反光效果,动态环境贴图实现,立方体全景贴图