three.js study notes (1): The use of five basic materials of THREE.Materail

  • MeshBasicMaterial (mesh basic material): basic material, used to give a simple color to the geometry, or to display the wireframe of the geometry.
  • MeshDepthMaterial: This material uses the distance from the camera to the mesh to determine how to color the mesh.
  • MeshLambertMaterial (mesh Lambert material): This is a material that takes into account lighting effects and is used to create dark, non-lit objects.
  • MeshNormalMaterial (mesh normal material): This is a simple material that calculates the color of the object's surface based on the normal vector.
  • MeshPhongMaterial (grid Phong-style material): This is a material that takes light into account and is used to create shiny objects.

1. Common properties of materials

three.js provides an abstract base class for THREE.Materail material, and all other material types inherit the following properties and methods:

1. Basic attributes

  • id (identifier): The unique number of this material instance, and is assigned when the material is created. The value starts at 0 for the first material and increases by 1 for each new material added.

  • uuid (Universally Unique Identifier): This is a unique ID generated and used internally.

  • name (name): This property can be used to give the material a name for debugging purposes.

  • opacity (opacity): defines the transparency of the object. Used with the transparent attribute. The value assigned to this attribute ranges from 0 to 1.

  • Transparent (whether transparent): Define whether this material is transparent, and the degree of transparency can be controlled through the opacity attribute.

    • The default value is false, so if you need to do transparent rendering, you need to set transparent to true.

    • If using an alpha (transparency) channel texture, this property should be set to true.

  • overdraw (overdraw): When you use THREE.CanvasRender, the polygon will be rendered slightly larger. This property can be set to true when objects rendered with this renderer have gaps.

  • visible (visible): defines whether the material is visible. The default is true, if set to false, the object will not be visible in the scene.

  • side (side): Through this property, you can define which side of the geometry to render.

    • The default is THREE.FrontSide (front), which defines the front (outside) side of the material that will be rendered.

    • Set to THREE.BackSide (back) to define the back (inner side) where the material will be rendered.

    • Set to THREE.DoubleSide to define the inner and outer sides of the material that will be rendered.

  • needsUpdate (whether to update): For some modifications of the material, it is necessary to tell Three.js that the material has changed. If this property is set to true, Three.js will update its cache with the new material properties.

There are three points to pay attention to during use:

(1) opacity and transparent need to be used together. When transparent is true, opacity will work. The following example demonstrates;

// 创建材质
let color = new THREE.Color(Math.random(), Math.random(), Math.random())
// 未向材质中添加 transparent 属性
const material = new THREE.MeshBasicMaterial({
  color: color,
  opacity: 0.5,
})  

// 创建材质
let color = new THREE.Color(Math.random(), Math.random(), Math.random())
// 向材质中添加 transparent 属性
const material = new THREE.MeshBasicMaterial({
  color: color,
  transparent: true,
  opacity: 0.5,
})  

(2) When the properties of the material change, you need to set needsUpdate (specifying that the material needs to be recompiled) to true to trigger the rendering update of the material. 

window.addEventListener('click', e => {
  // 当鼠标移动的时候播放视频
  // 判断视频是否属于播放状态
  if (video.paused) {
    this.$nextTick(res => {
      video.load()
      video.play()
    })
    let texture = new THREE.VideoTexture(video)
    skyMaterial.map = texture
    skyMaterial.map.needsUpdate = true
  }
})

(3) side determines which face to draw, or both faces to draw

material.side = THREE.DonbleSide
// 或者
const material = new THREE.MeshStandardMaterial({
  side: DonbleSide,
})

2. Fusion attribute

  • blending: This property determines how the material on the object blends with the background. The general blending mode is THREE.NormalBlending, in which only the upper layer of the material is displayed.

  • blendSrc (blend source):

    • In addition to using the standard blend modes, you can also create custom blend modes by setting blendsrc, blenddst, and blendequation.

    • This property defines how the object (source) blends with the background (target). The default value is THREE.SrcAlphaFactor, that is, use the alpha (transparency) channel for fusion.

  • blendDst (blending target): This attribute defines how to use the background (target) when merging. The default value is THREE.OneMinusSrcAlphaFactor, which means that the target also uses the source's alpha channel for fusion, but the value used is 1 (the source's alpha channel value), the blending of the material must be set to CustomBlending to take effect.

  • blendEquation (blending formula): defines how to use the values ​​of blendsrc and blenddst. The default is to add them up (AddEquation). By using these three properties, custom fusion modes can be created.

