three.js ~ example ~ Mr.doob

2012-01-05 ~

by sjpt

HTML

<p id="msg" style="top:400px">
message
</p>
... await: <input id="wait" type="checkbox" />
frame serve ms <input id="dtb" type="range" min="0" max="100" value="10"/>

JavaScript

import * as THREE from 'https://threejs.org/build/three.module.js'
import Stats from 'https://threejs.org/examples/jsm/libs/stats.module.js';
var camera, scene, renderer, group, stats, blob, items;
var pp=[0,0], nexti=0, lasti;
let pend = 0;
let lastt = 0;
const nn=2500, mm=6;
let lastsleep;

init();
animate();

async function init() {

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 10000);
    camera.position.z = 505;
    scene.add(camera);

    scene.add(costly(nn, mm));

    renderer = new THREE.WebGL1Renderer();
    renderer.setSize(window.innerWidth, window.innerHeight);

    document.body.appendChild(renderer.domElement);
    stats = new Stats();
	stats.showPanel( 1 ); // 0: fps, 1: ms, 2: mb, 3+: custom
    stats.dom.style.top = '50px'
	document.body.appendChild( stats.dom );

}

async function streamFrame() {
	const d = Date.now();
	lastt = Math.max(d, lastt) + +dtb.value;
   	lastsleep = lastt - d;
	const p = new Promise(async resolve => {
	    await sleep(lastsleep);
    	nexti++;
        resolve([Math.sin(nexti/1000*30), Math.cos(nexti/1000*19)]);
    })
    return p;
}


function costly(n,mm) {
    const g = new THREE.PlaneBufferGeometry(10,10,n,n);
    const m = new THREE.MeshBasicMaterial();
    group = new THREE.Group();
    for (let i = 0; i < mm; i++) {
        const mm = new THREE.Mesh(g,m);
        const r = Math.random;
        mm.position.set(r()*30, r()*30, r()*30);
        group.add(mm);
    }
    return group;
}


async function animate() {
	if (lasti !== nexti) {
    	stats.end()
    	stats.begin()
    }
    if (wait.checked)
    	await render();
    else
    	render();
    requestAnimationFrame(animate);
}

async function render() {
	pend++;
    window.msg.innerHTML = `pend ${pend} dt ${dtb.value} ${wait.checked} lastsleep ${lastsleep}`
    
	const d = Date.now() / 1000;
    group.position.set(40*pp[0], 40*pp[1],0 );

    renderer.render(scene, camera);
	pp = await...