Skip to content

webgl_postprocessing_outline

对应 three.js 示例地址

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

js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
import { ShaderPass } from "three/examples/jsm/postprocessing/ShaderPass.js";
import { OutlinePass } from "three/examples/jsm/postprocessing/OutlinePass.js";
import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";
import { FXAAShader } from "three/examples/jsm/shaders/FXAAShader.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_postprocessing_outline",
  useLoaders: [OBJLoader],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "- Outline Pass by"
      },
      {
        tag: "a",
        link: "http://eduperiment.com",
        content: "Prashant Sharma"
      },
      {
        tag: "text",
        content: "and"
      },
      {
        tag: "a",
        link: "https://clara.io",
        content: "Ben Houston"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let stats;
    let camera, scene, renderer, controls;
    let composer, effectFXAA, outlinePass;
    let selectedObjects = [];
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();
    const obj3d = new THREE.Object3D();
    const group = new THREE.Group();
    const params = {
      edgeStrength: 3,
      edgeGlow: 0,
      edgeThickness: 1,
      pulsePeriod: 0,
      rotate: false,
      usePatternTexture: false
    };
    const gui = new GUI({ width: 280 });
    gui.add(params, "edgeStrength", 0.01, 10).onChange(function(value) {
      outlinePass.edgeStrength = Number(value);
    });
    gui.add(params, "edgeGlow", 0, 1).onChange(function(value) {
      outlinePass.edgeGlow = Number(value);
    });
    gui.add(params, "edgeThickness", 1, 4).onChange(function(value) {
      outlinePass.edgeThickness = Number(value);
    });
    gui.add(params, "pulsePeriod", 0, 5).onChange(function(value) {
      outlinePass.pulsePeriod = Number(value);
    });
    gui.add(params, "rotate");
    gui.add(params, "usePatternTexture").onChange(function(value) {
      outlinePass.usePatternTexture = value;
    });
    function Configuration() {
      this.visibleEdgeColor = "#ffffff";
      this.hiddenEdgeColor = "#190a05";
    }
    const conf = new Configuration();
    gui.addColor(conf, "visibleEdgeColor").onChange(function(value) {
      outlinePass.visibleEdgeColor.set(value);
    });
    gui.addColor(conf, "hiddenEdgeColor").onChange(function(value) {
      outlinePass.hiddenEdgeColor.set(value);
    });
    init();
    function init() {
      const width = window.innerWidth;
      const height = window.innerHeight;
      renderer = new THREE.WebGLRenderer({ canvas });
      renderer.shadowMap.enabled = true;
      renderer.setSize(width, height);
      renderer.setAnimationLoop(animate);
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 100);
      camera.position.set(0, 0, 8);
      controls = new OrbitControls(camera, renderer.domElement);
      controls.minDistance = 5;
      controls.maxDistance = 20;
      controls.enablePan = false;
      controls.enableDamping = true;
      controls.dampingFactor = 0.05;
      scene.add(new THREE.AmbientLight(11184810, 0.6));
      const light = new THREE.DirectionalLight(14548957, 2);
      light.position.set(1, 1, 1);
      light.castShadow = true;
      light.shadow.mapSize.width = 1024;
      light.shadow.mapSize.height = 1024;
      const d = 10;
      light.shadow.camera.left = -10;
      light.shadow.camera.right = d;
      light.shadow.camera.top = d;
      light.shadow.camera.bottom = -10;
      light.shadow.camera.far = 1e3;
      scene.add(light);
      const loader = new OBJLoader();
      loader.load("models/obj/tree.obj", function(object) {
        let scale = 1;
        object.traverse(function(child) {
          if (child instanceof THREE.Mesh) {
            child.geometry.center();
            child.geometry.computeBoundingSphere();
            scale = 0.2 * child.geometry.boundingSphere.radius;
            const phongMaterial = new THREE.MeshPhongMaterial({
              color: 16777215,
              specular: 1118481,
              shininess: 5
            });
            child.material = phongMaterial;
            child.receiveShadow = true;
            child.castShadow = true;
          }
        });
        object.position.y = 1;
        object.scale.divideScalar(scale);
        obj3d.add(object);
      });
      scene.add(group);
      group.add(obj3d);
      const geometry = new THREE.SphereGeometry(3, 48, 24);
      for (let i = 0; i < 20; i++) {
        const material = new THREE.MeshLambertMaterial();
        material.color.setHSL(Math.random(), 1, 0.3);
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.x = Math.random() * 4 - 2;
        mesh.position.y = Math.random() * 4 - 2;
        mesh.position.z = Math.random() * 4 - 2;
        mesh.receiveShadow = true;
        mesh.castShadow = true;
        mesh.scale.multiplyScalar(Math.random() * 0.3 + 0.1);
        group.add(mesh);
      }
      const floorMaterial = new THREE.MeshLambertMaterial({ side: THREE.DoubleSide });
      const floorGeometry = new THREE.PlaneGeometry(12, 12);
      const floorMesh = new THREE.Mesh(floorGeometry, floorMaterial);
      floorMesh.rotation.x -= Math.PI * 0.5;
      floorMesh.position.y -= 1.5;
      group.add(floorMesh);
      floorMesh.receiveShadow = true;
      const torusGeometry = new THREE.TorusGeometry(1, 0.3, 16, 100);
      const torusMaterial = new THREE.MeshPhongMaterial({ color: 16755455 });
      const torus = new THREE.Mesh(torusGeometry, torusMaterial);
      torus.position.z = -4;
      group.add(torus);
      torus.receiveShadow = true;
      torus.castShadow = true;
      stats = new Stats(renderer);
      composer = new EffectComposer(renderer);
      const renderPass = new RenderPass(scene, camera);
      composer.addPass(renderPass);
      outlinePass = new OutlinePass(
        new THREE.Vector2(window.innerWidth, window.innerHeight),
        scene,
        camera
      );
      composer.addPass(outlinePass);
      const textureLoader = new THREE.TextureLoader();
      textureLoader.load("textures/tri_pattern.jpg", function(texture) {
        outlinePass.patternTexture = texture;
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.RepeatWrapping;
      });
      const outputPass = new OutputPass();
      composer.addPass(outputPass);
      effectFXAA = new ShaderPass(FXAAShader);
      effectFXAA.uniforms["resolution"].value.set(1 / window.innerWidth, 1 / window.innerHeight);
      composer.addPass(effectFXAA);
      window.addEventListener("resize", onWindowResize);
      canvas.addEventListener("pointermove", onPointerMove);
      function onPointerMove(event) {
        if (event.isPrimary === false) return;
        mouse.x = event.clientX / window.innerWidth * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
        checkIntersection();
      }
      function addSelectedObject(object) {
        selectedObjects = [];
        selectedObjects.push(object);
      }
      function checkIntersection() {
        raycaster.setFromCamera(mouse, camera);
        const intersects = raycaster.intersectObject(scene, true);
        if (intersects.length > 0) {
          const selectedObject = intersects[0].object;
          addSelectedObject(selectedObject);
          outlinePass.selectedObjects = selectedObjects;
        }
      }
      needToDispose(renderer, scene, controls, composer, loader);
    }
    function onWindowResize() {
      const width = window.innerWidth;
      const height = window.innerHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      renderer.setSize(width, height);
      composer.setSize(width, height);
      effectFXAA.uniforms["resolution"].value.set(1 / window.innerWidth, 1 / window.innerHeight);
    }
    function animate() {
      stats.begin();
      const timer = Date.now();
      if (params.rotate) {
        group.rotation.y = timer * 1e-4;
      }
      controls.update();
      composer.render();
      stats.end();
      stats.update();
    }
  }
};
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;