3. Advanced attributes

  • depthTest / depthWrite: When drawing opaque objects, turning on the depth test can ensure the correct occlusion relationship. When drawing transparent objects, turning off the depth test can ensure the correct blend.

  • polygonOffset / polygonOffsetFactor / polygonOffsetUnits

  • alphatest: If a pixel is smaller than this value, it will not be displayed.

2. Description of various materials

1. THREE.MeshBasicMaterial (mesh basic material):

  • Definition: MeshBasicMaterial is a relatively simple material

  • Features: This material is not affected by lighting, and can render basic planes or geometry without considering the impact of lighting.

(1) Attribute introduction

  • color (color): the color of the material, the default value is white (0xffffff). The material color property can be changed by this.cube.material.color.set(value)

  • xxxMap (texture map): demo10

  • wireframe (wireframe): The default value is false (that is, rendered as a flat polygon), setting this property can render the material as a wireframe.

  • wireframeLinewidth (wireframe line width): If the wireframe has been opened, this property defines the width of the line in the wireframe.

  • wireframeLinecap (wireframe segment endpoints): Defines the appearance of the ends of the line

    • round (default): round

    • square: direction

    • butt: flat

  • wireframeLinejoin: This property defines how the join points of line segments are displayed. Possible values ​​are:

    • round: round (default)

    • bevel: bevel

    • miter: sharp corner

  • shading (coloring): This attribute defines how to shade. Possible values ​​are:

    • THREE.SmoothShading (default, this will produce a smooth object with no individual faces visible)

    • THREE.NoShading

    • THREE. FlatShading

  • vertexColors (vertex colors)

    • Different colors can be defined for each vertex through this property. Default: THREE.NoColors. If this value is set to THREE.VertexColors, the renderer will use the value of the colors property of the THREE.Geometry object.

    • This property has no effect on CanvasRenderer, but it does work on WebGLRender. For example, we can use this property to set different colors for different parts of the line segment. You can also use this property to create gradient effects for this material type.

  • fog (atomization): This attribute specifies whether the current material is affected by the global fog effect setting, and the default is true. If this property is set to false, then our global fog effect settings will not affect the rendering of the current object.

(2) The texture map contained in the material:

  • map: Color map.

  • aoMap: The red channel of this texture is used as an ambient occlusion map, aoMap requires a second set of UVs.

  • envMap: Environment map.

  • lightMap: Lightmap, lightMap requires a second set of UVs.

  • alphaMap: The alpha map is a grayscale texture used to control the opacity of the entire surface. (black: completely transparent; white: completely opaque).

  • specularMap: The specular map used by the material.

(3) Example of use:

Example 1: Color texture map

// 导入纹理
// TextureLoader创建一个纹理加载器对象,可以加载图片作为几何体纹理
const textureLoader = new THREE.TextureLoader()
// 执行load方法,加载纹理贴图成功后,返回一个纹理对象Texture
const picTexture = textureLoader.load('./static/images/detail1.jpg')

// 添加物体:纹理贴图映射到一个矩形平面上
const cubeGeometry = new THREE.BoxBufferGeometry(1, 1, 1)

// 设置材质
const material = new THREE.MeshBasicMaterial({
  color: '#dda0dd',
  // 添加纹理贴图
  map: picTexture,
  transparent: true,
  opacity: 0.5,
  side: THREE.DoubleSide,
})
this.cube = new THREE.Mesh(cubeGeometry, material)
// 将物体添加到场景中
this.scene.add(this.cube)

Example 2: Basic example

// 添加物体
// 创建几何体
const geometry = new THREE.BoxGeometry(1, 1, 1)
// 创建材质
const material = new THREE.MeshBasicMaterial({ color: '#dda0dd' })
// 根据几何体和材质创建物体
this.cube = new THREE.Mesh(geometry, material)
// 将几何体添加到场景中
this.scene.add(this.cube)

