68 lines
2.7 KiB
HTML
68 lines
2.7 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<title>three.js CSG</title>
|
|
<style>html,body{margin:0;height:100%;overflow:hidden;background:#202428}canvas{display:block}</style>
|
|
<script type="importmap">
|
|
{
|
|
"imports": {
|
|
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
|
|
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/",
|
|
"three-mesh-bvh": "https://cdn.jsdelivr.net/npm/three-mesh-bvh@0.7.3/build/index.module.js",
|
|
"three-bvh-csg": "https://cdn.jsdelivr.net/npm/three-bvh-csg@0.0.16/build/index.module.js"
|
|
}
|
|
}
|
|
</script>
|
|
</head>
|
|
<body>
|
|
<script type="module">
|
|
import * as THREE from 'three';
|
|
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
|
|
import { Brush, Evaluator, ADDITION, SUBTRACTION, INTERSECTION, DIFFERENCE } from 'three-bvh-csg';
|
|
|
|
// ---------------------------------------------------------------- scene
|
|
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
|
renderer.setPixelRatio(window.devicePixelRatio);
|
|
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
document.body.appendChild(renderer.domElement);
|
|
|
|
const scene = new THREE.Scene();
|
|
const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100);
|
|
camera.position.set(4, 3, 5);
|
|
const controls = new OrbitControls(camera, renderer.domElement);
|
|
|
|
scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1.2));
|
|
const sun = new THREE.DirectionalLight(0xffffff, 1.5);
|
|
sun.position.set(5, 8, 4);
|
|
scene.add(sun);
|
|
scene.add(new THREE.GridHelper(10, 10, 0x555555, 0x333333));
|
|
|
|
// ---------------------------------------------------------------- model
|
|
// Change this function only. It must return an Object3D that is added to the scene.
|
|
function buildModel() {
|
|
const mat = new THREE.MeshStandardMaterial({ color: 0x4488ff, metalness: 0.2, roughness: 0.5 });
|
|
const cube = new Brush(new THREE.BoxGeometry(2, 2, 2), mat);
|
|
const hole = new Brush(new THREE.CylinderGeometry(0.5, 0.5, 2.2, 48), mat);
|
|
hole.rotation.x = Math.PI / 2; // cylinder axis along z
|
|
cube.updateMatrixWorld(); hole.updateMatrixWorld();
|
|
|
|
const ev = new Evaluator(); ev.useGroups = false;
|
|
const part = ev.evaluate(cube, hole, SUBTRACTION);
|
|
part.material = mat;
|
|
part.position.y = 1;
|
|
return part;
|
|
}
|
|
scene.add(buildModel());
|
|
|
|
// ---------------------------------------------------------------- loop
|
|
window.addEventListener('resize', () => {
|
|
camera.aspect = window.innerWidth / window.innerHeight;
|
|
camera.updateProjectionMatrix();
|
|
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
});
|
|
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, camera); });
|
|
</script>
|
|
</body>
|
|
</html>
|