Skip to content

webgl_mesh_batch

对应 three.js 示例地址

仅需关注 init 函数的内容,其他部分都是示例小程序所使用的描述配置。

js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { radixSort } from "three/examples/jsm/utils/SortUtils.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_mesh_batch",
  useLoaders: [],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "webgl - mesh - batch"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let stats, gui;
    let camera, controls, scene, renderer;
    let geometries, mesh, material;
    const ids = [];
    const matrix = new THREE.Matrix4();
    const position = new THREE.Vector3();
    const rotation = new THREE.Euler();
    const quaternion = new THREE.Quaternion();
    const scale = new THREE.Vector3();
    const MAX_GEOMETRY_COUNT = 2e4;
    const Method = {
      BATCHED: "BATCHED",
      NAIVE: "NAIVE"
    };
    const api = {
      method: Method.BATCHED,
      count: 256,
      dynamic: 16,
      sortObjects: true,
      perObjectFrustumCulled: true,
      opacity: 1,
      useCustomSort: true
    };
    init();
    initGeometries();
    initMesh();
    function randomizeMatrix(matrix2) {
      position.x = Math.random() * 40 - 20;
      position.y = Math.random() * 40 - 20;
      position.z = Math.random() * 40 - 20;
      rotation.x = Math.random() * 2 * Math.PI;
      rotation.y = Math.random() * 2 * Math.PI;
      rotation.z = Math.random() * 2 * Math.PI;
      quaternion.setFromEuler(rotation);
      scale.x = scale.y = scale.z = 0.5 + Math.random() * 0.5;
      return matrix2.compose(position, quaternion, scale);
    }
    function randomizeRotationSpeed(rotation2) {
      rotation2.x = Math.random() * 0.01;
      rotation2.y = Math.random() * 0.01;
      rotation2.z = Math.random() * 0.01;
      return rotation2;
    }
    function initGeometries() {
      geometries = [
        new THREE.ConeGeometry(1, 2),
        new THREE.BoxGeometry(2, 2, 2),
        new THREE.SphereGeometry(1, 16, 8)
      ];
    }
    function createMaterial() {
      if (!material) {
        material = new THREE.MeshNormalMaterial();
      }
      return material;
    }
    function cleanup() {
      if (mesh) {
        mesh.parent.remove(mesh);
        if (mesh.dispose) {
          mesh.dispose();
        }
      }
    }
    function initMesh() {
      cleanup();
      if (api.method === Method.BATCHED) {
        initBatchedMesh();
      } else {
        initRegularMesh();
      }
    }
    function initRegularMesh() {
      mesh = new THREE.Group();
      const material2 = createMaterial();
      for (let i = 0; i < api.count; i++) {
        const child = new THREE.Mesh(geometries[i % geometries.length], material2);
        randomizeMatrix(child.matrix);
        child.matrix.decompose(child.position, child.quaternion, child.scale);
        child.userData.rotationSpeed = randomizeRotationSpeed(new THREE.Euler());
        mesh.add(child);
      }
      scene.add(mesh);
    }
    function initBatchedMesh() {
      const geometryCount = api.count;
      const vertexCount = geometries.length * 512;
      const indexCount = geometries.length * 1024;
      const euler = new THREE.Euler();
      const matrix2 = new THREE.Matrix4();
      mesh = new THREE.BatchedMesh(geometryCount, vertexCount, indexCount, createMaterial());
      mesh.userData.rotationSpeeds = [];
      mesh.frustumCulled = false;
      ids.length = 0;
      const geometryIds = [
        mesh.addGeometry(geometries[0]),
        mesh.addGeometry(geometries[1]),
        mesh.addGeometry(geometries[2])
      ];
      for (let i = 0; i < api.count; i++) {
        const id = mesh.addInstance(geometryIds[i % geometryIds.length]);
        mesh.setMatrixAt(id, randomizeMatrix(matrix2));
        const rotationMatrix = new THREE.Matrix4();
        rotationMatrix.makeRotationFromEuler(randomizeRotationSpeed(euler));
        mesh.userData.rotationSpeeds.push(rotationMatrix);
        ids.push(id);
      }
      scene.add(mesh);
    }
    function init() {
      const width = window.innerWidth;
      const height = window.innerHeight;
      camera = new THREE.PerspectiveCamera(70, width / height, 1, 100);
      camera.position.z = 30;
      renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(width, height);
      renderer.setAnimationLoop(animate);
      scene = new THREE.Scene();
      scene.background = new THREE.Color(16777215);
      controls = new OrbitControls(camera, renderer.domElement);
      controls.autoRotate = true;
      controls.autoRotateSpeed = 1;
      stats = new Stats(renderer);
      gui = new GUI();
      gui.add(api, "count", 1, MAX_GEOMETRY_COUNT).step(1).onChange(initMesh);
      gui.add(api, "dynamic", 0, MAX_GEOMETRY_COUNT).step(1);
      gui.add(api, "method", Method).onChange(initMesh);
      gui.add(api, "opacity", 0, 1).onChange((v) => {
        if (v < 1) {
          material.transparent = true;
          material.depthWrite = false;
        } else {
          material.transparent = false;
          material.depthWrite = true;
        }
        material.opacity = v;
        material.needsUpdate = true;
      });
      gui.add(api, "sortObjects");
      gui.add(api, "perObjectFrustumCulled");
      gui.add(api, "useCustomSort");
      window.addEventListener("resize", onWindowResize);
      needToDispose(renderer, scene, controls);
    }
    function sortFunction(list) {
      this._options = this._options || {
        get: (el) => el.z,
        aux: new Array(this.maxInstanceCount)
      };
      const options = this._options;
      options.reversed = this.material.transparent;
      let minZ = Infinity;
      let maxZ = -Infinity;
      for (let i = 0, l = list.length; i < l; i++) {
        const z = list[i].z;
        if (z > maxZ) maxZ = z;
        if (z < minZ) minZ = z;
      }
      const depthDelta = maxZ - minZ;
      const factor = (2 ** 32 - 1) / depthDelta;
      for (let i = 0, l = list.length; i < l; i++) {
        list[i].z -= minZ;
        list[i].z *= factor;
      }
      radixSort(list, options);
    }
    function onWindowResize() {
      const width = window.innerWidth;
      const height = window.innerHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      renderer.setSize(width, height);
    }
    function animate() {
      animateMeshes();
      controls.update();
      stats.update();
      render();
    }
    function animateMeshes() {
      const loopNum = Math.min(api.count, api.dynamic);
      if (api.method === Method.BATCHED) {
        for (let i = 0; i < loopNum; i++) {
          const rotationMatrix = mesh.userData.rotationSpeeds[i];
          const id = ids[i];
          mesh.getMatrixAt(id, matrix);
          matrix.multiply(rotationMatrix);
          mesh.setMatrixAt(id, matrix);
        }
      } else {
        for (let i = 0; i < loopNum; i++) {
          const child = mesh.children[i];
          const rotationSpeed = child.userData.rotationSpeed;
          child.rotation.set(
            child.rotation.x + rotationSpeed.x,
            child.rotation.y + rotationSpeed.y,
            child.rotation.z + rotationSpeed.z
          );
        }
      }
    }
    function render() {
      if (mesh.isBatchedMesh) {
        mesh.sortObjects = api.sortObjects;
        mesh.perObjectFrustumCulled = api.perObjectFrustumCulled;
        mesh.setCustomSort(api.useCustomSort ? sortFunction : null);
      }
      renderer.render(scene, camera);
    }
  }
};
export {
  exampleInfo as default
};
ts
import { Loader, TypedArray } from 'three';
/**
 * 官网示例的多端使用封装把版本
 * */