// 创建 GUI
const gui = new dat.GUI()
gui
  .add(this.cube.position, 'x')
  .min(0)
  .max(5)
  .step(0.01)
  .name('移动x轴')
  .onChange(value => {
     console.log('值被修改了')
  })
  .onFinishChange(value => {
    console.log('完全停下来')
  })
// 修改物体的颜色
const params = {
  color: '#dda0dd',
  fn: () => {
    // 让立方体运动起来
    gsap.to(this.cube.position, { x: 10, duration: 2, yoyo: true, repeat: -1 })
  },
}

// 设置选项框
gui.add(this.cube, 'visible').name('是否显示')
// 点击触发某个事件
gui.add(params, 'fn').name('点击立方体运动')
// 添加文件夹(折叠选项)
let folder = gui.addFolder('设置立方体')
folder.add(this.cube.material, 'wireframe')
  folder
  .addColor(params, 'color')
  .onChange(value => {
    this.cube.material.color.set(value)
  })
  .name('修改颜色')

2. THREE.MeshDepthMaterial (mesh depth material):

A material that draws geometry by depth. Depth is based on the camera near and far planes. White is closest and black is farthest. The appearance of an object using this material is not determined by lighting or a material property, but by the distance from the object to the camera. We can combine this material with other materials to easily create fading effects.

(1) Attribute introduction:

  •  wireframe (wireframe): Setting this property renders the material as a wireframe, very useful for debugging.
  • wireframeLinewidth: In wireframe mode, this property determines the width of the wireframe.

(2) The texture map contained in the material:

  • map: Color map.
  • alphaMap: The alpha map is a grayscale texture used to control the opacity of the entire surface. (black: completely transparent; white: completely opaque).
  • displacementMap: The displacement map affects the position of the vertices of the mesh. Unlike other maps that only affect the lighting and shadows of the material, the displaced vertices can cast shadows, block other objects, and act as real geometry. You can adjust the influence of the displacement map on the grid by setting the displacementScale size.

(3) Example of use:

	this.scene = new THREE.Scene()
    this.scene.overrideMaterial = new THREE.MeshDepthMaterial()	

	// 环境光
	const ambientLight = new THREE.AmbientLight(0xffffff, 0.1) // 创建环境光
	this.scene.add(ambientLight) // 将环境光添加到场景

    addCube() {
      const cubeSize = Math.ceil(3 + Math.random() * 3)
      const cubeGeometry = new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize)

      const cubeMaterial = new THREE.MeshLambertMaterial({
        color: 0xffffff,
      })

      this.cube = new THREE.Mesh(cubeGeometry, cubeMaterial)

      this.cube.castShadow = true
      this.cube.updateMatrix()

      // 设置方块位置
      this.cube.position.x = -50 + Math.round(Math.random() * 150)
      this.cube.position.y = Math.round(Math.random() * 10)
      this.cube.position.z = -150 + Math.round(Math.random() * 250)

      // 将方块添加到场景
      this.scene.add(this.cube)
    },

    // 更新属性
    updateFun() {
      this.camera.near = this.properties.near.value
      this.camera.far = this.properties.far.value

      this.camera.updateProjectionMatrix()
      const THIS = this
      THIS.scene.traverse(function (e) {
        if (e instanceof THREE.Mesh) {
          e.rotation.x += THIS.properties.speed.value
          e.rotation.y += THIS.properties.speed.value
          e.rotation.z += THIS.properties.speed.value
        }
      })
    },

 

As can be seen from the picture above, the brightness of far and near is different. Adjust the near and far values ​​of the camera through the gui-related data in the upper right corner.

Pay special attention to the following places:

  • Set the transparent property of THREE.MeshBasicMaterial to true and specify a fusion mode. Otherwise THREE.js will not perform any fusion operations and the square will never be solid green.
  • Blending mode THREE.MultiplyBlending is used here, which multiplies the foreground color and background color to get the desired result.
  • When the THREE.SceneUtils.createMultiMaterialObject() method creates a mesh, the geometry is duplicated, returning a mesh group (two meshes inside are identical). When one of the rendered objects is on top of another object and one of the objects is transparent, there will be screen flickering problems during rendering. Here we can avoid this behavior by shrinking the mesh with THREE.MeshDepthMaterial material.

