Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container">
    <canvas id="canvas"></canvas>
</div>

<div class="links">
    <a href="https://tympanus.net/codrops/2023/01/25/crafting-a-dice-roller-with-three-js-and-cannon-es/" target="_blank">tutorial<img class="icon" src="https://ksenia-k.com/img/icons/link.svg"></a>
</div>
              
            
!

CSS

              
                html, body {
    padding: 0;
    margin: 0;
}
.container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
}


.links {
    position: fixed;
    bottom: 20px;
    right: 20px;
    font-size: 18px;
    font-family: sans-serif;
}
a {
    text-decoration: none;
    color: black;
    margin-left: 1em;
}
a:hover {
    text-decoration: underline;
}
a img.icon {
    display: inline-block;
    height: 1em;
    margin: 0 0 -0.1em 0.3em;
}
              
            
!

JS

              
                import * as THREE from 'https://cdn.skypack.dev/three@0.133.1/build/three.module';
import { OrbitControls } from 'https://cdn.skypack.dev/three@0.133.1/examples/jsm/controls/OrbitControls'
import * as BufferGeometryUtils from 'https://cdn.skypack.dev/three@0.133.1/examples/jsm/utils/BufferGeometryUtils.js';

import { GUI } from "https://cdn.skypack.dev/lil-gui@0.16.1";


const container = document.querySelector('.container');
const canvasEl = document.querySelector('#canvas');

let renderer, scene, camera, orbit, lightHolder, clock;
let boxMaterialOuter, boxMaterialOuterWireframe;

let diceMesh;

const params = {
    segments: 50,
    edgeRadius: .07,
    notchRadius: .12,
    notchDepth: .1,
    showOuterMesh: true,
    showInnerMesh: true,
    showOuterWireframe: false
}

initScene();
createControls();
window.addEventListener('resize', updateSceneSize);


function initScene() {

    renderer = new THREE.WebGLRenderer({
        alpha: true,
        antialias: true,
        canvas: canvasEl
    });
    renderer.shadowMap.enabled = true
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(45, container.clientWidth / container.clientHeight, .1, 100);
    camera.position.set(1, 1, 3);

    updateSceneSize();

    clock = new THREE.Clock()

    const ambientLight = new THREE.AmbientLight(0xffffff, .5);
    scene.add(ambientLight);
    lightHolder = new THREE.Group();
    const sideLight = new THREE.PointLight(0xffffff, .5);
    sideLight.position.set(5, 5, 5);
    lightHolder.add(sideLight);
    scene.add(lightHolder);

    orbit = new OrbitControls(camera, canvasEl);
    orbit.enableDamping = true;

    createDiceMesh();

    render();
}

function createDiceMesh() {
    boxMaterialOuterWireframe = new THREE.MeshNormalMaterial({
        wireframe: true
    })
    boxMaterialOuter = new THREE.MeshStandardMaterial({
        color: 0xeeeeee,
        visible: params.showOuterMesh,
    })
    const boxMaterialInner = new THREE.MeshStandardMaterial({
        color: 0x000000,
        roughness: 0,
        metalness: 1,
        visible: params.showInnerMesh,
        side: THREE.DoubleSide,
    })

    diceMesh = new THREE.Group();
    const innerMesh = new THREE.Mesh(createInnerGeometry(), boxMaterialInner);
    const outerMesh = new THREE.Mesh(createBoxGeometry(), params.showOuterWireframe ? boxMaterialOuterWireframe : boxMaterialOuter);
    diceMesh.add(innerMesh, outerMesh);
    scene.add(diceMesh)
}

