111 three.js下雨进阶版,面只旋转y轴朝向相机

07/23 12:34
阅读数 109

之前实现过,是利用的sprite永久朝向相机的特性实现的效果。但是这种效果对于雪还比较好,如果贴图修改成长条形的雨的话,从上往下看,就会有一种说不出的感觉,不真实。
而我也通过修改shader和自己拼接渲染数据,实现了一个比较简单的渲染效果。接下来讲解一下实现逻辑:

第一步,创建一个包围盒,来设置范围

      const box = new THREE.Box3(
        new THREE.Vector3(-2000, -2000, -2000),
        new THREE.Vector3(2000, 2000, 2000)
      );

第二步,创建一个默认材质,并修改材质的shader

这里简单的提一句,three.js的材质对象是生成webgl的原生的program的工具,内置的那些材质都有相应的字符串拼接组成。
相应的,我们也可以通过拼接的方式,修改材质的默认着色器代码,从而达到自己的需求。

      material = new THREE.MeshBasicMaterial({
        transparent: true,
        opacity:.8,
        map: new THREE.TextureLoader().load("./color.png"),
        depthWrite: false,
      });

      material.onBeforeCompile = function (shader, renderer) {
        const getFoot = `
            uniform float top;
            uniform float bottom;
            uniform float time;
            #include <common>
            float angle(float x, float y){
              return atan(y, x);
            }
            vec2 getFoot(vec2 camera,vec2 normal,vec2 pos){
                vec2 position;

                float distanceLen = distance(pos, normal);

                float a = angle(camera.x - normal.x, camera.y - normal.y);

                if(pos.x > normal.x){
                  a -= 0.785; 
                }
                else{
                  a += 0.785; 
                }

                position.x = cos(a) * distanceLen;
                position.y = sin(a) * distanceLen;
                
                return position + normal;
            }
            `;
        const begin_vertex = `
            vec2 foot = getFoot(vec2(cameraPosition.x, cameraPosition.z),  vec2(normal.x, normal.z), vec2(position.x, position.z));
            float height = top-bottom;
            float y = normal.y - bottom - height*time;
            if(y < 0.0) y += height;
            float ratio = (1.0 - y /height) * (1.0 - y /height);
            y = height * (1.0 - ratio);
            y += bottom;
            y += position.y - normal.y;
            vec3 transformed = vec3( foot.x, y, foot.y );
            // vec3 transformed = vec3( position );
            `;
        shader.vertexShader = shader.vertexShader.replace(
          "#include <common>",
          getFoot
        );
        shader.vertexShader = shader.vertexShader.replace(
          "#include <begin_vertex>",
          begin_vertex
        );

        shader.uniforms.cameraPosition = {
          value: new THREE.Vector3(0, 200, 0),
        };
        shader.uniforms.top = {
          value: 2000,
        };
        shader.uniforms.bottom = {
          value: -2000,
        };
        shader.uniforms.time = {
          value: 0,
        };
        material.uniforms = shader.uniforms;
      };

第三步,通过包围盒生成相应的渲染数据

由于MeshBasicMaterial材质不受光照影响,所以,我们直接在拼接数据时, 将normal值设置面片的中心,一个正方形的面片需要由两个三角形组成,也就是最少四个顶点完成。
主要的操作就在这里,这里生成的数据,会在shader里面计算获取到y轴都为零情况下,沿中心点旋转的角度,通过此角度再生成一下旋转后,顶点需要渲染的位置。

      var geometry = new THREE.BufferGeometry();

      const vertices = [];
      const normals = [];
      const uvs = [];
      const indices = [];

      for (let i = 0; i < 1000; i++) {
        const pos = new THREE.Vector3();
        pos.x = Math.random() * (box.max.x - box.min.x) + box.min.x;
        pos.y = Math.random() * (box.max.y - box.min.y) + box.min.y;
        pos.z = Math.random() * (box.max.z - box.min.z) + box.min.z;

        const height = (box.max.y - box.min.y) / 15;
        const width = height / 50;

        vertices.push(
          pos.x + width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y - height / 2,
          pos.z,
          pos.x + width,
          pos.y - height / 2,
          pos.z
        );

        normals.push(
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z
        );

        uvs.push(1, 1, 0, 1, 0, 0, 1, 0);

        indices.push(
          i * 4 + 0,
          i * 4 + 1,
          i * 4 + 2,
          i * 4 + 0,
          i * 4 + 2,
          i * 4 + 3
        );
      }

      geometry.addAttribute(
        "position",
        new THREE.BufferAttribute(new Float32Array(vertices), 3)
      );
      geometry.addAttribute(
        "normal",
        new THREE.BufferAttribute(new Float32Array(normals), 3)
      );
      geometry.addAttribute(
        "uv",
        new THREE.BufferAttribute(new Float32Array(uvs), 2)
      );
      geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1));

第四步,在帧更新内,更新材质的uniform

    var time = 0;
    function render() {
      time = (time + clock.getDelta() * 0.2) % 1;

      // console.log(time);

      material.cameraPosition = camera.position;

      if (material.uniforms) {
        material.uniforms.cameraPosition.value = camera.position;
        material.uniforms.time.value = time;
      }

      renderer.render(scene, camera);
    }

最后一步,就设置一个变量,然后通过帧更新,更新雨点的位置,直接在shader里面计算简单方便。