3. THREE.MeshNormalMaterial (normal mesh material)

A material that maps normal vectors to RGB colors. With this material, the color of each face is computed from the normal vector pointing out from that face.

(1) Attribute introduction:

  • wireframe (wireframe)
  • wireframeLinewidth (wireframe line width)
  • shading (shading method)
  • THREE.FlatShading: flat shading
  • THREE.SmoothShading: smooth shading

(2) The texture map contained in the material:

  • bumpMap: The texture used to create the bump map.
  • normalMap: The type of normal map.
  • displacementMap: The displacement map affects the position of the vertices of the mesh. Unlike other maps that only affect the lighting and shadows of the material, the displaced vertices can cast shadows, block other objects, and act as real geometry. You can adjust the influence of the displacement map on the grid by setting the displacementScale size.

(3) Example of use:

// 创建法向量纹理
var meshMaterial = new THREE.MeshNormalMaterial({
  flatShading: THREE.FlatShading,
  transparent: true,
  opacity: 0.7
});

4. THREE.MeshLambertMaterial (grid Lambert material)

  • Definition: A material with a matte surface, without specular highlights.
  • Features:
    • For use on dull, matte surfaces and will react to light sources.
    • For use on dull, matte surfaces and will react to light sources.
    • This material can be used to create dull, non-shiny surfaces.
    • This simulates some surfaces well (such as untreated wood or stone), but not glossy surfaces with specular highlights (such as painted wood).

(1) Attribute introduction

  • ambient: This is the ambient color of the material. It is used in conjunction with the ambient light source described in the previous chapter. This color is multiplied with the color provided by the ambient light. The default is white.
  • emissive: This is the color of the material's emissive. It's not really like a light source, just a pure color unaffected by other lights. The default is black.
  • wrapAround: If this property is set to true, the semi-lambert lighting technique is enabled. With it, the light falls more subtly. If the mesh has rough, dark areas, enabling this property will soften the shadows and make the unevenness more uniform.
  • wrapRGB: When the wrapAround property is set to true, you can use THREE.Vector3 to control the speed of light fall.

There are two more important attributes here: ambient (environmental color) and emissive (emissive)

  • ambient is used with the AmbientLight light source, this color will be multiplied by the color of the AmbientLight light source; the default is white.

(2) The texture map contained in the material:

  • bumpMap: The texture used to create the bump map.
  • alphaMap: The alpha map is a grayscale texture used to control the opacity of the entire surface. (black: completely transparent; white: completely opaque).
  • displacementMap: The displacement map affects the position of the vertices of the mesh. Unlike other maps that only affect the lighting and shadows of the material, the displaced vertices can cast shadows, block other objects, and act as real geometry. You can adjust the influence of the displacement map on the grid by setting the displacementScale size.
  • emissiveMap: Sets the emissive (luminous) map.
  • envMap: Environment map.
  • lightMap: Lightmap, lightMap requires a second set of UVs.
  • normalMap: The type of normal map.
  • specularMap: The specular map used by the material.

(3) Example of use

      // 创建网格模型
      const planeMaterial = new THREE.MeshLambertMaterial({
        color: 0x777777,
      }) // 材质对象Material
      const plane = new THREE.Mesh(geometry, planeMaterial)
      plane.receiveShadow = true

      // 设置平面位置
      plane.rotation.x = -0.5 * Math.PI
      plane.position.set(0, -20, 0)

      // 平面对象添加到场景中
      this.scene.add(plane)

      const sphereGeometry = new THREE.SphereGeometry(14, 20, 20)
      const cubeGeometry = new THREE.BoxGeometry(15, 15, 15)
      const planeGeometry = new THREE.PlaneGeometry(14, 14, 4, 4)

      // 创建材质
      this.meshMaterial = new THREE.MeshLambertMaterial({
        color: 0x7777ff,
      })

      // 创建球、方块、平面
      this.sphere = new THREE.Mesh(sphereGeometry, this.meshMaterial)
      this.cube = new THREE.Mesh(cubeGeometry, this.meshMaterial)
      this.plane = new THREE.Mesh(planeGeometry, this.meshMaterial)

      this.sphere.position.set(-12, 3, 2)
      this.cube.position = this.sphere.position
      this.plane.position = this.sphere.position
      this.activeMesh = this.sphere
   
      // 环境光
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.1) // 创建环境光
      this.scene.add(ambientLight) // 将环境光添加到场景

      const spotLight = new THREE.SpotLight(0xffffff) // 创建聚光灯
      spotLight.position.set(-40, 60, -10)
      this.scene.add(spotLight)

