Skip to content

webgl_postprocessing_godrays

对应 three.js 示例地址

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

js
import * as THREE from "three";
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { GodRaysDepthMaskShader, GodRaysGenerateShader, GodRaysCombineShader, GodRaysFakeSunShader } from "three/examples/jsm/shaders/GodRaysShader.js";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_postprocessing_godrays",
  useLoaders: [OBJLoader],
  info: [
    [
      {
        tag: "a",
        link: "https://threejs.org",
        content: "three.js"
      },
      {
        tag: "text",
        content: "- webgl god-rays example - tree by"
      },
      {
        tag: "a",
        link: "http://www.turbosquid.com/3d-models/free-tree-3d-model/592617",
        content: "stanloshka"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let stats;
    let camera, scene, renderer, materialDepth;
    let sphereMesh;
    const sunPosition = new THREE.Vector3(0, 1e3, -1e3);
    const clipPosition = new THREE.Vector4();
    const screenSpacePosition = new THREE.Vector3();
    const postprocessing = { enabled: true };
    const orbitRadius = 200;
    const bgColor = 1297;
    const sunColor = 16772608;
    const godrayRenderTargetResolutionMultiplier = 1 / 4;
    init();
    function init() {
      camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 3e3);
      camera.position.z = 200;
      scene = new THREE.Scene();
      materialDepth = new THREE.MeshDepthMaterial();
      const loader = new OBJLoader();
      loader.load("models/obj/tree.obj", function(object) {
        object.position.set(0, -150, -150);
        object.scale.multiplyScalar(400);
        scene.add(object);
      });
      const geo = new THREE.SphereGeometry(1, 20, 10);
      sphereMesh = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({ color: 0 }));
      sphereMesh.scale.multiplyScalar(20);
      scene.add(sphereMesh);
      renderer = new THREE.WebGLRenderer({ canvas });
      renderer.setClearColor(16777215);
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.autoClear = false;
      renderer.setAnimationLoop(animate);
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.minDistance = 50;
      controls.maxDistance = 500;
      stats = new Stats(renderer);
      const gui = new GUI();
      gui.add(postprocessing, "enabled");
      window.addEventListener("resize", onWindowResize);
      initPostprocessing(window.innerWidth, window.innerHeight);
      needToDispose(renderer, scene, controls, loader);
    }
    function onWindowResize() {
      const renderTargetWidth = window.innerWidth;
      const renderTargetHeight = window.innerHeight;
      camera.aspect = renderTargetWidth / renderTargetHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(renderTargetWidth, renderTargetHeight);
      postprocessing.rtTextureColors.setSize(renderTargetWidth, renderTargetHeight);
      postprocessing.rtTextureDepth.setSize(renderTargetWidth, renderTargetHeight);
      postprocessing.rtTextureDepthMask.setSize(renderTargetWidth, renderTargetHeight);
      const adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
      const adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
      postprocessing.rtTextureGodRays1.setSize(adjustedWidth, adjustedHeight);
      postprocessing.rtTextureGodRays2.setSize(adjustedWidth, adjustedHeight);
    }
    function initPostprocessing(renderTargetWidth, renderTargetHeight) {
      postprocessing.scene = new THREE.Scene();
      postprocessing.camera = new THREE.OrthographicCamera(-0.5, 0.5, 0.5, -0.5, -1e4, 1e4);
      postprocessing.camera.position.z = 100;
      postprocessing.scene.add(postprocessing.camera);
      postprocessing.rtTextureColors = new THREE.WebGLRenderTarget(
        renderTargetWidth,
        renderTargetHeight,
        { type: THREE.HalfFloatType }
      );
      postprocessing.rtTextureDepth = new THREE.WebGLRenderTarget(
        renderTargetWidth,
        renderTargetHeight,
        { type: THREE.HalfFloatType }
      );
      postprocessing.rtTextureDepthMask = new THREE.WebGLRenderTarget(
        renderTargetWidth,
        renderTargetHeight,
        { type: THREE.HalfFloatType }
      );
      const adjustedWidth = renderTargetWidth * godrayRenderTargetResolutionMultiplier;
      const adjustedHeight = renderTargetHeight * godrayRenderTargetResolutionMultiplier;
      postprocessing.rtTextureGodRays1 = new THREE.WebGLRenderTarget(
        adjustedWidth,
        adjustedHeight,
        {
          type: THREE.HalfFloatType
        }
      );
      postprocessing.rtTextureGodRays2 = new THREE.WebGLRenderTarget(
        adjustedWidth,
        adjustedHeight,
        {
          type: THREE.HalfFloatType
        }
      );
      const godraysMaskShader = GodRaysDepthMaskShader;
      postprocessing.godrayMaskUniforms = THREE.UniformsUtils.clone(godraysMaskShader.uniforms);
      postprocessing.materialGodraysDepthMask = new THREE.ShaderMaterial({
        uniforms: postprocessing.godrayMaskUniforms,
        vertexShader: godraysMaskShader.vertexShader,
        fragmentShader: godraysMaskShader.fragmentShader
      });
      const godraysGenShader = GodRaysGenerateShader;
      postprocessing.godrayGenUniforms = THREE.UniformsUtils.clone(godraysGenShader.uniforms);
      postprocessing.materialGodraysGenerate = new THREE.ShaderMaterial({
        uniforms: postprocessing.godrayGenUniforms,
        vertexShader: godraysGenShader.vertexShader,
        fragmentShader: godraysGenShader.fragmentShader
      });
      const godraysCombineShader = GodRaysCombineShader;
      postprocessing.godrayCombineUniforms = THREE.UniformsUtils.clone(
        godraysCombineShader.uniforms
      );
      postprocessing.materialGodraysCombine = new THREE.ShaderMaterial({
        uniforms: postprocessing.godrayCombineUniforms,
        vertexShader: godraysCombineShader.vertexShader,
        fragmentShader: godraysCombineShader.fragmentShader
      });
      const godraysFakeSunShader = GodRaysFakeSunShader;
      postprocessing.godraysFakeSunUniforms = THREE.UniformsUtils.clone(
        godraysFakeSunShader.uniforms
      );
      postprocessing.materialGodraysFakeSun = new THREE.ShaderMaterial({
        uniforms: postprocessing.godraysFakeSunUniforms,
        vertexShader: godraysFakeSunShader.vertexShader,
        fragmentShader: godraysFakeSunShader.fragmentShader
      });
      postprocessing.godraysFakeSunUniforms.bgColor.value.setHex(bgColor);
      postprocessing.godraysFakeSunUniforms.sunColor.value.setHex(sunColor);
      postprocessing.godrayCombineUniforms.fGodRayIntensity.value = 0.75;
      postprocessing.quad = new THREE.Mesh(
        new THREE.PlaneGeometry(1, 1),
        postprocessing.materialGodraysGenerate
      );
      postprocessing.quad.position.z = -9900;
      postprocessing.scene.add(postprocessing.quad);
    }
    function animate() {
      stats.begin();
      render();
      stats.end();
      stats.update();
    }
    function getStepSize(filterLen, tapsPerPass, pass) {
      return filterLen * Math.pow(tapsPerPass, -pass);
    }
    function filterGodRays(inputTex, renderTarget, stepSize) {
      postprocessing.scene.overrideMaterial = postprocessing.materialGodraysGenerate;
      postprocessing.godrayGenUniforms["fStepSize"].value = stepSize;
      postprocessing.godrayGenUniforms["tInput"].value = inputTex;
      renderer.setRenderTarget(renderTarget);
      renderer.render(postprocessing.scene, postprocessing.camera);
      postprocessing.scene.overrideMaterial = null;
    }
    function render() {
      const time = Date.now() / 4e3;
      sphereMesh.position.x = orbitRadius * Math.cos(time);
      sphereMesh.position.z = orbitRadius * Math.sin(time) - 100;
      if (postprocessing.enabled) {
        renderer.clearDepth();
        clipPosition.x = sunPosition.x;
        clipPosition.y = sunPosition.y;
        clipPosition.z = sunPosition.z;
        clipPosition.w = 1;
        clipPosition.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
        clipPosition.x /= clipPosition.w;
        clipPosition.y /= clipPosition.w;
        screenSpacePosition.x = (clipPosition.x + 1) / 2;
        screenSpacePosition.y = (clipPosition.y + 1) / 2;
        screenSpacePosition.z = clipPosition.z;
        postprocessing.godrayGenUniforms["vSunPositionScreenSpace"].value.copy(screenSpacePosition);
        postprocessing.godraysFakeSunUniforms["vSunPositionScreenSpace"].value.copy(
          screenSpacePosition
        );
        renderer.setRenderTarget(postprocessing.rtTextureColors);
        renderer.clear(true, true, false);
        const sunsqH = 0.74 * window.innerHeight;
        const sunsqW = 0.74 * window.innerHeight;
        screenSpacePosition.x *= window.innerWidth;
        screenSpacePosition.y *= window.innerHeight;
        renderer.setScissor(
          screenSpacePosition.x - sunsqW / 2,
          screenSpacePosition.y - sunsqH / 2,
          sunsqW,
          sunsqH
        );
        renderer.setScissorTest(true);
        postprocessing.godraysFakeSunUniforms["fAspect"].value = window.innerWidth / window.innerHeight;
        postprocessing.scene.overrideMaterial = postprocessing.materialGodraysFakeSun;
        renderer.setRenderTarget(postprocessing.rtTextureColors);
        renderer.render(postprocessing.scene, postprocessing.camera);
        renderer.setScissorTest(false);
        scene.overrideMaterial = null;
        renderer.setRenderTarget(postprocessing.rtTextureColors);
        renderer.render(scene, camera);
        scene.overrideMaterial = materialDepth;
        renderer.setRenderTarget(postprocessing.rtTextureDepth);
        renderer.clear();
        renderer.render(scene, camera);
        postprocessing.godrayMaskUniforms["tInput"].value = postprocessing.rtTextureDepth.texture;
        postprocessing.scene.overrideMaterial = postprocessing.materialGodraysDepthMask;
        renderer.setRenderTarget(postprocessing.rtTextureDepthMask);
        renderer.render(postprocessing.scene, postprocessing.camera);
        const filterLen = 1;
        const TAPS_PER_PASS = 6;
        filterGodRays(
          postprocessing.rtTextureDepthMask.texture,
          postprocessing.rtTextureGodRays2,
          getStepSize(filterLen, TAPS_PER_PASS, 1)
        );
        filterGodRays(
          postprocessing.rtTextureGodRays2.texture,
          postprocessing.rtTextureGodRays1,
          getStepSize(filterLen, TAPS_PER_PASS, 2)
        );
        filterGodRays(
          postprocessing.rtTextureGodRays1.texture,
          postprocessing.rtTextureGodRays2,
          getStepSize(filterLen, TAPS_PER_PASS, 3)
        );
        postprocessing.godrayCombineUniforms["tColors"].value = postprocessing.rtTextureColors.texture;
        postprocessing.godrayCombineUniforms["tGodRays"].value = postprocessing.rtTextureGodRays2.texture;
        postprocessing.scene.overrideMaterial = postprocessing.materialGodraysCombine;
        renderer.setRenderTarget(null);
        renderer.render(postprocessing.scene, postprocessing.camera);
        postprocessing.scene.overrideMaterial = null;
      } else {
        renderer.setRenderTarget(null);
        renderer.clear();
        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;