Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
186
Indexable
Never
(async function(){
	let THREE = await import('./three.module.min.js');
	var canvas = document.getElementById('PCA3D');
	var renderer = new THREE.WebGLRenderer({canvas: canvas, alpha: true, preserveDrawingBuffer: true});
	var scene = new THREE.Scene();

//	var light = new THREE.PointLight( 0xffffff, 1, 100 );
//	light.position.set( 50, 50, 50 );
//	scene.add( light );

	var radius = 75;
	var n = 50;
	var p = new Array(n);
	for (var i = 0; i < n; ++i) {
		var x = radius * Math.random() * 0.3;
		var y = radius * Math.random() * 0.9;
		var z = radius * Math.random() * 0.6;
		p[i] = [x,y,z];
	}
	var [c, ev] = pca(p);

	var geometry = new THREE.SphereGeometry( 2 );
	var material = new THREE.MeshPhongMaterial( {
		color : 'gray',
		emissive : 0x222222,
		reflectivity : 0.8,
	} );
	for (var i = 0; i < n; ++i) {
		var sphere = new THREE.Mesh( geometry, material );
		sphere.position.fromArray( p[i] );
		scene.add( sphere );
	}

	var dir1 = new THREE.Vector3( ev[0], ev[1], ev[2] ).normalize();
	var dir2 = new THREE.Vector3( ev[3], ev[4], ev[5] ).normalize();
	var dir3 = new THREE.Vector3( ev[6], ev[7], ev[8] ).normalize();
	var center = new THREE.Vector3( c[0], c[1], c[2] );
	var arrowHelper1 = new THREE.ArrowHelper( dir1, center, 20, 0xCC5500, 4, 4 );
	var arrowHelper2 = new THREE.ArrowHelper( dir2, center, 20, 0x00CC55, 4, 4 );
	var arrowHelper3 = new THREE.ArrowHelper( dir3, center, 20, 0x5500CC, 4, 4 );
	arrowHelper1.line.material.linewidth = 3;	// bug
	arrowHelper2.line.material.linewidth = 3;	// bug
	arrowHelper3.line.material.linewidth = 3;	// bug
	scene.add( arrowHelper1 );
	scene.add( arrowHelper2 );
	scene.add( arrowHelper3 );
	var axesHelper = new THREE.AxesHelper( radius * 2 );
	scene.add( axesHelper );

	var camera = new THREE.PerspectiveCamera();
	var depth = radius * 1.2;
	var angle_x = 0.5;
	var angle_y = 0.5;
	function updateCamera() {
		camera.position.x = center.x + depth * Math.cos(angle_y) * Math.cos(angle_x);
		camera.position.y = center.y + depth * Math.sin(-angle_x);
		camera.position.z = center.z + depth * Math.sin(angle_y);
		camera.up.set( 0, 0, 1 );
		camera.lookAt( center );
	}
	updateCamera();
	renderer.render(scene, camera);

	canvas.onmousemove = function(event) {
		angle_x = (event.offsetX-canvas.width/2)/(canvas.width/2);
		angle_y = (event.offsetY-canvas.height/2)/(canvas.height/2);
		updateCamera();
		renderer.render(scene, camera);
	}
})();