webgl_clipping_advanced
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "webgl_clipping_advanced",
useLoaders: [],
info: [],
init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
function planesFromMesh(vertices, indices) {
const n = indices.length / 3, result = new Array(n);
for (let i = 0, j = 0; i < n; ++i, j += 3) {
const a = vertices[indices[j]], b = vertices[indices[j + 1]], c = vertices[indices[j + 2]];
result[i] = new THREE.Plane().setFromCoplanarPoints(a, b, c);
}
return result;
}
function createPlanes(n) {
const result = new Array(n);
for (let i = 0; i !== n; ++i) result[i] = new THREE.Plane();
return result;
}
function assignTransformedPlanes(planesOut, planesIn, matrix) {
for (let i = 0, n = planesIn.length; i !== n; ++i)
planesOut[i].copy(planesIn[i]).applyMatrix4(matrix);
}
function cylindricalPlanes(n, innerRadius) {
const result = createPlanes(n);
for (let i = 0; i !== n; ++i) {
const plane = result[i], angle = i * Math.PI * 2 / n;
plane.normal.set(Math.cos(angle), 0, Math.sin(angle));
plane.constant = innerRadius;
}
return result;
}
const planeToMatrix = function() {
const xAxis = new THREE.Vector3(), yAxis = new THREE.Vector3(), trans = new THREE.Vector3();
return function planeToMatrix2(plane) {
const zAxis = plane.normal, matrix = new THREE.Matrix4();
if (Math.abs(zAxis.x) > Math.abs(zAxis.z)) {
yAxis.set(-zAxis.y, zAxis.x, 0);
} else {
yAxis.set(0, -zAxis.z, zAxis.y);
}
xAxis.crossVectors(yAxis.normalize(), zAxis);
plane.coplanarPoint(trans);
return matrix.set(
xAxis.x,
yAxis.x,
zAxis.x,
trans.x,
xAxis.y,
yAxis.y,
zAxis.y,
trans.y,
xAxis.z,
yAxis.z,
zAxis.z,
trans.z,
0,
0,
0,
1
);
};
}();
const Vertices = [
new THREE.Vector3(1, 0, +Math.SQRT1_2),
new THREE.Vector3(-1, 0, +Math.SQRT1_2),
new THREE.Vector3(0, 1, -Math.SQRT1_2),
new THREE.Vector3(0, -1, -Math.SQRT1_2)
], Indices = [0, 1, 2, 0, 2, 3, 0, 3, 1, 1, 3, 2], Planes = planesFromMesh(Vertices, Indices), PlaneMatrices = Planes.map(planeToMatrix), GlobalClippingPlanes = cylindricalPlanes(5, 2.5), Empty = Object.freeze([]);
let camera, scene, renderer, startTime, stats, object, clipMaterial, volumeVisualization, globalClippingPlanes;
function init() {
camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.25, 16);
camera.position.set(0, 1.5, 3);
scene = new THREE.Scene();
scene.add(new THREE.AmbientLight(16777215));
const spotLight = new THREE.SpotLight(16777215, 60);
spotLight.angle = Math.PI / 5;
spotLight.penumbra = 0.2;
spotLight.position.set(2, 3, 3);
spotLight.castShadow = true;
spotLight.shadow.camera.near = 3;
spotLight.shadow.camera.far = 10;
spotLight.shadow.mapSize.width = 1024;
spotLight.shadow.mapSize.height = 1024;
scene.add(spotLight);
const dirLight = new THREE.DirectionalLight(16777215, 1.5);
dirLight.position.set(0, 2, 0);
dirLight.castShadow = true;
dirLight.shadow.camera.near = 1;
dirLight.shadow.camera.far = 10;
dirLight.shadow.camera.right = 1;
dirLight.shadow.camera.left = -1;
dirLight.shadow.camera.top = 1;
dirLight.shadow.camera.bottom = -1;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
scene.add(dirLight);
clipMaterial = new THREE.MeshPhongMaterial({
color: 15600144,
shininess: 100,
side: THREE.DoubleSide,
// Clipping setup:
clippingPlanes: createPlanes(Planes.length),
clipShadows: true
});
object = new THREE.Group();
const geometry = new THREE.BoxGeometry(0.18, 0.18, 0.18);
for (let z = -2; z <= 2; ++z)
for (let y = -2; y <= 2; ++y)
for (let x = -2; x <= 2; ++x) {
const mesh = new THREE.Mesh(geometry, clipMaterial);
mesh.position.set(x / 5, y / 5, z / 5);
mesh.castShadow = true;
object.add(mesh);
}
scene.add(object);
const planeGeometry = new THREE.PlaneGeometry(3, 3, 1, 1), color = new THREE.Color();
volumeVisualization = new THREE.Group();
volumeVisualization.visible = false;
for (let i = 0, n = Planes.length; i !== n; ++i) {
const material = new THREE.MeshBasicMaterial({
color: color.setHSL(i / n, 0.5, 0.5).getHex(),
side: THREE.DoubleSide,
opacity: 0.2,
transparent: true,
// clip to the others to show the volume (wildly
// intersecting transparent planes look bad)
clippingPlanes: clipMaterial.clippingPlanes.filter(function(_, j) {
return j !== i;
})
// no need to enable shadow clipping - the plane
// visualization does not cast shadows
});
const mesh = new THREE.Mesh(planeGeometry, material);
mesh.matrixAutoUpdate = false;
volumeVisualization.add(mesh);
}
scene.add(volumeVisualization);
const ground = new THREE.Mesh(
planeGeometry,
new THREE.MeshPhongMaterial({
color: 10530223,
shininess: 10
})
);
ground.rotation.x = -Math.PI / 2;
ground.scale.multiplyScalar(3);
ground.receiveShadow = true;
scene.add(ground);
renderer = new THREE.WebGLRenderer({ canvas });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
renderer.shadowMap.enabled = true;
globalClippingPlanes = createPlanes(GlobalClippingPlanes.length);
renderer.clippingPlanes = Empty;
renderer.localClippingEnabled = true;
window.addEventListener("resize", onWindowResize);
stats = new Stats(renderer);
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 1;
controls.maxDistance = 8;
controls.target.set(0, 1, 0);
controls.update();
const gui = new GUI(), folder = gui.addFolder("Local Clipping"), props = {
get Enabled() {
return renderer.localClippingEnabled;
},
set Enabled(v) {
renderer.localClippingEnabled = v;
if (!v) volumeVisualization.visible = false;
},
get Shadows() {
return clipMaterial.clipShadows;
},
set Shadows(v) {
clipMaterial.clipShadows = v;
},
get Visualize() {
return volumeVisualization.visible;
},
set Visualize(v) {
if (renderer.localClippingEnabled) volumeVisualization.visible = v;
}
};
folder.add(props, "Enabled");
folder.add(props, "Shadows");
folder.add(props, "Visualize").listen();
gui.addFolder("Global Clipping").add(
{
get Enabled() {
return renderer.clippingPlanes !== Empty;
},
set Enabled(v) {
renderer.clippingPlanes = v ? globalClippingPlanes : Empty;
}
},
"Enabled"
);
startTime = Date.now();
needToDispose(renderer, scene, controls);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function setObjectWorldMatrix(object2, matrix) {
const parent = object2.parent;
scene.updateMatrixWorld();
object2.matrix.copy(parent.matrixWorld).invert();
object2.applyMatrix4(matrix);
}
const transform = new THREE.Matrix4(), tmpMatrix = new THREE.Matrix4();
function animate() {
const currentTime = Date.now(), time = (currentTime - startTime) / 1e3;
object.position.y = 1;
object.rotation.x = time * 0.5;
object.rotation.y = time * 0.2;
object.updateMatrix();
transform.copy(object.matrix);
const bouncy = Math.cos(time * 0.5) * 0.5 + 0.7;
transform.multiply(tmpMatrix.makeScale(bouncy, bouncy, bouncy));
assignTransformedPlanes(clipMaterial.clippingPlanes, Planes, transform);
const planeMeshes = volumeVisualization.children;
for (let i = 0, n = planeMeshes.length; i !== n; ++i) {
tmpMatrix.multiplyMatrices(transform, PlaneMatrices[i]);
setObjectWorldMatrix(planeMeshes[i], tmpMatrix);
}
transform.makeRotationY(time * 0.1);
assignTransformedPlanes(globalClippingPlanes, GlobalClippingPlanes, transform);
stats.begin();
renderer.render(scene, camera);
stats.end();
stats.update();
}
init();
}
};
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;