Examples : Glasses

Description

This examples demonstrates,

  • Using the Reflector to mirror the scene above it.
  • Using the CSS2DRenderer and CSS2DObject to create annotations.
  • Demonstrating annotations on a moving object.
  • Extracting annotation information from the Blender exported glTF custom properties.
  • Using the ConvexBufferGeometry to create convex hulls around more sophisticated meshes that can be used as Physics bodies.
  • Using Cannon.js as the Physics engine
  • Creating a refraction effect on the glasses frame using the MeshPhysicalMaterial and CubeCamera.
  • Using the GLTFLoader and selectively applying materials to the loaded geometry.

Code

./src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import express from "express"
import path from "path"
import http from "http"

const port: number = 3000

class App {
    private server: http.Server
    private port: number

    constructor(port: number) {
        this.port = port
        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))
        app.use('/build/three.module.js', express.static(path.join(__dirname, '../../node_modules/three/build/three.module.js')))
        app.use('/jsm/controls/OrbitControls', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/controls/OrbitControls.js')))
        app.use('/jsm/loaders/GLTFLoader', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/loaders/GLTFLoader.js')))
        app.use('/jsm/libs/stats.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/stats.module.js')))
        app.use('/jsm/libs/dat.gui.module', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/dat.gui.module.js')))
        app.use('/jsm/libs/tween.module.min', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/libs/tween.module.min.js')))
        app.use('/cannon/cannon.min', express.static(path.join(__dirname, '../../node_modules/cannon/build/cannon.min.js')))
        app.use('/jsm/objects/Reflector', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/objects/Reflector.js')))
        app.use('/jsm/', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/')))
        app.use('/jsm/geometries/ConvexGeometry', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/geometries/ConvexGeometry.js')))
        app.use('/jsm/renderers/CSS2DRenderer', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/renderers/CSS2DRenderer.js')))

        this.server = new http.Server(app);
    }

    public Start() {
        this.server.listen(this.port, () => {
            console.log(`Server listening on port ${this.port}.`)
        })
    }
}

new App(port).Start()

./src/client/client.ts

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import { GLTFLoader } from '/jsm/loaders/GLTFLoader';
import Stats from '/jsm/libs/stats.module'
import { GUI } from '/jsm/libs/dat.gui.module'
import { Reflector } from '/jsm/objects/Reflector';
import '/cannon/cannon.min';
import CannonUtils from './utils/cannonUtils.js';
import { ConvexBufferGeometry } from '/jsm/geometries/ConvexGeometry';
import { TWEEN } from '/jsm/libs/tween.module.min';
import { CSS2DRenderer, CSS2DObject } from '/jsm/renderers/CSS2DRenderer';

let annotations: { [key: string]: Annotation } = {}
const annotationMarkers: THREE.Sprite[] = []

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xaec6cf);

const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
world.allowSleep = true;

var light = new THREE.DirectionalLight();
light.position.set(2.5, 7.5, 15);
scene.add(light);

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(1, 1, 1.5);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
document.body.appendChild(renderer.domElement);

const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = '0px';
labelRenderer.domElement.style.pointerEvents = 'none';
document.body.appendChild(labelRenderer.domElement);

const circleTexture = new THREE.TextureLoader().load("img/circle.png");
const envTexture = new THREE.CubeTextureLoader().load(["img/px_25.jpg", "img/nx_25.jpg", "img/py_25.jpg", "img/ny_25.jpg", "img/pz_25.jpg", "img/nz_25.jpg"]);
envTexture.mapping = THREE.CubeReflectionMapping;

const groundMirror = new Reflector(new THREE.PlaneBufferGeometry(500, 500), {
    color: new THREE.Color(0x222222),
    textureWidth: window.innerWidth * window.devicePixelRatio,
    textureHeight: window.innerHeight * window.devicePixelRatio
});
groundMirror.position.y = -.005;
groundMirror.rotateX(-Math.PI / 2);
groundMirror.layers.set(1);
scene.add(groundMirror);

const planeShape = new CANNON.Plane();
const planeBody = new CANNON.Body({ mass: 0 });
planeBody.addShape(planeShape);
planeBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2);
world.addBody(planeBody);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, .5, 0);
controls.addEventListener("change", function () {
    if (camera.position.y < .1) {
        camera.position.y = .1;
    }
});

const cubeRenderTarget = new THREE.WebGLCubeRenderTarget(2048);
const cubeCamera = new THREE.CubeCamera(0.1, 100, cubeRenderTarget);
scene.add(cubeCamera);

const refractionMaterial = new THREE.MeshPhysicalMaterial({
    metalness: 0,
    roughness: 0.2,
    envMap: cubeRenderTarget.texture,
    refractionRatio: 1.0,
    transparent: true,
    transmission: .99,
    side: THREE.DoubleSide,
    clearcoat: 1.0,
    clearcoatRoughness: 0.39
});

const armMaterial = new THREE.MeshPhysicalMaterial({
    color: 0x444444,
    envMap: envTexture,
    metalness: 1,
    roughness: 0
});

const hingMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xF0E68C,
    envMap: envTexture,
    metalness: 1,
    roughness: 0
});

