Skip to content

webgl_raycaster_bvh

对应 three.js 示例地址

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

js
import * as THREE from "three";
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast, MeshBVHHelper } from "three-mesh-bvh";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_raycaster_bvh",
  useLoaders: [FBXLoader],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "raycaster -"
      },
      {
        tag: "a",
        link: "https://github.com/gkjohnson/three-mesh-bvh",
        content: "three-mesh-bvh"
      }
    ],
    [
      {
        tag: "text",
        content: "See"
      },
      {
        tag: "a",
        link: "https://github.com/gkjohnson/three-mesh-bvh",
        content: "main project repository"
      },
      {
        tag: "text",
        content: "for more information and examples on high performance spatial queries."
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
    THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
    THREE.Mesh.prototype.raycast = acceleratedRaycast;
    let stats;
    let camera, scene, renderer;
    let mesh, helper, bvh;
    let sphereInstance, lineSegments;
    const _raycaster = new THREE.Raycaster();
    const _position = new THREE.Vector3();
    const _quaternion = new THREE.Quaternion();
    const _scale = new THREE.Vector3(1, 1, 1);
    const _matrix = new THREE.Matrix4();
    const _axis = new THREE.Vector3();
    const MAX_RAYS = 3e3;
    const RAY_COLOR = 4473924;
    const params = {
      count: 150,
      firstHitOnly: true,
      useBVH: true,
      displayHelper: false,
      helperDepth: 10
    };
    init();
    function init() {
      camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 100);
      camera.position.z = 10;
      scene = new THREE.Scene();
      scene.background = new THREE.Color(15658734);
      const ambient = new THREE.HemisphereLight(16777215, 10066329, 3);
      scene.add(ambient);
      renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setAnimationLoop(animate);
      stats = new Stats(renderer);
      const lineGeometry = new THREE.BufferGeometry();
      lineGeometry.setAttribute(
        "position",
        new THREE.BufferAttribute(new Float32Array(MAX_RAYS * 2 * 3), 3)
      );
      lineSegments = new THREE.LineSegments(
        lineGeometry,
        new THREE.LineBasicMaterial({
          color: RAY_COLOR,
          transparent: true,
          opacity: 0.25,
          depthWrite: false
        })
      );
      sphereInstance = new THREE.InstancedMesh(
        new THREE.SphereGeometry(),
        new THREE.MeshBasicMaterial({ color: RAY_COLOR }),
        2 * MAX_RAYS
      );
      sphereInstance.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
      sphereInstance.count = 0;
      scene.add(sphereInstance, lineSegments);
      const loader = new FBXLoader();
      loader.load("models/fbx/stanford-bunny.fbx", (object) => {
        mesh = object.children[0];
        const geometry = mesh.geometry;
        geometry.translate(0, 0.5 / 75e-4, 0);
        geometry.computeBoundsTree();
        bvh = geometry.boundsTree;
        if (!params.useBVH) {
          geometry.boundsTree = null;
        }
        scene.add(mesh);
        mesh.scale.setScalar(75e-4);
        helper = new MeshBVHHelper(mesh);
        helper.color.set(15277667);
        scene.add(helper);
      });
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.minDistance = 5;
      controls.maxDistance = 75;
      const gui = new GUI();
      const rayFolder = gui.addFolder("Raycasting");
      rayFolder.add(params, "count", 1, MAX_RAYS, 1);
      rayFolder.add(params, "firstHitOnly");
      rayFolder.add(params, "useBVH").onChange((v) => {
        mesh.geometry.boundsTree = v ? bvh : null;
      });
      const helperFolder = gui.addFolder("BVH Helper");
      helperFolder.add(params, "displayHelper");
      helperFolder.add(params, "helperDepth", 1, 20, 1).onChange((v) => {
        helper.depth = v;
        helper.update();
      });
      window.addEventListener("resize", onWindowResize);
      onWindowResize();
      initRays();
      needToDispose(renderer, scene, controls);
    }
    function initRays() {
      const position = new THREE.Vector3();
      const quaternion = new THREE.Quaternion();
      const scale = new THREE.Vector3(1, 1, 1);
      const matrix = new THREE.Matrix4();
      for (let i = 0; i < MAX_RAYS * 2; i++) {
        position.randomDirection().multiplyScalar(3.75);
        matrix.compose(position, quaternion, scale);
        sphereInstance.setMatrixAt(i, matrix);
      }
    }
    const startTime = Date.now();
    function updateRays() {
      if (!mesh) return;
      _raycaster.firstHitOnly = params.firstHitOnly;
      const rayCount = params.count;
      let lineNum = 0;
      for (let i = 0; i < rayCount; i++) {
        sphereInstance.getMatrixAt(i * 2, _matrix);
        _matrix.decompose(_position, _quaternion, _scale);
        const offset = 1e-4 * (Date.now() - startTime);
        _axis.set(Math.sin(i * 100 + offset), Math.cos(-i * 10 + offset), Math.sin(i * 1 + offset)).normalize();
        _position.applyAxisAngle(_axis, 1e-3);
        _scale.setScalar(0.02);
        _matrix.compose(_position, _quaternion, _scale);
        sphereInstance.setMatrixAt(i * 2, _matrix);
        _raycaster.ray.origin.copy(_position);
        _raycaster.ray.direction.copy(_position).multiplyScalar(-1).normalize();
        const hits = _raycaster.intersectObject(mesh);
        if (hits.length !== 0) {
          const hit = hits[0];
          const point = hit.point;
          _scale.setScalar(0.01);
          _matrix.compose(point, _quaternion, _scale);
          sphereInstance.setMatrixAt(i * 2 + 1, _matrix);
          lineSegments.geometry.attributes.position.setXYZ(
            lineNum++,
            _position.x,
            _position.y,
            _position.z
          );
          lineSegments.geometry.attributes.position.setXYZ(lineNum++, point.x, point.y, point.z);
        } else {
          sphereInstance.setMatrixAt(i * 2 + 1, _matrix);
          lineSegments.geometry.attributes.position.setXYZ(
            lineNum++,
            _position.x,
            _position.y,
            _position.z
          );
          lineSegments.geometry.attributes.position.setXYZ(lineNum++, 0, 0, 0);
        }
      }
      sphereInstance.count = rayCount * 2;
      sphereInstance.instanceMatrix.needsUpdate = true;
      lineSegments.geometry.setDrawRange(0, lineNum);
      lineSegments.geometry.attributes.position.needsUpdate = true;
    }
    function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }
    function animate() {
      render();
      stats.update();
    }
    function render() {
      if (helper) {
        helper.visible = params.displayHelper;
      }
      if (mesh) {
        mesh.rotation.y += 2e-3;
        mesh.updateMatrixWorld();
      }
      updateRays();
      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;