Examples : RNG

Description

Demonstrates using physics container and compound shapes.

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
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/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/loaders/OBJLoader', express.static(path.join(__dirname, '../../node_modules/three/examples/jsm/loaders/OBJLoader.js')))
        app.use('/cannon/cannon.min', express.static(path.join(__dirname, '../../node_modules/cannon/build/cannon.min.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
import * as THREE from '/build/three.module.js'
import { OrbitControls } from '/jsm/controls/OrbitControls'
import Stats from '/jsm/libs/stats.module'
import { GUI } from '/jsm/libs/dat.gui.module'
import '/cannon/cannon.min'
import CannonUtils from './utils/cannonUtils.js'
import { OBJLoader } from '/jsm/loaders/OBJLoader'

const scene: THREE.Scene = new THREE.Scene()

const light1 = new THREE.SpotLight();
light1.position.set(10, 10, 10)
light1.angle = Math.PI / 4
light1.penumbra = 0.15
light1.castShadow = true;
light1.shadow.mapSize.width = 1024;
light1.shadow.mapSize.height = 1024;
light1.shadow.camera.near = 0.5;
light1.shadow.camera.far = 50
scene.add(light1);

const light2 = new THREE.SpotLight();
light2.position.set(-10, 10, 10)
light2.angle = Math.PI / 4
light2.penumbra = 0.15
light2.castShadow = true;
light2.shadow.mapSize.width = 1024;
light2.shadow.mapSize.height = 1024;
light2.shadow.camera.near = 0.5;
light2.shadow.camera.far = 50
scene.add(light2);

const camera: THREE.PerspectiveCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.x = 4
camera.position.y = 6
camera.position.z = 7

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

const controls = new OrbitControls(camera, renderer.domElement)
controls.screenSpacePanning = true
controls.target.y = 5

const world = new CANNON.World()
world.gravity.set(0, -9.82, 0)
//world.broadphase = new CANNON.NaiveBroadphase() //
//world.solver.iterations = 10
//world.allowSleep = true

const basicMaterial: THREE.MeshBasicMaterial = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide })
const normalMaterial: THREE.MeshNormalMaterial = new THREE.MeshNormalMaterial({ side: THREE.DoubleSide, wireframe: true })
const phongMaterial: THREE.MeshPhongMaterial = new THREE.MeshPhongMaterial()
const railMaterial: THREE.MeshPhysicalMaterial = new THREE.MeshPhysicalMaterial()
railMaterial.color = new THREE.Color("#ffffff")
railMaterial.reflectivity = 0
railMaterial.refractionRatio = 0
railMaterial.roughness = 0.2
railMaterial.metalness = 1
railMaterial.clearcoat = 0.15
railMaterial.clearcoatRoughness = 0.5
railMaterial.side = THREE.DoubleSide

const inverseSphereMaterial: THREE.MeshPhysicalMaterial = new THREE.MeshPhysicalMaterial();
inverseSphereMaterial.color = new THREE.Color("#ffffff")
inverseSphereMaterial.reflectivity = 0
inverseSphereMaterial.refractionRatio = 0.1
inverseSphereMaterial.roughness = 0
inverseSphereMaterial.metalness = 0.16
inverseSphereMaterial.clearcoat = 0.1
inverseSphereMaterial.clearcoatRoughness = 0.5
inverseSphereMaterial.transmission = 1.0
inverseSphereMaterial.opacity = 1
inverseSphereMaterial.transparent = true
inverseSphereMaterial.side = THREE.DoubleSide

const envTexture = new THREE.CubeTextureLoader().load(["img/px_50.png", "img/nx_50.png", "img/py_50.png", "img/ny_50.png", "img/pz_50.png", "img/nz_50.png"])
envTexture.mapping = THREE.CubeReflectionMapping
inverseSphereMaterial.envMap = envTexture

const ballMaterial: THREE.MeshPhysicalMaterial[] = new Array()
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/1-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/2-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/3-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/4-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/5-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/6-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/7-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/8-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/9-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))
ballMaterial.push(new THREE.MeshPhysicalMaterial({ map: new THREE.TextureLoader().load("img/10-ball.jpg"), roughness: 0.88, metalness: 1.0, clearcoat: 0.3, clearcoatRoughness: 0.15, envMap: envTexture }))