const frameRefraction = new THREE.MeshPhysicalMaterial({
    metalness: 1,
    roughness: 0,
    color: 0xffffff,
    envMap: cubeRenderTarget.texture,
    refractionRatio: 0.9,
    transparent: true,
    transmission: 0.0,
    side: THREE.FrontSide
});

const frameMaterial = new THREE.MeshPhysicalMaterial({
    color: 0xb2ffc8,
    envMap: envTexture,
    metalness: 1,
    roughness: 0,
    transparent: true,
    transmission: .66,
    side: THREE.BackSide,
});

cubeRenderTarget.texture.mapping = THREE.CubeRefractionMapping

let modelReady = false
let glasses = new THREE.Object3D
const glassesBody = new CANNON.Body({ mass: 1 })
const glTFLoader = new GLTFLoader()
let annotationCounter = 0

glTFLoader.load('models/glasses.glb', (gltf) => {
    gltf.scene.traverse(function (child) {
        if ((<THREE.Mesh>child).isMesh) {
            const mesh = (<THREE.Mesh>child).clone();
            mesh.rotation.x = 0;
            if (mesh.name.endsWith("Lens")) {
                mesh.material = refractionMaterial;
                glasses.add(mesh);
                glassesBody.addShape(gemoetryToShape(mesh.geometry as THREE.BufferGeometry));
            }
            else if (mesh.name.endsWith("hinge")) {
                mesh.material = hingMaterial;
                glasses.add(mesh);
                glassesBody.addShape(gemoetryToShape(mesh.geometry as THREE.BufferGeometry));
            }
            else if (mesh.name.endsWith("frame")) {
                mesh.material = frameRefraction;
                glasses.add(mesh);
                const newMesh = new THREE.Mesh(mesh.geometry.clone(), frameMaterial);
                newMesh.rotation.copy(mesh.rotation);
                glasses.add(newMesh);
                const shape = gemoetryToShape(mesh.geometry as THREE.BufferGeometry);
                glassesBody.addShape(shape);
            }
            else if (mesh.name.endsWith("Arm")) {
                mesh.material = armMaterial;
                glasses.add(mesh);
                glassesBody.addShape(gemoetryToShape(mesh.geometry as THREE.BufferGeometry));
            }
        }
        else if (child.isObject3D) {
            if (child.name.startsWith("Annotation")) {
                const aId = (annotationCounter++).toString();
                annotations[aId] = { title: child.userData.title, description: child.userData.description };
                const annotationSpriteMaterial = new THREE.SpriteMaterial({
                    map: circleTexture,
                    depthTest: false,
                    depthWrite: false,
                    sizeAttenuation: false
                });
                const annotationSprite = new THREE.Sprite(annotationSpriteMaterial);
                annotationSprite.scale.set(6.6, 6.6, 6.6);
                //changing from blender annotation coords to threejs coords
                const tmpY = -child.position.y
                child.position.y = child.position.z
                child.position.z = tmpY
                child.getWorldPosition(annotationSprite.position);
                annotationSprite.userData.id = aId;
                glasses.add(annotationSprite);
                annotationSprite.layers.set(1);
                annotationMarkers.push(annotationSprite);
                const annotationDiv = document.createElement('div');
                annotationDiv.className = 'annotationLabel';
                annotationDiv.innerHTML = aId;
                const annotationLabel = new CSS2DObject(annotationDiv);
                annotationLabel.position.copy(annotationSprite.position);
                glasses.add(annotationLabel);
                if (child.userData.title) {
                    const annotationTextDiv = document.createElement('div');
                    annotationTextDiv.className = 'annotationDescription';
                    annotationTextDiv.innerHTML = child.userData.title;
                    if (child.userData.description) {
                        annotationTextDiv.innerHTML += "<p>" + child.userData.description + "</p>";
                    }
                    annotationDiv.appendChild(annotationTextDiv);
                    annotations[aId].descriptionDomElement = annotationTextDiv;
                }
            }
        }
    });

    glasses.scale.set(.01, .01, .01)
    scene.add(glasses);

    glassesBody.position.y = 5;
    glassesBody.quaternion.x = Math.PI / 4;
    glassesBody.quaternion.z = -Math.PI / 7;
    glassesBody.sleepSpeedLimit = .1;
    world.addBody(glassesBody);

    modelReady = true;
}, (xhr) => {
    console.log((xhr.loaded / xhr.total * 100) + '% loaded')
}, (error) => {
    console.log(error);
});

