webgl_marchingcubes
对应 three.js 示例地址 。
仅需关注 init
函数的内容,其他部分都是示例小程序所使用的描述配置。
js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { MarchingCubes } from "three/examples/jsm/objects/MarchingCubes.js";
import { ToonShader1, ToonShader2, ToonShaderHatching, ToonShaderDotted } from "three/examples/jsm/shaders/ToonShader.js";
/** @type {import("@minisheeep/mp-three-examples").OfficialExampleInfo} */
const exampleInfo = {
name: "webgl_marchingcubes",
useLoaders: [],
info: [
[
{ tag: "a", link: "https://threejs.org", content: "three.js" },
{ tag: "text", content: "- marching cubes" }
],
[
{ tag: "text", content: "based on greggman's" },
{ tag: "a", link: "https://webglsamples.org/blob/blob.html", content: "blob" },
{ tag: "text", content: ", original code by Henrik Rydgård" }
]
],
init: ({ window, canvas, GUI, Stats, needToDispose, useFrame }) => {
let stats;
let camera, scene, renderer;
let materials, current_material;
let light, pointLight, ambientLight;
let effect, resolution;
let effectController;
let time = 0;
const clock = new THREE.Clock();
init();
function init() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1e4);
camera.position.set(-500, 500, 1500);
scene = new THREE.Scene();
scene.background = new THREE.Color(328965);
light = new THREE.DirectionalLight(16777215, 3);
light.position.set(0.5, 0.5, 1);
scene.add(light);
pointLight = new THREE.PointLight(16743424, 3, 0, 0);
pointLight.position.set(0, 0, 100);
scene.add(pointLight);
ambientLight = new THREE.AmbientLight(3289650, 3);
scene.add(ambientLight);
materials = generateMaterials();
current_material = "shiny";
resolution = 28;
effect = new MarchingCubes(resolution, materials[current_material], true, true, 1e5);
effect.position.set(0, 0, 0);
effect.scale.set(700, 700, 700);
effect.enableUvs = false;
effect.enableColors = false;
scene.add(effect);
renderer = new THREE.WebGLRenderer({ canvas });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animate);
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 500;
controls.maxDistance = 5e3;
stats = new Stats(renderer);
setupGui();
window.addEventListener("resize", onWindowResize);
needToDispose(renderer, scene, controls);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function generateMaterials() {
const path = "textures/cube/SwedishRoyalCastle/";
const format = ".jpg";
const urls = [
path + "px" + format,
path + "nx" + format,
path + "py" + format,
path + "ny" + format,
path + "pz" + format,
path + "nz" + format
];
const cubeTextureLoader = new THREE.CubeTextureLoader();
const reflectionCube = cubeTextureLoader.load(urls);
const refractionCube = cubeTextureLoader.load(urls);
refractionCube.mapping = THREE.CubeRefractionMapping;
const toonMaterial1 = createShaderMaterial(ToonShader1, light, ambientLight);
const toonMaterial2 = createShaderMaterial(ToonShader2, light, ambientLight);
const hatchingMaterial = createShaderMaterial(ToonShaderHatching, light, ambientLight);
const dottedMaterial = createShaderMaterial(ToonShaderDotted, light, ambientLight);
const texture = new THREE.TextureLoader().load("textures/uv_grid_opengl.jpg");
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.colorSpace = THREE.SRGBColorSpace;
const materials2 = {
shiny: new THREE.MeshStandardMaterial({
color: 10223616,
envMap: reflectionCube,
roughness: 0.1,
metalness: 1
}),
chrome: new THREE.MeshLambertMaterial({ color: 16777215, envMap: reflectionCube }),
liquid: new THREE.MeshLambertMaterial({
color: 16777215,
envMap: refractionCube,
refractionRatio: 0.85
}),
matte: new THREE.MeshPhongMaterial({ specular: 4802889, shininess: 1 }),
flat: new THREE.MeshLambertMaterial({
/*TODO flatShading: true */
}),
textured: new THREE.MeshPhongMaterial({
color: 16777215,
specular: 1118481,
shininess: 1,
map: texture
}),
colors: new THREE.MeshPhongMaterial({
color: 16777215,
specular: 16777215,
shininess: 2,
vertexColors: true
}),
multiColors: new THREE.MeshPhongMaterial({ shininess: 2, vertexColors: true }),
plastic: new THREE.MeshPhongMaterial({ specular: 12698049, shininess: 250 }),
toon1: toonMaterial1,
toon2: toonMaterial2,
hatching: hatchingMaterial,
dotted: dottedMaterial
};
return materials2;
}
function createShaderMaterial(shader, light2, ambientLight2) {
const u = THREE.UniformsUtils.clone(shader.uniforms);
const vs = shader.vertexShader;
const fs = shader.fragmentShader;
const material = new THREE.ShaderMaterial({
uniforms: u,
vertexShader: vs,
fragmentShader: fs
});
material.uniforms["uDirLightPos"].value = light2.position;
material.uniforms["uDirLightColor"].value = light2.color;
material.uniforms["uAmbientLightColor"].value = ambientLight2.color;
return material;
}
function setupGui() {
const createHandler = function(id) {
return function() {
current_material = id;
effect.material = materials[id];
effect.enableUvs = current_material === "textured" ? true : false;
effect.enableColors = current_material === "colors" || current_material === "multiColors" ? true : false;
};
};
effectController = {
material: "shiny",
speed: 1,
numBlobs: 10,
resolution: 28,
isolation: 80,
floor: true,
wallx: false,
wallz: false,
dummy: function() {
}
};
let h;
const gui = new GUI();
h = gui.addFolder("Materials");
for (const m in materials) {
effectController[m] = createHandler(m);
h.add(effectController, m).name(m);
}
h = gui.addFolder("Simulation");
h.add(effectController, "speed", 0.1, 8, 0.05);
h.add(effectController, "numBlobs", 1, 50, 1);
h.add(effectController, "resolution", 14, 100, 1);
h.add(effectController, "isolation", 10, 300, 1);
h.add(effectController, "floor");
h.add(effectController, "wallx");
h.add(effectController, "wallz");
}
function updateCubes(object, time2, numblobs, floor, wallx, wallz) {
object.reset();
const rainbow = [
new THREE.Color(16711680),
new THREE.Color(16759552),
new THREE.Color(16776960),
new THREE.Color(65280),
new THREE.Color(255),
new THREE.Color(9699517),
new THREE.Color(13107435)
];
const subtract = 12;
const strength = 1.2 / ((Math.sqrt(numblobs) - 1) / 4 + 1);
for (let i = 0; i < numblobs; i++) {
const ballx = Math.sin(i + 1.26 * time2 * (1.03 + 0.5 * Math.cos(0.21 * i))) * 0.27 + 0.5;
const bally = Math.abs(Math.cos(i + 1.12 * time2 * Math.cos(1.22 + 0.1424 * i))) * 0.77;
const ballz = Math.cos(i + 1.32 * time2 * 0.1 * Math.sin(0.92 + 0.53 * i)) * 0.27 + 0.5;
if (current_material === "multiColors") {
object.addBall(ballx, bally, ballz, strength, subtract, rainbow[i % 7]);
} else {
object.addBall(ballx, bally, ballz, strength, subtract);
}
}
if (floor) object.addPlaneY(2, 12);
if (wallz) object.addPlaneZ(2, 12);
if (wallx) object.addPlaneX(2, 12);
object.update();
}
function animate() {
render();
stats.update();
}
function render() {
const delta = clock.getDelta();
time += delta * effectController.speed * 0.5;
if (effectController.resolution !== resolution) {
resolution = effectController.resolution;
effect.init(Math.floor(resolution));
}
if (effectController.isolation !== effect.isolation) {
effect.isolation = effectController.isolation;
}
updateCubes(
effect,
time,
effectController.numBlobs,
effectController.floor,
effectController.wallx,
effectController.wallz
);
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;