const positions = [
    [-2, 3, 0],
    [0, 3, 0],
    [2, 3, 0],
    [0, 3, -2],
    [0, 3, 2],
    [-2, 6, 0],
    [.5, 8, .5],
    [2, 6, 0],
    [0, 6, -2],
    [0, 6, 2]
]
const sphereMesh: THREE.Mesh[] = new Array()
const sphereBody: CANNON.Body[] = new Array()
for (let i = 0; i < 10; i++) {
    const sphereGeometry: THREE.SphereGeometry = new THREE.SphereGeometry(1, 16, 16)
    sphereMesh.push(new THREE.Mesh(sphereGeometry, ballMaterial[i]))
    sphereMesh[i].position.x = positions[i][0]
    sphereMesh[i].position.y = positions[i][1]
    sphereMesh[i].position.z = positions[i][2]
    sphereMesh[i].castShadow = true
    sphereMesh[i].receiveShadow = true
    scene.add(sphereMesh[i])
    const sphereShape = new CANNON.Sphere(1)
    sphereBody.push(new CANNON.Body({ mass: 1 }))
    sphereBody[i].addShape(sphereShape)
    sphereBody[i].position.x = sphereMesh[i].position.x
    sphereBody[i].position.y = sphereMesh[i].position.y
    sphereBody[i].position.z = sphereMesh[i].position.z
    world.addBody(sphereBody[i])
}


let inverseSphere: THREE.Object3D
let inverseSphereBody: CANNON.Body
let innerRail: THREE.Object3D
let innerRailBody: CANNON.Body
let outerRail: THREE.Object3D
let modelLoaded: Boolean = false
const objLoader: OBJLoader = new OBJLoader();
objLoader.load(
    'models/inverseSphere4.obj',
    (object) => {
        object.traverse(function (child) {
            if ((<THREE.Mesh>child).isMesh) {
                //      (<THREE.Mesh>child).material = material
                //  }
                // })
                //if (child instanceof THREE.Mesh) {
                //console.dir(child)
                if (child.name.startsWith("sphere")) {
                    //scene.add(child)
                    //     console.log(child.name)

                    inverseSphere = child;
                    (inverseSphere as THREE.Mesh).material = inverseSphereMaterial;
                    inverseSphere.position.x = 0;
                    inverseSphere.position.y = 5;

                    var constraintBody = new CANNON.Body({ mass: 0 })
                    constraintBody.addShape(new CANNON.Sphere(.01))
                    constraintBody.position.set(0, 5, 0);
                    world.addBody(constraintBody);

                    const shape = CannonUtils.CreateTrimesh((inverseSphere as THREE.Mesh).geometry)
                    inverseSphereBody = new CANNON.Body({ mass: 100 });
                    inverseSphereBody.addShape(shape)
                    inverseSphereBody.position.x = inverseSphere.position.x
                    inverseSphereBody.position.y = inverseSphere.position.y
                    inverseSphereBody.position.z = inverseSphere.position.z
                    world.addBody(inverseSphereBody)

                    const c = new CANNON.PointToPointConstraint(constraintBody, new CANNON.Vec3(0, 0, 0), inverseSphereBody, new CANNON.Vec3(0, 0, 0));
                    world.addConstraint(c);


                } else if (child.name.startsWith("outerRail_")) {
                    //     //     console.log(child.name)

                    outerRail = child;
                    (outerRail as THREE.Mesh).material = railMaterial
                    outerRail.position.y = 5

                    const outerRailShape = CannonUtils.CreateTrimesh((outerRail as THREE.Mesh).geometry)
                    const outerRailBody = new CANNON.Body({ mass: 0 })
                    outerRailBody.addShape(outerRailShape)
                    outerRailBody.position.set(0, 5, 0);
                    world.addBody(outerRailBody);
                } else if (child.name.startsWith("innerRail_")) {
                    console.log(child.name)
                    innerRail = child;
                    (innerRail as THREE.Mesh).material = railMaterial
                    innerRail.position.y = 5
                    const innerRailShape = CannonUtils.CreateTrimesh((innerRail as THREE.Mesh).geometry)
                    //innerRailBody = new CANNON.Body({ mass: 0.01 })
                    //innerRailBody.addShape(innerRailShape)
                    //innerRailBody.position.set(0, 5, 0);
                    //world.addBody(innerRailBody);
                    inverseSphereBody.addShape(innerRailShape)

                }

            }
        })
        scene.add(inverseSphere)
        scene.add(outerRail)
        scene.add(innerRail)

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

const planeGeometry: THREE.PlaneGeometry = new THREE.PlaneGeometry(25, 25)
const planeMesh: THREE.Mesh = new THREE.Mesh(planeGeometry, phongMaterial)
planeMesh.rotateX(-Math.PI / 2)
planeMesh.receiveShadow = true;
scene.add(planeMesh)

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

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

const gui = new GUI()
const physicsFolder = gui.addFolder("Physics")
physicsFolder.add(world.gravity, "x", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "y", -10.0, 10.0, 0.1)
physicsFolder.add(world.gravity, "z", -10.0, 10.0, 0.1)

const materialFolder = gui.addFolder('THREE.Material')
materialFolder.add(inverseSphereMaterial, 'transparent')
materialFolder.add(inverseSphereMaterial, 'opacity', 0, 1, 0.01)

const InverseSphereMaterialFolder = gui.addFolder('InverseSphereMaterial');
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'reflectivity', 0, 1, 0.01);
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'refractionRatio', 0, 1, 0.01);
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'roughness', 0, 1, 0.01);
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'metalness', 0, 1, 0.01);
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'clearcoat', 0, 1, 0.01)
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'clearcoatRoughness', 0, 1, 0.01)
InverseSphereMaterialFolder.add(inverseSphereMaterial, 'transmission', 0, 1, 0.01)
//InverseSphereMaterialFolder.open()