function gemoetryToShape(geometry: THREE.BufferGeometry) {
    const convexHull = new ConvexBufferGeometry(new THREE.Geometry().fromBufferGeometry(geometry).vertices);
    const shape = CannonUtils.CreateTrimesh(convexHull.scale(.01, .01, .01));
    return shape;
}

window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
    labelRenderer.setSize(window.innerWidth, window.innerHeight);
    render();
}

const raycaster = new THREE.Raycaster();
raycaster.layers.set(1);

renderer.domElement.addEventListener('pointerdown', onClick, false);

function onClick(event: MouseEvent) {
    raycaster.setFromCamera({
        x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
        y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1
    }, camera);
    const intersects = raycaster.intersectObjects(annotationMarkers, true);
    if (intersects.length > 0) {
        if (intersects[0].object.userData && intersects[0].object.userData.id) {
            const p = intersects[0].point;
            const diffVec3 = p.clone().sub(controls.target);
            const camTo = camera.position.clone().add(diffVec3);
            new TWEEN.Tween(controls.target)
                .to({
                    x: p.x,
                    y: p.y,
                    z: p.z
                }, 500)
                .easing(TWEEN.Easing.Cubic.Out)
                .start();
            new TWEEN.Tween(camera.position)
                .to({
                    x: camTo.x,
                    y: camTo.y,
                    z: camTo.z
                }, 500)
                .easing(TWEEN.Easing.Cubic.Out)
                .start();
            Object.keys(annotations).forEach(annotation => {
                if (annotations[annotation].descriptionDomElement) {
                    (annotations[annotation].descriptionDomElement as HTMLDivElement).style.display = "none";
                }
            });
            if (annotations[intersects[0].object.userData.id].descriptionDomElement) {
                (annotations[intersects[0].object.userData.id].descriptionDomElement as HTMLDivElement).style.display = "block";
            }
        }
    }
}
const gui = new GUI();
const lensFolder = gui.addFolder("Lenses");
lensFolder.add(refractionMaterial, "opacity", 0, 1.0, 0.01).name("Opacity");
lensFolder.add(refractionMaterial, "metalness", 0, 1.0, 0.01).name("Metalness");
lensFolder.add(refractionMaterial, "roughness", 0, 1.0, 0.01).name("Roughness");
lensFolder.add(refractionMaterial, "transmission", 0, 1.0, 0.01).name("Transmission");
lensFolder.add(refractionMaterial, "clearcoat", 0, 1.0, 0.01).name("Clearcoat");
lensFolder.add(refractionMaterial, "clearcoatRoughness", 0, 1.0, 0.01).name("ClearcoatRoughness");
lensFolder.open();

const framesFolder = gui.addFolder("Frames");
framesFolder.add(frameRefraction, "opacity", 0, 1.0, 0.01).name("Opacity");
framesFolder.add(frameRefraction, "metalness", 0, 1.0, 0.01).name("Metalness");
framesFolder.add(frameRefraction, "roughness", 0, 1.0, 0.01).name("Roughness");
framesFolder.add(frameRefraction, "transmission", 0, 1.0, 0.01).name("Transmission");
framesFolder.add(frameRefraction, "refractionRatio", 0, 1.0, 0.01).name("RefractionRatio");
framesFolder.open()

const stats = Stats();
document.body.appendChild(stats.dom);

const clock = new THREE.Clock();

var animate = function () {
    requestAnimationFrame(animate);

    controls.update();

    TWEEN.update();

    let delta = clock.getDelta();
    if (delta > .1)
        delta = .1;
    world.step(delta);

    if (modelReady) {
        glasses.position.set(glassesBody.position.x, glassesBody.position.y, glassesBody.position.z);
        glasses.quaternion.set(glassesBody.quaternion.x, glassesBody.quaternion.y, glassesBody.quaternion.z, glassesBody.quaternion.w);
    }

    render();

    stats.update();
};

function render() {
    if (modelReady) {
        cubeCamera.position.copy(camera.position);
        camera.layers.disable(1);
        cubeCamera.update(renderer, scene);
        camera.layers.enable(1);
    }
    renderer.render(scene, camera);
    labelRenderer.render(scene, camera);
}
animate();

./dist/client/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>

<head>
    <title>Three.js TypeScript Tutorials by Sean Bradley</title>
    <style>
        body {
            overflow: hidden;
            margin: 0px;
        }

        .annotationLabel {
            color: #ffffff;
            font-family: monospace;
            pointer-events: none;
            font-size: 17px;
        }

        .annotationDescription {
            color: #ffffff;
            font-family: monospace;
            pointer-events: none;
            font-size: 14px;
            position: absolute;
            left: 25px;
            padding: 1em;
            width: 200px;
            background: rgba(0, 0, 0, 0.66);
            border-radius: .5em;
            transition: opacity .5s;
            display: none;
        }
    </style>
</head>

<body>
    <script type="module" src="client.js"></script>
</body>

</html>