Skip to content

webgl_geometry_shapes

对应 three.js 示例地址

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

js
import * as THREE from "three";

/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
  name: "webgl_geometry_shapes",
  useLoaders: [],
  info: [
    [
      {
        tag: "text",
        content: "Simple procedurally-generated shapes"
      }
    ]
  ],
  init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
    let stats;
    let camera, scene, renderer;
    let group;
    let targetRotation = 0;
    let targetRotationOnPointerDown = 0;
    let pointerX = 0;
    let pointerXOnPointerDown = 0;
    let windowHalfX = window.innerWidth / 2;
    init();
    function init() {
      scene = new THREE.Scene();
      scene.background = new THREE.Color(15790320);
      camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1e3);
      camera.position.set(0, 150, 500);
      scene.add(camera);
      const light = new THREE.PointLight(16777215, 2.5, 0, 0);
      camera.add(light);
      group = new THREE.Group();
      group.position.y = 50;
      scene.add(group);
      const loader = new THREE.TextureLoader();
      const texture = loader.load("textures/uv_grid_opengl.jpg");
      texture.colorSpace = THREE.SRGBColorSpace;
      texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
      texture.repeat.set(8e-3, 8e-3);
      function addShape(shape, extrudeSettings2, color, x2, y2, z, rx, ry, rz, s) {
        let geometry = new THREE.ShapeGeometry(shape);
        let mesh = new THREE.Mesh(
          geometry,
          new THREE.MeshPhongMaterial({ side: THREE.DoubleSide, map: texture })
        );
        mesh.position.set(x2, y2, z - 175);
        mesh.rotation.set(rx, ry, rz);
        mesh.scale.set(s, s, s);
        group.add(mesh);
        geometry = new THREE.ShapeGeometry(shape);
        mesh = new THREE.Mesh(
          geometry,
          new THREE.MeshPhongMaterial({ color, side: THREE.DoubleSide })
        );
        mesh.position.set(x2, y2, z - 125);
        mesh.rotation.set(rx, ry, rz);
        mesh.scale.set(s, s, s);
        group.add(mesh);
        geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings2);
        mesh = new THREE.Mesh(geometry, new THREE.MeshPhongMaterial({ color }));
        mesh.position.set(x2, y2, z - 75);
        mesh.rotation.set(rx, ry, rz);
        mesh.scale.set(s, s, s);
        group.add(mesh);
        addLineShape(shape, color, x2, y2, z, rx, ry, rz, s);
      }
      function addLineShape(shape, color, x2, y2, z, rx, ry, rz, s) {
        shape.autoClose = true;
        const points = shape.getPoints();
        const spacedPoints = shape.getSpacedPoints(50);
        const geometryPoints = new THREE.BufferGeometry().setFromPoints(points);
        const geometrySpacedPoints = new THREE.BufferGeometry().setFromPoints(spacedPoints);
        let line = new THREE.Line(geometryPoints, new THREE.LineBasicMaterial({ color }));
        line.position.set(x2, y2, z - 25);
        line.rotation.set(rx, ry, rz);
        line.scale.set(s, s, s);
        group.add(line);
        line = new THREE.Line(geometrySpacedPoints, new THREE.LineBasicMaterial({ color }));
        line.position.set(x2, y2, z + 25);
        line.rotation.set(rx, ry, rz);
        line.scale.set(s, s, s);
        group.add(line);
        let particles = new THREE.Points(
          geometryPoints,
          new THREE.PointsMaterial({ color, size: 4 })
        );
        particles.position.set(x2, y2, z + 75);
        particles.rotation.set(rx, ry, rz);
        particles.scale.set(s, s, s);
        group.add(particles);
        particles = new THREE.Points(
          geometrySpacedPoints,
          new THREE.PointsMaterial({ color, size: 4 })
        );
        particles.position.set(x2, y2, z + 125);
        particles.rotation.set(rx, ry, rz);
        particles.scale.set(s, s, s);
        group.add(particles);
      }
      const californiaPts = [];
      californiaPts.push(new THREE.Vector2(610, 320));
      californiaPts.push(new THREE.Vector2(450, 300));
      californiaPts.push(new THREE.Vector2(392, 392));
      californiaPts.push(new THREE.Vector2(266, 438));
      californiaPts.push(new THREE.Vector2(190, 570));
      californiaPts.push(new THREE.Vector2(190, 600));
      californiaPts.push(new THREE.Vector2(160, 620));
      californiaPts.push(new THREE.Vector2(160, 650));
      californiaPts.push(new THREE.Vector2(180, 640));
      californiaPts.push(new THREE.Vector2(165, 680));
      californiaPts.push(new THREE.Vector2(150, 670));
      californiaPts.push(new THREE.Vector2(90, 737));
      californiaPts.push(new THREE.Vector2(80, 795));
      californiaPts.push(new THREE.Vector2(50, 835));
      californiaPts.push(new THREE.Vector2(64, 870));
      californiaPts.push(new THREE.Vector2(60, 945));
      californiaPts.push(new THREE.Vector2(300, 945));
      californiaPts.push(new THREE.Vector2(300, 743));
      californiaPts.push(new THREE.Vector2(600, 473));
      californiaPts.push(new THREE.Vector2(626, 425));
      californiaPts.push(new THREE.Vector2(600, 370));
      californiaPts.push(new THREE.Vector2(610, 320));
      for (let i = 0; i < californiaPts.length; i++) californiaPts[i].multiplyScalar(0.25);
      const californiaShape = new THREE.Shape(californiaPts);
      const triangleShape = new THREE.Shape().moveTo(80, 20).lineTo(40, 80).lineTo(120, 80).lineTo(80, 20);
      const x = 0, y = 0;
      const heartShape = new THREE.Shape().moveTo(x + 25, y + 25).bezierCurveTo(x + 25, y + 25, x + 20, y, x, y).bezierCurveTo(x - 30, y, x - 30, y + 35, x - 30, y + 35).bezierCurveTo(x - 30, y + 55, x - 10, y + 77, x + 25, y + 95).bezierCurveTo(x + 60, y + 77, x + 80, y + 55, x + 80, y + 35).bezierCurveTo(x + 80, y + 35, x + 80, y, x + 50, y).bezierCurveTo(x + 35, y, x + 25, y + 25, x + 25, y + 25);
      const sqLength = 80;
      const squareShape = new THREE.Shape().moveTo(0, 0).lineTo(0, sqLength).lineTo(sqLength, sqLength).lineTo(sqLength, 0).lineTo(0, 0);
      const roundedRectShape = new THREE.Shape();
      (function roundedRect(ctx, x2, y2, width, height, radius) {
        ctx.moveTo(x2, y2 + radius);
        ctx.lineTo(x2, y2 + height - radius);
        ctx.quadraticCurveTo(x2, y2 + height, x2 + radius, y2 + height);
        ctx.lineTo(x2 + width - radius, y2 + height);
        ctx.quadraticCurveTo(x2 + width, y2 + height, x2 + width, y2 + height - radius);
        ctx.lineTo(x2 + width, y2 + radius);
        ctx.quadraticCurveTo(x2 + width, y2, x2 + width - radius, y2);
        ctx.lineTo(x2 + radius, y2);
        ctx.quadraticCurveTo(x2, y2, x2, y2 + radius);
      })(roundedRectShape, 0, 0, 50, 50, 20);
      const trackShape = new THREE.Shape().moveTo(40, 40).lineTo(40, 160).absarc(60, 160, 20, Math.PI, 0, true).lineTo(80, 40).absarc(60, 40, 20, 2 * Math.PI, Math.PI, true);
      const circleRadius = 40;
      const circleShape = new THREE.Shape().moveTo(0, circleRadius).quadraticCurveTo(circleRadius, circleRadius, circleRadius, 0).quadraticCurveTo(circleRadius, -40, 0, -40).quadraticCurveTo(-40, -40, -40, 0).quadraticCurveTo(-40, circleRadius, 0, circleRadius);
      const fishShape = new THREE.Shape().moveTo(x, y).quadraticCurveTo(x + 50, y - 80, x + 90, y - 10).quadraticCurveTo(x + 100, y - 10, x + 115, y - 40).quadraticCurveTo(x + 115, y, x + 115, y + 40).quadraticCurveTo(x + 100, y + 10, x + 90, y + 10).quadraticCurveTo(x + 50, y + 80, x, y);
      const arcShape = new THREE.Shape().moveTo(50, 10).absarc(10, 10, 40, 0, Math.PI * 2, false);
      const holePath = new THREE.Path().moveTo(20, 10).absarc(10, 10, 10, 0, Math.PI * 2, true);
      arcShape.holes.push(holePath);
      const smileyShape = new THREE.Shape().moveTo(80, 40).absarc(40, 40, 40, 0, Math.PI * 2, false);
      const smileyEye1Path = new THREE.Path().moveTo(35, 20).absellipse(25, 20, 10, 10, 0, Math.PI * 2, true);
      const smileyEye2Path = new THREE.Path().moveTo(65, 20).absarc(55, 20, 10, 0, Math.PI * 2, true);
      const smileyMouthPath = new THREE.Path().moveTo(20, 40).quadraticCurveTo(40, 60, 60, 40).bezierCurveTo(70, 45, 70, 50, 60, 60).quadraticCurveTo(40, 80, 20, 60).quadraticCurveTo(5, 50, 20, 40);
      smileyShape.holes.push(smileyEye1Path);
      smileyShape.holes.push(smileyEye2Path);
      smileyShape.holes.push(smileyMouthPath);
      const splinepts = [];
      splinepts.push(new THREE.Vector2(70, 20));
      splinepts.push(new THREE.Vector2(80, 90));
      splinepts.push(new THREE.Vector2(-30, 70));
      splinepts.push(new THREE.Vector2(0, 0));
      const splineShape = new THREE.Shape().moveTo(0, 0).splineThru(splinepts);
      const extrudeSettings = {
        depth: 8,
        bevelEnabled: true,
        bevelSegments: 2,
        steps: 2,
        bevelSize: 1,
        bevelThickness: 1
      };
      addShape(californiaShape, extrudeSettings, 15761408, -300, -100, 0, 0, 0, 0, 1);
      addShape(triangleShape, extrudeSettings, 8421616, -180, 0, 0, 0, 0, 0, 1);
      addShape(roundedRectShape, extrudeSettings, 32768, -150, 150, 0, 0, 0, 0, 1);
      addShape(trackShape, extrudeSettings, 32896, 200, -100, 0, 0, 0, 0, 1);
      addShape(squareShape, extrudeSettings, 16624, 150, 100, 0, 0, 0, 0, 1);
      addShape(heartShape, extrudeSettings, 15728640, 60, 100, 0, 0, 0, Math.PI, 1);
      addShape(circleShape, extrudeSettings, 61440, 120, 250, 0, 0, 0, 0, 1);
      addShape(fishShape, extrudeSettings, 4210752, -60, 200, 0, 0, 0, 0, 1);
      addShape(smileyShape, extrudeSettings, 15728880, -200, 250, 0, 0, 0, Math.PI, 1);
      addShape(arcShape, extrudeSettings, 8404992, 150, 0, 0, 0, 0, 0, 1);
      addShape(splineShape, extrudeSettings, 8421504, -50, -100, 0, 0, 0, 0, 1);
      addLineShape(arcShape.holes[0], 8404992, 150, 0, 0, 0, 0, 0, 1);
      for (let i = 0; i < smileyShape.holes.length; i += 1) {
        addLineShape(smileyShape.holes[i], 15728880, -200, 250, 0, 0, 0, Math.PI, 1);
      }
      renderer = new THREE.WebGLRenderer({ antialias: true, canvas });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.setAnimationLoop(animate);
      stats = new Stats(renderer);
      canvas.addEventListener("pointerdown", onPointerDown);
      window.addEventListener("resize", onWindowResize);
      needToDispose(renderer, scene);
    }
    function onWindowResize() {
      windowHalfX = window.innerWidth / 2;
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    }
    function onPointerDown(event) {
      if (event.isPrimary === false) return;
      pointerXOnPointerDown = event.clientX - windowHalfX;
      targetRotationOnPointerDown = targetRotation;
      canvas.addEventListener("pointermove", onPointerMove);
      canvas.addEventListener("pointerup", onPointerUp);
    }
    function onPointerMove(event) {
      if (event.isPrimary === false) return;
      pointerX = event.clientX - windowHalfX;
      targetRotation = targetRotationOnPointerDown + (pointerX - pointerXOnPointerDown) * 0.02;
    }
    function onPointerUp(event) {
      if (event.isPrimary === false) return;
      canvas.removeEventListener("pointermove", onPointerMove);
      canvas.removeEventListener("pointerup", onPointerUp);
    }
    function animate() {
      render();
      stats.update();
    }
    function render() {
      group.rotation.y += (targetRotation - group.rotation.y) * 0.05;
      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;