// const ballMaterialFolder = gui.addFolder('BallMaterial');
// ballMaterialFolder.add(ballMaterial, 'reflectivity', 0, 1, 0.01);
// ballMaterialFolder.add(ballMaterial, 'refractionRatio', 0, 1, 0.01);
// ballMaterialFolder.add(ballMaterial, 'roughness', 0.0, 1.0, 0.01);
// ballMaterialFolder.add(ballMaterial, 'metalness', 0, 1, 0.01);
// ballMaterialFolder.add(ballMaterial, 'clearcoat', 0, 1, 0.01)
// ballMaterialFolder.add(ballMaterial, 'clearcoatRoughness', 0, 1, 0.01)

const railMaterialFolder = gui.addFolder('RailMaterial');
railMaterialFolder.add(railMaterial, 'reflectivity', 0, 1, 0.01);
railMaterialFolder.add(railMaterial, 'refractionRatio', 0, 1, 0.01);
railMaterialFolder.add(railMaterial, 'roughness', 0.0, 1.0, 0.01);
railMaterialFolder.add(railMaterial, 'metalness', 0, 1, 0.01);
railMaterialFolder.add(railMaterial, 'clearcoat', 0, 1, 0.01)
railMaterialFolder.add(railMaterial, 'clearcoatRoughness', 0, 1, 0.01)
//railMaterialFolder.open()

const clock: THREE.Clock = new THREE.Clock()

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

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

    for (let i = 0; i < 10; i++) {
        sphereMesh[i].position.set(sphereBody[i].position.x, sphereBody[i].position.y, sphereBody[i].position.z);
        sphereMesh[i].quaternion.set(sphereBody[i].quaternion.x, sphereBody[i].quaternion.y, sphereBody[i].quaternion.z, sphereBody[i].quaternion.w);
    }

    if (modelLoaded) {
        inverseSphereBody.angularVelocity.set(0, 0, -.5)
        inverseSphere.position.set(inverseSphereBody.position.x, inverseSphereBody.position.y, inverseSphereBody.position.z);
        inverseSphere.quaternion.set(inverseSphereBody.quaternion.x, inverseSphereBody.quaternion.y, inverseSphereBody.quaternion.z, inverseSphereBody.quaternion.w);

        // innerRailBody.angularVelocity.set(0, 0, -.5)
        innerRail.position.set(inverseSphereBody.position.x, inverseSphereBody.position.y, inverseSphereBody.position.z);
        innerRail.quaternion.set(inverseSphereBody.quaternion.x, inverseSphereBody.quaternion.y, inverseSphereBody.quaternion.z, inverseSphereBody.quaternion.w);

    }

    render()

    stats.update()
};

function render() {
    renderer.render(scene, camera)
}
animate();