function createBoxGeometry() {
    let boxGeometry = new THREE.BoxGeometry(1, 1, 1, params.segments, params.segments, params.segments);

    const positionAttr = boxGeometry.attributes.position;
    const subCubeHalfSize = .5 - params.edgeRadius;

    for (let i = 0; i < positionAttr.count; i++) {

        let position = new THREE.Vector3().fromBufferAttribute(positionAttr, i);

        const subCube = new THREE.Vector3(Math.sign(position.x), Math.sign(position.y), Math.sign(position.z)).multiplyScalar(subCubeHalfSize);
        const addition = new THREE.Vector3().subVectors(position, subCube);

        if (Math.abs(position.x) > subCubeHalfSize && Math.abs(position.y) > subCubeHalfSize && Math.abs(position.z) > subCubeHalfSize) {
            addition.normalize().multiplyScalar(params.edgeRadius);
            position = subCube.add(addition);
        } else if (Math.abs(position.x) > subCubeHalfSize && Math.abs(position.y) > subCubeHalfSize) {
            addition.z = 0;
            addition.normalize().multiplyScalar(params.edgeRadius);
            position.x = subCube.x + addition.x;
            position.y = subCube.y + addition.y;
        } else if (Math.abs(position.x) > subCubeHalfSize && Math.abs(position.z) > subCubeHalfSize) {
            addition.y = 0;
            addition.normalize().multiplyScalar(params.edgeRadius);
            position.x = subCube.x + addition.x;
            position.z = subCube.z + addition.z;
        } else if (Math.abs(position.y) > subCubeHalfSize && Math.abs(position.z) > subCubeHalfSize) {
            addition.x = 0;
            addition.normalize().multiplyScalar(params.edgeRadius);
            position.y = subCube.y + addition.y;
            position.z = subCube.z + addition.z;
        }

        const notchWave = (v) => {
            v = (1 / params.notchRadius) * v;
            v = Math.PI * Math.max(-1, Math.min(1, v));
            return params.notchDepth * (Math.cos(v) + 1.);
        }
        const notch = (pos) => notchWave(pos[0]) * notchWave(pos[1]);

        const offset = .23;

        if (position.y === .5) {
            position.y -= notch([position.x, position.z]);
        } else if (position.x === .5) {
            position.x -= notch([position.y + offset, position.z + offset]);
            position.x -= notch([position.y - offset, position.z - offset]);
        } else if (position.z === .5) {
            position.z -= notch([position.x - offset, position.y + offset]);
            position.z -= notch([position.x, position.y]);
            position.z -= notch([position.x + offset, position.y - offset]);
        } else if (position.z === -.5) {
            position.z += notch([position.x + offset, position.y + offset]);
            position.z += notch([position.x + offset, position.y - offset]);
            position.z += notch([position.x - offset, position.y + offset]);
            position.z += notch([position.x - offset, position.y - offset]);
        } else if (position.x === -.5) {
            position.x += notch([position.y + offset, position.z + offset]);
            position.x += notch([position.y + offset, position.z - offset]);
            position.x += notch([position.y, position.z]);
            position.x += notch([position.y - offset, position.z + offset]);
            position.x += notch([position.y - offset, position.z - offset]);
        } else if (position.y === -.5) {
            position.y += notch([position.x + offset, position.z + offset]);
            position.y += notch([position.x + offset, position.z]);
            position.y += notch([position.x + offset, position.z - offset]);
            position.y += notch([position.x - offset, position.z + offset]);
            position.y += notch([position.x - offset, position.z]);
            position.y += notch([position.x - offset, position.z - offset]);
        }

        positionAttr.setXYZ(i, position.x, position.y, position.z);
    }

    boxGeometry.deleteAttribute('normal');
    boxGeometry.deleteAttribute('uv');
    boxGeometry = BufferGeometryUtils.mergeVertices(boxGeometry);

    boxGeometry.computeVertexNormals();

    return boxGeometry;
}

function createInnerGeometry() {
    const baseGeometry = new THREE.PlaneGeometry(1 - 2 * params.edgeRadius, 1 - 2 * params.edgeRadius);
    const offset = .48;
    return BufferGeometryUtils.mergeBufferGeometries([
        baseGeometry.clone().translate(0, 0, offset),
        baseGeometry.clone().translate(0, 0, -offset),
        baseGeometry.clone().rotateX(.5 * Math.PI).translate(0, -offset, 0),
        baseGeometry.clone().rotateX(.5 * Math.PI).translate(0, offset, 0),
        baseGeometry.clone().rotateY(.5 * Math.PI).translate(-offset, 0, 0),
        baseGeometry.clone().rotateY(.5 * Math.PI).translate(offset, 0, 0),
    ], false);
}

function recreateGeometry() {
    diceMesh.children[0].geometry = createInnerGeometry();
    diceMesh.children[1].geometry = createBoxGeometry();
}

function render() {

    orbit.update();
    lightHolder.quaternion.copy(camera.quaternion);

    const elapsedTime = .4 * clock.getElapsedTime()
    diceMesh.rotation.x = 2.2 + elapsedTime;
    diceMesh.rotation.y = elapsedTime;

    renderer.render(scene, camera);
    requestAnimationFrame(render);
}

function updateSceneSize() {
    camera.aspect = container.clientWidth / container.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(container.clientWidth, container.clientHeight);
}

function createControls() {
    const gui = new GUI();
	 const appearance = gui.addFolder('APPEARANCE');
	 const internalParams = gui.addFolder('INTERNAL STRUCTURE');
    internalParams.add(params, 'showInnerMesh').onChange(v => {
        diceMesh.children[0].visible = v;
    });
    internalParams.add(params, 'showOuterWireframe').onChange(v => {
		  diceMesh.children[1].visible = true;
        diceMesh.children[1].material = v ? boxMaterialOuterWireframe : boxMaterialOuter;
    });
    internalParams.add(params, 'showOuterMesh').onChange(v => {
        diceMesh.children[1].visible = v;
    });
    appearance.add(params, 'edgeRadius', .01, .2).step(.01).onChange(recreateGeometry)
        .name('box edgeRadius');
    appearance.add(params, 'notchRadius', .01, .2).step(.01).onChange(recreateGeometry)
        .name('notches edgeRadius');
    appearance.add(params, 'notchDepth', .02, .2).step(.01).onChange(recreateGeometry)
        .name('notches depth');
    internalParams.add(params, 'segments', 2, 70).step(1).onChange(recreateGeometry)
        .name('outer mesh segments');
}
              
            
!
999px

Console