export interface OfficialExampleInfo extends MiniProgramMeta {
  /*** 示例名称(保持和官网一致)*/
  name: string;
  /** main */
  init: (context: LoadContext) => void;
}

export interface LoadContext {
  //为了减少官方代码的改动,实际上等同于 canvas
  window: EventTarget & { innerWidth: number; innerHeight: number; devicePixelRatio: number };
  /** HTMLCanvasElement */
  canvas: any;
  /** https://www.npmjs.com/package/lil-gui */
  GUI: any;
  /**
   * https://www.npmjs.com/package/stats.js
   * 也可以使用其他受支持的版本
   * */
  Stats: any;
  /** 收集需要 dispose 的对象(官方示例没有处理这部分)*/
  needToDispose: (...objs: any[]) => void | ((fromFn: () => any[]) => void);

  /**基于 raq 的通用封装 */
  useFrame(animateFunc: (/** ms */ delta: number) => void): { cancel: () => void };

  /** 显示加载模态框 */
  requestLoading(text?: string): Promise<void>;

  /** 隐藏加载模态框*/
  cancelLoading(): void;

  /** 保存文件的通用封装*/
  saveFile(
    fileName: string,
    data: ArrayBuffer | TypedArray | DataView | string
  ): Promise<string | null>;

  /** 示例使用 DracoDecoder 时的资源路径 */
  DecoderPath: {
    GLTF: string;
    STANDARD: string;
  };