5. THREE.MeshPhongMaterial (grid Phong material)

THREE.MeshPhongMaterial can create a material with a glossy surface with specular highlights.

(1) Attribute introduction

  • ambient: This is the ambient color of the material. It is used in conjunction with the ambient light source described in the previous chapter. This color is multiplied with the color provided by the ambient light. The default is white.
  • emissive: This is the color of the material's emissive. It's not really like a light source, just a pure color unaffected by other lights. The default is black.
  • wrapAround: If this property is set to true, the semi-lambert lighting technique is enabled. With it, the light falls more subtly. If the mesh has rough, dark areas, enabling this property will soften the shadows and make the unevenness more uniform.
  • wrapRGB: When the wrapAround property is set to true, you can use THREE.Vector3 to control the speed of light fall.
  • Specular: This attribute specifies the brightness of the material and the color of the highlight.
    • If you set it to the same color as the color property, you'll get a more metallic-like material.
    • If you set it to gray, the material will become more like plastic.
  • shininess: This attribute specifies the brightness of the specular highlight. Default value: 30.
  • metal: If this property is set to true, Three.js calculates the color of pixels in a slightly different way to make objects look more like metal. Note that this effect is very small.

 (2) The texture map contained in the material:

  • bumpMap: The texture used to create the bump map.
  • alphaMap: The alpha map is a grayscale texture used to control the opacity of the entire surface. (black: completely transparent; white: completely opaque).
  • aoMap: The red channel of this texture is used as an ambient occlusion map, aoMap requires a second set of UVs.
  • displacementMap: The displacement map affects the position of the vertices of the mesh. Unlike other maps that only affect the lighting and shadows of the material, the displaced vertices can cast shadows, block other objects, and act as real geometry. You can adjust the influence of the displacement map on the grid by setting the displacementScale size.
  • emissiveMap: Sets the emissive (luminous) map.
  • envMap: Environment map.
  • lightMap: Lightmap, lightMap requires a second set of UVs.
  • normalMap: The type of normal map.
  • specularMap: The specular map used by the material.

(3) Detailed examples of use

A light source (ambient light and point light) for the instance object, and create a small ball with this material. It can be seen that this material looks brighter.

// 创建球体
const loader = new THREE.TextureLoader();
const geometry = new THREE.SphereGeometry(50, 128, 128);
// 定义地球材质
const texture = loader.load('./static/images/earth_atmos_4096.jpg');
// 添加浮雕凹凸贴图
const bump = loader.load('./static/images/earth_bump.jpg');
// 添加高光贴图
const spec = loader.load('./static/images/earth_specular_2048.jpg');
// 创建材质
const material = new THREE.MeshPhongMaterial({
  map: texture,
  bumpMap: bump,
  bumpScale: 5,
  specularMap: spec,
  specular: new THREE.Color('#1a2948'),
  shininess: 2
});
const mesh = new THREE.Mesh(geometry, material);
mesh.name = 'earth';
// 添加地球到场景
this.scene.add(mesh);

// 添加光源
const ambientLight = new THREE.AmbientLight(0x999999);
const pointLight = new THREE.PointLight(0xffffff, 1, 200);
pointLight.position.set(0, 100, 0);
this.scene.add(ambientLight, pointLight);

 

Guess you like

Origin blog.csdn.net/qq_43641110/article/details/128971908