接下来付上demo源码:


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
  </head>
  <body></body>
  <script src="../node_modules/three/build/three.js"></script>
  <script src="../node_modules/three/examples/js/controls/OrbitControls.js"></script>
  <script src="../node_modules/three/examples/js/libs/stats.min.js"></script>
  <script src="../node_modules/three/examples/js/libs/dat.gui.min.js"></script>
  <script>
    var camera, scene, renderer, stats, control, material;

    var sphere;

    var clock = new THREE.Clock();

    init();
    animate();

    function init() {
      camera = new THREE.PerspectiveCamera(
        40,
        window.innerWidth / window.innerHeight,
        1,
        15000
      );
      camera.position.z = 3000;

      scene = new THREE.Scene();
      scene.background = new THREE.Color(0x333333);
      
      const box = new THREE.Box3(
        new THREE.Vector3(-2000, -2000, -2000),
        new THREE.Vector3(2000, 2000, 2000)
      );

      material = new THREE.MeshBasicMaterial({
        transparent: true,
        opacity:.8,
        map: new THREE.TextureLoader().load("./color.png"),
        depthWrite: false,
      });

      material.onBeforeCompile = function (shader, renderer) {
        const getFoot = `
            uniform float top;
            uniform float bottom;
            uniform float time;
            #include <common>
            float angle(float x, float y){
              return atan(y, x);
            }
            vec2 getFoot(vec2 camera,vec2 normal,vec2 pos){
                vec2 position;

                float distanceLen = distance(pos, normal);

                float a = angle(camera.x - normal.x, camera.y - normal.y);

                if(pos.x > normal.x){
                  a -= 0.785; 
                }
                else{
                  a += 0.785; 
                }

                position.x = cos(a) * distanceLen;
                position.y = sin(a) * distanceLen;
                
                return position + normal;
            }
            `;
        const begin_vertex = `
            vec2 foot = getFoot(vec2(cameraPosition.x, cameraPosition.z),  vec2(normal.x, normal.z), vec2(position.x, position.z));
            float height = top-bottom;
            float y = normal.y - bottom - height*time;
            if(y < 0.0) y += height;
            float ratio = (1.0 - y /height) * (1.0 - y /height);
            y = height * (1.0 - ratio);
            y += bottom;
            y += position.y - normal.y;
            vec3 transformed = vec3( foot.x, y, foot.y );
            // vec3 transformed = vec3( position );
            `;
        shader.vertexShader = shader.vertexShader.replace(
          "#include <common>",
          getFoot
        );
        shader.vertexShader = shader.vertexShader.replace(
          "#include <begin_vertex>",
          begin_vertex
        );

        shader.uniforms.cameraPosition = {
          value: new THREE.Vector3(0, 200, 0),
        };
        shader.uniforms.top = {
          value: 2000,
        };
        shader.uniforms.bottom = {
          value: -2000,
        };
        shader.uniforms.time = {
          value: 0,
        };
        material.uniforms = shader.uniforms;
      };

      var geometry = new THREE.BufferGeometry();

      const vertices = [];
      const normals = [];
      const uvs = [];
      const indices = [];

      for (let i = 0; i < 1000; i++) {
        const pos = new THREE.Vector3();
        pos.x = Math.random() * (box.max.x - box.min.x) + box.min.x;
        pos.y = Math.random() * (box.max.y - box.min.y) + box.min.y;
        pos.z = Math.random() * (box.max.z - box.min.z) + box.min.z;

        const height = (box.max.y - box.min.y) / 15;
        const width = height / 50;

        vertices.push(
          pos.x + width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y + height / 2,
          pos.z,
          pos.x - width,
          pos.y - height / 2,
          pos.z,
          pos.x + width,
          pos.y - height / 2,
          pos.z
        );

        normals.push(
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z,
          pos.x,
          pos.y,
          pos.z
        );

        uvs.push(1, 1, 0, 1, 0, 0, 1, 0);

        indices.push(
          i * 4 + 0,
          i * 4 + 1,
          i * 4 + 2,
          i * 4 + 0,
          i * 4 + 2,
          i * 4 + 3
        );
      }

      geometry.addAttribute(
        "position",
        new THREE.BufferAttribute(new Float32Array(vertices), 3)
      );
      geometry.addAttribute(
        "normal",
        new THREE.BufferAttribute(new Float32Array(normals), 3)
      );
      geometry.addAttribute(
        "uv",
        new THREE.BufferAttribute(new Float32Array(uvs), 2)
      );
      geometry.setIndex(new THREE.BufferAttribute(new Uint32Array(indices), 1));

      scene.add(new THREE.Mesh(geometry, material));

      var axesHelper = new THREE.AxesHelper(500);
      scene.add(axesHelper);

      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      stats = new Stats();
      document.body.appendChild(stats.dom);

      control = new THREE.OrbitControls(camera, renderer.domElement);

      window.addEventListener("resize", onWindowResize, false);
    }

    function onWindowResize() {
      windowHalfX = window.innerWidth / 2;
      windowHalfY = window.innerHeight / 2;

      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();

      renderer.setSize(window.innerWidth, window.innerHeight);
    }

    //

    function animate() {
      requestAnimationFrame(animate);

      render();
      stats.update();
    }

    var time = 0;
    function render() {
      time = (time + clock.getDelta() * 0.2) % 1;

      // console.log(time);

      material.cameraPosition = camera.position;

      if (material.uniforms) {
        material.uniforms.cameraPosition.value = camera.position;
        material.uniforms.time.value = time;
      }

      renderer.render(scene, camera);
    }
  </script>
</html>

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部