  /** 为资源路径拼上 CDN 前缀 */
  withCDNPrefix(path: string): string;

  /**
   * 在小程序中应使用 import { VideoTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/VideoTexture.js';
   * 正常情况(web) 可直接使用 THREE.VideoTexture
   * */
  getVideoTexture(videoOptions: VideoOptions): Promise<[{ isVideoTexture: true }, video: any]>;

  /**
   * 在小程序中应使用 import { CameraTexture } from '@minisheep/three-platform-adapter/override/jsm/textures/CameraTexture.js';
   * 正常情况(web) 可参考示例 webgl_materials_video_webcam
   * */
  getCameraTexture(): { isVideoTexture: true };

  /** 用于动态修改 info 中的占位符*/
  bindInfoText(template: `$${string}$`, initValue?: string): { value: string };

  /** 分屏控件对应的事件回调 */
  onSlideStart(handle: () => void): void;
  /** 分屏控件对应的事件回调 */
  onSlideEnd(handle: () => void): void;
  /** 分屏控件对应的事件回调 */
  onSlideChange(handle: (offset: number, boxSize: number) => void): void;
}

export type VideoOptions = {
  src: string;
  /** 相当于 HTMLVideoElement 的 naturalWidth (小程序中获取不到)*/
  width: number;
  /** 相当于 HTMLVideoElement 的 naturalHeight (小程序中获取不到)*/
  height: number;
  loop?: boolean;
  autoplay?: boolean;
  muted?: boolean;
};

/** 示例小程序中使用的一些配置 */
export interface MiniProgramMeta {
  /** 用于统计加载相关信息 */
  useLoaders: Loader[];
  /** 通用 info */
  info: TagItem[][];
  /** 特殊 info */
  infoPanel?: {
    left?: [string, string][];
    right?: [string, string][];
  };
  /** 分屏控件配置 */
  needSlider?: {
    /** 方向 */
    direction?: 'horizontal' | 'vertical';
    /** 初始偏移 0-100 */
    initPosition?: number;
  };
  /** 操作摇杆控件 */
  needArrowControls?: boolean;
  /** 默认需要的画布类型 */
  canvasType?: '2d' | 'webgl' | 'webgl2';
  /** 为保持效果一致所需要的画布样式 */
  canvasStyle?: {
    bgColor?: string;
    width?: number | string;
    height?: number | string;
  };
  /** 部分示例需要在加载前进行一些提示 */
  initAfterConfirm?: {
    /**
     * 提示类型
     * @default 'default'
     * */
    type?: 'warning' | 'default';
    text: string[];
  };
}

export interface BaseTag<T extends string> {
  tag: T;
  content: string;
}

export interface ATag extends BaseTag<'a'> {
  link: string;
}

export type TextTag = BaseTag<'text'>;

export type TagItem = TextTag | ATag;